diff --git a/.bumpversion.cfg b/.bumpversion.cfg index bed73ed9ee..b0e705d75e 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,6 +1,6 @@ [bumpversion] -current_version = 68.1.2 +current_version = 82.0.1 commit = True tag = True -[bumpversion:file:setup.cfg] +[bumpversion:file:pyproject.toml] diff --git a/.coveragerc b/.coveragerc index 0402a8c61f..be34df9d9d 100644 --- a/.coveragerc +++ b/.coveragerc @@ -2,6 +2,15 @@ omit = # leading `*/` for pytest-dev/pytest-cov#456 */.tox/* + + # local + */_vendor/* + */tools/* + */setuptools/_distutils/* + # See #4588 for integration tests coverage + */setuptools/tests/integration/* + */setuptools/tests/test_integration.py + disable_warnings = couldnt-parse @@ -10,3 +19,9 @@ disable_warnings = [report] show_missing = True +exclude_also = + # Exclude common false positives per + # https://coverage.readthedocs.io/en/latest/excluding.html#advanced-exclusion + # Ref jaraco/skeleton#97 and jaraco/skeleton#135 + class .*\bProtocol\): + if TYPE_CHECKING: diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml index 1c42bf5a94..ff45e687c9 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.yml +++ b/.github/ISSUE_TEMPLATE/bug-report.yml @@ -45,13 +45,25 @@ body: - type: input attributes: label: setuptools version - placeholder: For example, setuptools===60.4.2 + placeholder: For example, setuptools==69.1.0 + description: >- + Please also test with the **latest version** of `setuptools`. + + Typically, this involves modifying `requires` in `[build-system]` of + [`pyproject.toml`](https://setuptools.pypa.io/en/latest/userguide/quickstart.html#basic-use), + not just updating `setuptools` using `pip`. validations: required: true - type: input attributes: label: Python version placeholder: For example, Python 3.10 + description: >- + Please ensure you are using a [supported version of Python](https://devguide.python.org/versions/#supported-versions). + + Setuptools does not support versions that have reached [`end-of-life`](https://devguide.python.org/versions/#unsupported-versions). + + Support for versions of Python under development (i.e. without a stable release) is experimental. validations: required: true - type: input @@ -95,7 +107,7 @@ body: label: How to Reproduce description: >- Describe the steps to reproduce this bug. - + Please try to create a [minimal reproducer](https://stackoverflow.com/help/minimal-reproducible-example), and avoid things like "see the steps in the CI logs". placeholder: | diff --git a/.github/ISSUE_TEMPLATE/distutils-deprecation.yml b/.github/ISSUE_TEMPLATE/distutils-deprecation.yml new file mode 100644 index 0000000000..7ac1f8bbb9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/distutils-deprecation.yml @@ -0,0 +1,103 @@ +--- +name: 📇 Distutils Deprecation Report +description: >- + Report a use-case affected by the deprecation of distutils +labels: +- distutils deprecation +- Needs Triage +projects: +- pypa/6 +body: +- type: markdown + attributes: + value: > + So you've encountered an issue with the deprecation of distutils. + + First, sorry for the inconvenience while we work to untangle the + legacy which is setuptools/distutils. Our goal is to ensure that + the vast majority of use cases are satisfied prior to removing + the legacy support. + + Please check the + [existing reports](https://github.com/pypa/setuptools/issues?q=label%3A%22distutils+deprecation%22+) + to see if the affecting condition has been reported previously. + +- type: markdown + attributes: + value: >- + **Environment** +- type: input + attributes: + label: setuptools version + placeholder: For example, setuptools==69.1.0 + description: >- + Please also test with the **latest version** of `setuptools`. + + Typically, this involves modifying `requires` in `[build-system]` of + [`pyproject.toml`](https://setuptools.pypa.io/en/latest/userguide/quickstart.html#basic-use), + not just updating `setuptools` using `pip`. + validations: + required: true +- type: input + attributes: + label: Python version + placeholder: For example, Python 3.10 + description: >- + Please ensure you are using a [supported version of Python](https://devguide.python.org/versions/#supported-versions). + + Setuptools does not support versions that have reached [`end-of-life`](https://devguide.python.org/versions/#unsupported-versions). + + Support for versions of Python under development (i.e. without a stable release) is experimental. + validations: + required: true +- type: input + attributes: + label: OS + placeholder: For example, Gentoo Linux, RHEL 8, Arch Linux, macOS etc. + validations: + required: true +- type: textarea + attributes: + label: Additional environment information + description: >- + Feel free to add more information about your environment here. + placeholder: >- + This is only happening when I run setuptools on my fridge's patched firmware 🤯 + +- type: textarea + attributes: + label: Description + description: >- + A clear and concise description of the circumstances leading to the warning. + validations: + required: true + +- type: textarea + attributes: + label: How to Reproduce + description: >- + Describe the steps to reproduce the warning. + + Please try to create a [minimal reproducer](https://stackoverflow.com/help/minimal-reproducible-example), + and avoid things like "see the steps in the CI logs". + placeholder: | + 1. Clone a simplified example: `git clone ...` + 2. Create a virtual environment for isolation with `...` + 2. Build the project with setuptools via '...' + 2. Then run '...' + 3. An error occurs. + validations: + required: true + +- type: textarea + attributes: + label: Other detail + description: >- + Paste the output of the steps above, including the commands + themselves and setuptools' output/traceback etc. + value: | + ```console + + ``` + +... diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index 89ff33961b..0000000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,8 +0,0 @@ -version: 2 -updates: - - package-ecosystem: "pip" - directory: "/" - schedule: - interval: "daily" - allow: - - dependency-type: "all" diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index c4458c9825..9c88511a5e 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -13,6 +13,6 @@ Closes _(See [documentation][PR docs] for details)_ -[`newsfragments/`]: https://github.com/pypa/setuptools/tree/master/newsfragments +[`newsfragments/`]: https://github.com/pypa/setuptools/tree/main/newsfragments [PR docs]: https://setuptools.pypa.io/en/latest/development/developer-guide.html#making-a-pull-request diff --git a/.github/workflows/ci-sage.yml b/.github/workflows/ci-sage.yml index 8cb9e3827f..3da7141573 100644 --- a/.github/workflows/ci-sage.yml +++ b/.github/workflows/ci-sage.yml @@ -58,7 +58,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out ${{ env.SPKG }} - uses: actions/checkout@v2 + uses: actions/checkout@v4 with: path: build/pkgs/${{ env.SPKG }}/src - name: Install prerequisites @@ -70,18 +70,17 @@ jobs: run: | (cd build/pkgs/${{ env.SPKG }}/src && python3 -m build --sdist) \ && mkdir -p upstream && cp build/pkgs/${{ env.SPKG }}/src/dist/*.tar.gz upstream/${{ env.SPKG }}-git.tar.gz \ - && echo "sage-package create ${{ env.SPKG }} --version git --tarball ${{ env.SPKG }}-git.tar.gz --type=standard" > upstream/update-pkgs.sh \ + && echo "sage-package create ${{ env.SPKG }} --pypi --source normal --type standard; sage-package create ${{ env.SPKG }} --version git --tarball ${{ env.SPKG }}-git.tar.gz --type=standard" > upstream/update-pkgs.sh \ && if [ -n "${{ env.REMOVE_PATCHES }}" ]; then echo "(cd ../build/pkgs/${{ env.SPKG }}/patches && rm -f ${{ env.REMOVE_PATCHES }}; :)" >> upstream/update-pkgs.sh; fi \ && ls -l upstream/ - - uses: actions/upload-artifact@v2 + - uses: actions/upload-artifact@v3 with: path: upstream name: upstream linux: # https://github.com/sagemath/sage/blob/develop/.github/workflows/docker.yml - # Use branch of ticket https://trac.sagemath.org/ticket/33288 - uses: sagemath/sagetrac-mirror/.github/workflows/docker.yml@u/mkoeppe/setuptools_ci_target + uses: sagemath/sage/.github/workflows/docker.yml@develop with: # Sage distribution packages to build targets: setuptools pyzmq @@ -89,11 +88,6 @@ jobs: sage_repo: sagemath/sage sage_ref: develop upstream_artifact: upstream - sage_trac_git: https://github.com/sagemath/sagetrac-mirror.git - # Test with the branch from https://trac.sagemath.org/ticket/33288 - # This may provide hotfixes for the CI that have not been merged into - # the sage develop branch yet. - sage_trac_ticket: 33288 # We prefix the image name with the SPKG name ("setuptools-") to avoid the error # 'Package "sage-docker-..." is already associated with another repository.' docker_push_repository: ghcr.io/${{ github.repository }}/setuptools- diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 43c96dbd16..5c6cc311fd 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -1,6 +1,16 @@ name: tests -on: [push, pull_request, workflow_dispatch] +on: + merge_group: + push: + branches-ignore: + # temporary GH branches relating to merge queues (jaraco/skeleton#93) + - gh-readonly-queue/** + tags: + # required if branches-ignore is supplied (jaraco/skeleton#103) + - '**' + pull_request: + workflow_dispatch: concurrency: group: >- @@ -13,74 +23,81 @@ permissions: contents: read env: - # Environment variables to support color support (jaraco/skeleton#66): - # Request colored output from CLI tools supporting it. Different tools - # interpret the value differently. For some, just being set is sufficient. - # For others, it must be a non-zero integer. For yet others, being set - # to a non-empty value is sufficient. For tox, it must be one of - # , 0, 1, false, no, off, on, true, yes. The only enabling value - # in common is "1". + # Environment variable to support color support (jaraco/skeleton#66) FORCE_COLOR: 1 - # MyPy's color enforcement (must be a non-zero number) - MYPY_FORCE_COLOR: -42 - # Recognized by the `py` package, dependency of `pytest` (must be "1") - PY_COLORS: 1 - # Make tox-wrapped tools see color requests - TOX_TESTENV_PASSENV: >- - FORCE_COLOR - MYPY_FORCE_COLOR - NO_COLOR - PY_COLORS - PYTEST_THEME - PYTEST_THEME_MODE # Suppress noisy pip warnings PIP_DISABLE_PIP_VERSION_CHECK: 'true' - PIP_NO_PYTHON_VERSION_WARNING: 'true' PIP_NO_WARN_SCRIPT_LOCATION: 'true' - # Disable the spinner, noise in GHA; TODO(webknjaz): Fix this upstream - # Must be "1". - TOX_PARALLEL_NO_SPINNER: 1 + # Ensure tests can sense settings about the environment + TOX_OVERRIDE: >- + testenv.pass_env+=GITHUB_*,FORCE_COLOR jobs: test: strategy: + # https://blog.jaraco.com/efficient-use-of-ci-resources/ matrix: python: - - "3.8" - - "3.11" - - "3.12" + - "3.10" + - ">=3.13.5" # temporary bound until it becomes the default, python/cpython#135151 platform: - ubuntu-latest - macos-latest - windows-latest include: - - python: "3.9" + - python: "3.11" platform: ubuntu-latest - - python: "3.10" + - python: "3.12" platform: ubuntu-latest - - python: pypy3.9 + - python: "3.14" + platform: ubuntu-latest + - python: "3.15" + platform: ubuntu-latest + - python: pypy3.10 platform: ubuntu-latest distutils: stdlib - platform: ubuntu-latest python: "3.10" distutils: stdlib runs-on: ${{ matrix.platform }} - continue-on-error: ${{ matrix.python == '3.12' }} + continue-on-error: ${{ matrix.python == '3.15' || matrix.python == 'pypy3.10' }} + # XXX: pypy seems to be flaky with unrelated tests in #6345 env: SETUPTOOLS_USE_DISTUTILS: ${{ matrix.distutils || 'local' }} timeout-minutes: 75 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + - name: Install build dependencies + # Install dependencies for building packages on pre-release Pythons + # jaraco/skeleton#161 + if: matrix.python == '3.15' && matrix.platform == 'ubuntu-latest' + run: | + sudo apt update + sudo apt install -y libxml2-dev libxslt-dev - name: Setup Python id: python-install - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python }} allow-prereleases: true - - uses: actions/cache@v3 + # Workaround for actions/setup-python#981 on macos + # Workaround for https://github.com/pypa/setuptools/issues/5143 on windows + # (env var only modified for this specific step) + env: + SETUPTOOLS_USE_DISTUTILS: >- + ${{ + ( + ( matrix.platform == 'macos-latest' || matrix.platform == 'windows-latest' ) + && matrix.python == '3.9' + && 'stdlib' + ) + || matrix.distutils + || 'local' + }} + - uses: actions/cache@v4 id: cache with: path: setuptools/tests/config/downloads/*.cfg @@ -91,9 +108,24 @@ jobs: if: steps.cache.outputs.cache-hit != 'true' working-directory: setuptools/tests/config run: python -m downloads.preload setupcfg_examples.txt - - name: Install tox + - name: Adjust env vars + shell: bash run: | - python -m pip install tox + echo 'PIPX_DEFAULT_PYTHON=${{ steps.python-install.outputs.python-path }}' >> $GITHUB_ENV + - name: Pre-build distributions for test + shell: bash + run: | + rm -rf dist + # workaround for pypa/setuptools#4333 + pipx run --pip-args 'pyproject-hooks!=1.1' build + echo "PRE_BUILT_SETUPTOOLS_SDIST=$(ls dist/*.tar.gz)" >> $GITHUB_ENV + echo "PRE_BUILT_SETUPTOOLS_WHEEL=$(ls dist/*.whl)" >> $GITHUB_ENV + rm -rf setuptools.egg-info # Avoid interfering with the other tests + - name: Workaround for unreleased PyNaCl (pyca/pynacl#805) + if: contains(matrix.python, 'pypy') + run: echo "SETUPTOOLS_ENFORCE_DEPRECATION=0" >> $GITHUB_ENV + - name: Install tox + run: python -m pip install tox - name: Run run: tox - name: Create coverage report @@ -101,7 +133,7 @@ jobs: run: pipx run coverage xml --ignore-errors - name: Publish coverage if: hashFiles('coverage.xml') != '' # Rudimentary `file.exists()` - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: >- # Mark which lines are covered by which envs CI-GHA, @@ -109,28 +141,37 @@ jobs: OS-${{ runner.os }}, VM-${{ matrix.platform }}, Py-${{ steps.python-install.outputs.python-version }} + token: ${{ secrets.CODECOV_TOKEN }} - docs: + collateral: + strategy: + fail-fast: false + matrix: + job: + - diffcov + - docs runs-on: ubuntu-latest - env: - TOXENV: docs steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + with: + fetch-depth: 0 - name: Setup Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 + with: + python-version: 3.x - name: Install tox - run: | - python -m pip install tox - - name: Run - run: tox + run: python -m pip install tox + - name: Eval ${{ matrix.job }} + run: tox -e ${{ matrix.job }} check: # This job does nothing and is only used for the branch protection if: always() needs: + - check-changed-folders - integration-test - test - - docs + - collateral - test_cygwin runs-on: ubuntu-latest @@ -139,43 +180,49 @@ jobs: - name: Decide whether the needed jobs succeeded or failed uses: re-actors/alls-green@release/v1 with: - allowed-skips: integration-test + allowed-skips: check-changed-folders, integration-test jobs: ${{ toJSON(needs) }} test_cygwin: strategy: matrix: python: - - 39 + - 312 platform: - windows-latest runs-on: ${{ matrix.platform }} timeout-minutes: 75 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Install Cygwin with Python - uses: cygwin/cygwin-install-action@v2 + uses: cygwin/cygwin-install-action@v4 with: platform: x86_64 packages: >- python${{ matrix.python }}, python${{ matrix.python }}-devel, - python${{ matrix.python }}-tox, + python${{ matrix.python }}-pip, gcc-core, git, - name: Record the currently selected Python version id: python-install - # NOTE: This roughly emulates what `actions/setup-python@v4` provides + # NOTE: This roughly emulates what `actions/setup-python` provides # NOTE: except the action gets the version from the installation path # NOTE: on disk and we get it from runtime. run: | python -c 'import platform; print("python-version=" + platform.python_version())' >> ${GITHUB_OUTPUT} shell: C:\cygwin\bin\env.exe CYGWIN_NOWINPATH=1 CHERE_INVOKING=1 C:\cygwin\bin\bash.exe -leo pipefail -o igncr {0} + - name: Install tox using pip + shell: C:\cygwin\bin\env.exe CYGWIN_NOWINPATH=1 CHERE_INVOKING=1 C:\cygwin\bin\bash.exe -leo pipefail -o igncr {0} + run: | + # Workaround for https://github.com/pypa/setuptools/issues/4831 + python -m pip install tox - name: Run tests shell: C:\cygwin\bin\env.exe CYGWIN_NOWINPATH=1 CHERE_INVOKING=1 C:\cygwin\bin\bash.exe -leo pipefail -o igncr {0} run: | - git config --global --add safe.directory "$(cygpath -u "$GITHUB_WORKSPACE")" # workaround for #3408 - tox + git config --global --add safe.directory "$(cygpath -u "${{ github.workspace }}")" # workaround for #3408 + echo "$(cygpath -u "${{ github.workspace }}")" # for debugging purposes + python -m tox - name: Create coverage report if: hashFiles('.coverage') != '' # Rudimentary `file.exists()` run: | @@ -184,16 +231,47 @@ jobs: shell: C:\cygwin\bin\env.exe CYGWIN_NOWINPATH=1 CHERE_INVOKING=1 C:\cygwin\bin\bash.exe -leo pipefail -o igncr {0} - name: Publish coverage if: hashFiles('coverage.xml') != '' # Rudimentary `file.exists()` - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: - files: >- - ${{ github.workspace }}\coverage.xml flags: >- # Mark which lines are covered by which envs CI-GHA, ${{ github.job }}, OS-${{ runner.os }}, VM-${{ matrix.platform }}, Py-${{ steps.python-install.outputs.python-version }} + token: ${{ secrets.CODECOV_TOKEN }} + + check-changed-folders: + name: Fail the job if files changed under _disutils/_vendor folders + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: Check if files changed in the _distutils folder + id: changed-files-specific-distutils + uses: tj-actions/changed-files@v46 + with: + files: | + setuptools/_distutils/** + - name: Check if files changed in the _vendor folder + id: changed-files-specific-vendor + uses: tj-actions/changed-files@v46 + with: + files: | + setuptools/_vendor/** + - name: Fail the job if any file(s) in the _distutils folder change + if: steps.changed-files-specific-distutils.outputs.any_changed == 'true' + run: | + echo "One or more files in the setuptools/_distutils folder has changed." | tee "${GITHUB_STEP_SUMMARY}" + exit 1 + - name: Fail the job if any file(s) in the _vendor folder change + if: steps.changed-files-specific-vendor.outputs.any_changed == 'true' + run: | + echo "One or more files in the setuptools/_vendor folder has changed." | tee "${GITHUB_STEP_SUMMARY}" + exit 1 integration-test: needs: test @@ -208,13 +286,13 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 75 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Install OS-level dependencies run: | sudo apt-get update sudo apt-get install build-essential gfortran libopenblas-dev libyaml-dev - name: Setup Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: # Use a release that is not very new but still have a long life: python-version: "3.10" @@ -229,18 +307,20 @@ jobs: contents: write needs: - check - if: github.event_name == 'push' && contains(github.ref, 'refs/tags/') + if: >- # `always()` prevents auto-cancellation when previous steps are skipped (#5151): + always() + && needs.check.result == 'success' + && github.event_name == 'push' && github.ref_type == 'tag' runs-on: ubuntu-latest timeout-minutes: 75 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Setup Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: 3.x - name: Install tox - run: | - python -m pip install tox + run: python -m pip install tox - name: Run run: tox -e release env: diff --git a/.github/workflows/pyright.yml b/.github/workflows/pyright.yml new file mode 100644 index 0000000000..785bd2f198 --- /dev/null +++ b/.github/workflows/pyright.yml @@ -0,0 +1,77 @@ +# Split workflow file to not interfere with skeleton +name: pyright + +on: + merge_group: + push: + branches-ignore: + # temporary GH branches relating to merge queues (jaraco/skeleton#93) + - gh-readonly-queue/** + tags: + # required if branches-ignore is supplied (jaraco/skeleton#103) + - "**" + pull_request: + workflow_dispatch: + +concurrency: + group: >- + ${{ github.workflow }}- + ${{ github.ref_type }}- + ${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: true + +env: + # pin pyright version so a new version doesn't suddenly cause the CI to fail, + # until types-setuptools is removed from typeshed. + # For help with static-typing issues, or pyright update, ping @Avasam + # + # An exact version from https://github.com/microsoft/pyright/releases or "latest" + PYRIGHT_VERSION: "1.1.385" + + # Environment variable to support color support (jaraco/skeleton#66) + FORCE_COLOR: 1 + + # Suppress noisy pip warnings + PIP_DISABLE_PIP_VERSION_CHECK: "true" + PIP_NO_PYTHON_VERSION_WARNING: "true" + PIP_NO_WARN_SCRIPT_LOCATION: "true" + +jobs: + pyright: + strategy: + # https://blog.jaraco.com/efficient-use-of-ci-resources/ + matrix: + python: + - "3.10" + - "3.14" + platform: + - ubuntu-latest + runs-on: ${{ matrix.platform }} + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + allow-prereleases: true + - name: Install typed dependencies + run: python -m pip install -e .[core,type] + - name: Inform how to run locally + run: | + echo 'To run this test locally with npm pre-installed, run:' + echo '> npx -y pyright@${{ env.PYRIGHT_VERSION }} --threads' + echo 'You can also instead install "Pyright for Python" which will install npm for you:' + if [ '$PYRIGHT_VERSION' == 'latest' ]; then + echo '> pip install -U' + else + echo '> pip install pyright==${{ env.PYRIGHT_VERSION }}' + fi + echo '> pyright --threads' + shell: bash + - name: Run pyright + uses: jakebailey/pyright-action@v2 + with: + version: ${{ env.PYRIGHT_VERSION }} + python-version: ${{ matrix.python }} + extra-args: --threads diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 90ae80505e..0000000000 --- a/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -# syntax: glob -bin -build -dist -docs/build -include -lib -distribute.egg-info -setuptools.egg-info -.coverage -.eggs -.tox -.venv -*.egg -*.py[cod] -*.swp -*~ -.hg* -.cache -.idea/ -.pytest_cache/ -.mypy_cache/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000000..9cc4a33775 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,7 @@ +repos: +- repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.15.0 + hooks: + - id: ruff-check + args: [--fix, --unsafe-fixes] + - id: ruff-format diff --git a/.readthedocs.yaml b/.readthedocs.yaml index 053c728715..724370638f 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -3,10 +3,17 @@ python: install: - path: . extra_requirements: - - docs + - doc + +sphinx: + configuration: docs/conf.py # required boilerplate readthedocs/readthedocs.org#10401 build: - os: ubuntu-22.04 + os: ubuntu-lts-latest tools: - python: "3" + python: latest + # post-checkout job to ensure the clone isn't shallow jaraco/skeleton#114 + jobs: + post_checkout: + - git fetch --unshallow || true diff --git a/MANIFEST.in b/MANIFEST.in index 116840bfa2..7266e23fd0 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -2,18 +2,18 @@ recursive-include setuptools *.py *.exe *.xml *.tmpl recursive-include tests *.py recursive-include setuptools/tests *.html recursive-include docs *.py *.txt *.rst *.conf *.css *.css_t Makefile indexsidebar.html -recursive-include setuptools/_vendor *.py *.txt -recursive-include pkg_resources *.py *.txt -recursive-include pkg_resources/tests/data * +recursive-include setuptools/_vendor * recursive-include tools * recursive-include newsfragments * include *.py include *.rst include MANIFEST.in -include LICENSE +global-include LICEN[CS]E* COPYING* NOTICE* AUTHORS* include launcher.c include msvc-build-launcher.cmd +include mypy.ini include pytest.ini include tox.ini include setuptools/tests/config/setupcfg_examples.txt +include setuptools/config/*.schema.json global-exclude *.py[cod] __pycache__ diff --git a/NEWS.rst b/NEWS.rst index 2c5e02ff43..0b797c6ec0 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -1,3 +1,1264 @@ +v82.0.1 +======= + +Bugfixes +-------- + +- Fix the loading of ``launcher manifest.xml`` file. (#5047) +- Replaced deprecated ``json.__version__`` with fixture in tests. (#5186) + + +Improved Documentation +---------------------- + +- Add advice about how to improve predictability when installing sdists. (#5168) + + +Misc +---- + +- #4941, #5157, #5169, #5175 + + +v82.0.0 +======= + +Deprecations and Removals +------------------------- + +- ``pkg_resources`` has been removed from Setuptools. Most common uses of ``pkg_resources`` have been superseded by the `importlib.resources `_ and `importlib.metadata `_ projects. Projects and environments relying on ``pkg_resources`` for namespace packages or other behavior should depend on older versions of ``setuptools``. (#3085) + + +v81.0.0 +======= + +Deprecations and Removals +------------------------- + +- Removed support for the --dry-run parameter to setup.py. This one feature by its nature threads through lots of core and ancillary functionality, adding complexity and friction. Removal of this parameter will help decouple the compiler functionality from distutils and thus the eventual full integration of distutils. These changes do affect some class and function signatures, so any derivative functionality may require some compatibility shims to support their expected interface. Please report any issues to the Setuptools project for investigation. (#4872) + + +v80.10.2 +======== + +Bugfixes +-------- + +- Update vendored dependencies. (#5159) + + +Misc +---- + +- #5115, #5128 + + +v80.10.1 +======== + +Misc +---- + +- #5152 + + +v80.10.0 +======== + +Features +-------- + +- Remove post-release tags on setuptools' own build. (#4530) +- Refreshed vendored dependencies. (#5139) + + +Misc +---- + +- #5033 + + +v80.9.0 +======= + +Features +-------- + +- Set a deadline for the removal of pkg_resources later this year (December). (#3085) +- Removed reliance on pkg_resources in test_wheel. (#3085) + + +v80.8.0 +======= + +Features +-------- + +- Replaced more references to pkg_resources with importlib equivalents in wheel odule. (#3085) +- Restore explicit LICENSE file. (#5001) +- Removed no longer used build dependency on ``coherent.licensed``. (#5003) + + +v80.7.1 +======= + +Bugfixes +-------- + +- Only attempt to fetch eggs for unsatisfied requirements. (#4998) +- In installer, when discovering egg dists, let metadata discovery search each egg. (#4998) + + +v80.7.0 +======= + +Features +-------- + +- Removed usage of pkg_resources from installer. Set an official deadline on the installer deprecation to 2025-10-31. (#4997) + + +Misc +---- + +- #4996 + + +v80.6.0 +======= + +Features +-------- + +- Added a build dependency on coherent.licensed to inject the declared license text at build time. (#4981) + + +Misc +---- + +- #4995 + + +v80.5.0 +======= + +Features +-------- + +- Replaced more references to pkg_resources with importlib equivalents. (#3085) + + +Misc +---- + +- #4982 + + +v80.4.0 +======= + +Features +-------- + +- Simplified the error reporting in editable installs. (#4984) + + +v80.3.1 +======= + +Bugfixes +-------- + +- Restored select attributes in easy_install for temporary pbr compatibility. (#4976) + + +v80.3.0 +======= + +Features +-------- + +- Removed easy_install and package_index modules. (#917) +- Restored license declaration in package metadata. See jaraco/skeleton#171. (#4956) + + +v80.2.0 +======= + +Features +-------- + +- Restored support for install_scripts --executable (and classic behavior for the executable for those invocations). Instead, build_editable provides the portable form of the executables for downstream installers to rewrite. (#4934) + + +v80.1.0 +======= + +Features +-------- + +- Added a deadline of Oct 31 to the setup.py install deprecation. + + +Bugfixes +-------- + +- With ``setup.py install --prefix=...``, fall back to distutils install rather than failing. Note that running ``setup.py install`` is deprecated. (#3143) + + +v80.0.1 +======= + +Bugfixes +-------- + +- Fixed index_url logic in develop compatibility shim. (#4966) + + +v80.0.0 +======= + +Bugfixes +-------- + +- Update test to honor new behavior in importlib_metadata 8.7. (#4961) + + +Deprecations and Removals +------------------------- + +- Removed support for the easy_install command including the sandbox module. (#2908) +- Develop command no longer uses easy_install, but instead defers execution to pip (which then will re-invoke Setuptools via PEP 517 to build the editable wheel). Most of the options to develop are dropped. This is the final warning before the command is dropped completely in a few months. Use-cases relying on 'setup.py develop' should pin to older Setuptools version or migrate to modern build tooling. (#4955) + + +v79.0.1 +======= + +Bugfixes +-------- + +- Merge with pypa/distutils@24bd3179b including fix for pypa/distutils#355. + + +v79.0.0 +======= + +Deprecations and Removals +------------------------- + +- Removed support for 'legacy-editable' installs. (#917) + + +v78.1.1 +======= + +Bugfixes +-------- + +- More fully sanitized the filename in PackageIndex._download. (#4946) + + +v78.1.0 +======= + +Features +-------- + +- Restore access to _get_vc_env with a warning. (#4874) + + +v78.0.2 +======= + +Bugfixes +-------- + +- Postponed removals of deprecated dash-separated and uppercase fields in ``setup.cfg``. + All packages with deprecated configurations are advised to move before 2026. (#4911) + + +v78.0.1 +======= + +Misc +---- + +- #4909 + + +v78.0.0 +======= + +Bugfixes +-------- + +- Reverted distutils changes that broke the monkey patching of command classes. (#4902) + + +Deprecations and Removals +------------------------- + +- Setuptools no longer accepts options containing uppercase or dash characters in ``setup.cfg``. + Please ensure to write the options in ``setup.cfg`` using the :wiki:`lower_snake_case ` convention + (e.g. ``Name => name``, ``install-requires => install_requires``). + This is a follow-up on deprecations introduced in + `v54.1.0 `_ (see #1608) and + `v54.1.1 `_ (see #2592). + + .. note:: + This change *does not affect configurations in* ``pyproject.toml`` + (which uses the :wiki:`lower-kebab-case ` convention following the precedent set in :pep:`517`/:pep:`518`). (#4870) + + +Misc +---- + +- #4904 + + +v77.0.3 +======= + +Bugfixes +-------- + +- Temporarily convert error for license glob patterns containing ``../`` into a deprecation warning + to allow an accomodation period. (#4896) +- Better error messages for ``packaging.licenses`` import errors in environments with ``packaging<24.2``\. + The import statement was also deferred to spare users that are not using + license expressions. (#4898) +- Avoided eagerly raising an exception when ``license-files`` is defined + simultaneously inside and outside of ``pyproject.toml``. + Instead we rely on the existing deprecation error. (#4899) + + +v77.0.2 +======= + +Bugfixes +-------- + +- Restore ``distutils.ccompiler._default_compilers`` -- by :user:`ManiacDC` (#4876) +- Fixed copy pasta in ``msvc.shared_lib_format``\. (#4885) + + +v77.0.1 +======= + +Bugfixes +-------- + +- Manually fix news fragment entries causing CI to crash when building docs. (#4891) + + +v77.0.0 +======= + +Features +-------- + +- Added initial support for license expression (PEP :pep:`639 <639#add-license-expression-field>`). -- by :user:`cdce8p` (#4706) +- Store ``License-File``\s in ``.dist-info/licenses`` subfolder and added support for recursive globs for ``license_files`` (PEP :pep:`639 <639#add-license-expression-field>`). -- by :user:`cdce8p` (#4728) +- Bump core metadata version to ``2.4``\. -- by :user:`cdce8p` (#4830) +- Updated vendored copy of ``wheel`` to ``v0.45.1``\. (#4869) + + +Deprecations and Removals +------------------------- + +- Added initial implementation of :pep:`639`. + Users relying on pre- :pep:`639` implementation details + (like precise license file paths inside ``dist-info`` directory) + may need to adjust their code base to avoid problems. + Deprecations and stronger validation were also introduced (#4829). +- Added exception (or warning) when deprecated license classifiers are used, + according to PEP :pep:`639 <639#deprecate-license-classifiers>`. (#4833) +- Deprecated ``tools.setuptools.license-files`` in favor of ``project.license-files`` + and added exception if ``project.license-files`` and ``tools.setuptools.license-files`` + are used together. -- by :user:`cdce8p` (#4837) +- Deprecated ``project.license`` as a TOML table in + ``pyproject.toml``\. Users are expected to move towards using + ``project.license-files`` and/or SPDX expressions (as strings) in + ``project.license``\. + See PEP :pep:`639 <639#deprecate-license-key-table-subkeys>`. (#4840) +- Added simple validation for given glob patterns in ``license-files``\: + a warning will be generated if no file is matched. + Invalid glob patterns can raise an exception. + -- thanks :user:`cdce8p` for contributions. (#4838) + + +Misc +---- + +- #4734 + + +v76.1.0 +======= + +Features +-------- + +- In setuptools.msvc.EnvironmentInfo, now honor the correct paths when on an ARM host. (#4786) + + +Bugfixes +-------- + +- Restored implicit distutils.ccompiler import for g-ir-scanner. (#4871) +- Restore ``distutils.ccompiler.compiler_class`` -- by :user:`Avasam` (#4876) + + +v75.3.4 +======= + +Bugfixes +-------- + +- Backport CVE-47273 from 78.1.1 for Python 3.8. (#4946) + + +v75.3.3 +======= + +Bugfixes +-------- + +- Backported security fix for package index to 75.3.x for Python 3.8. (#5009) + + +v75.3.2 +======= + +- Fixed version error in changelog. + + +v75.3.1 +======= + +Bugfixes +-------- + +- Fix wheel file naming to follow binary distribution specification -- by :user:`di` (#4877) + + +v76.0.0 +======= + +Deprecations and Removals +------------------------- + +- Synced with pypa/distutils@5589d7527 including a simplified shebang generation when building scripts (#4863). (#4865) + + +v75.9.1 +======= + +Bugfixes +-------- + +- Fix ImportError in distutils when configuring for linking. (#4866) + + +v75.9.0 +======= + +Features +-------- + +- Synced with pypa/distutils@91f75bb98 including exporting of PyInit_pkg (pypa/distutils#327) and a refactoring of the compiler classes into distutils.compilers (pypa/distutils#295). (#4852) + + +v75.8.2 +======= + +Bugfixes +-------- + +- Fixed ``pkg_resources.require(...)`` to also consider standardised + ``dist-info`` directories. (#4856) + + +v75.8.1 +======= + +Bugfixes +-------- + +- Fix wheel file naming to follow binary distribution specification -- by :user:`di` (#4766) +- Fixed crash generating error message printed when building wheels for the + free-threaded build using the limited API. -- by :user:`ngoldbaum` (#4809) +- Fix documentation for recent CFLAGS distutils change. -- by :user:`thesamesam` (#4836) + + +v75.8.0 +======= + +Features +-------- + +- Implemented ``Dynamic`` field for core metadata (as introduced in PEP 643). + The existing implementation is currently experimental and the exact approach + may change in future releases. (#4698) + + +v75.7.0 +======= + +Features +-------- + +- Synced with pypa/distutils@c97a3db2f including better support for free threaded Python on Windows (pypa/distutils#310), improved typing support, and linter accommodations. (#4478) +- Synced with pypa/distutils@ff11eed0c including bugfix for duplicate CFLAGS and adaption to support Python 3.13 is_abs in the C compiler (#4669). (#4790) + + +v75.6.0 +======= + +Features +-------- + +- Preserve original ``PKG-INFO`` into ``METADATA`` when creating wheel + (instead of calling ``wheel.metadata.pkginfo_to_metadata``). + This helps to be more compliant with the flow specified in PEP 517. (#4701) +- Changed the ``WindowsSdkVersion``, ``FrameworkVersion32`` and ``FrameworkVersion64`` properties of ``setuptools.msvc.PlatformInfo`` to return an empty `tuple` instead of `None` as a fallthrough case -- by :user:`Avasam` (#4754) + + +v75.5.0 +======= + +Features +-------- + +- Removed support for ``SETUPTOOLS_DANGEROUSLY_SKIP_PYPROJECT_VALIDATION``, as it + is deemed prone to errors. (#4746) + + +v75.4.0 +======= + +Features +-------- + +- Added support for the environment variable + ``SETUPTOOLS_DANGEROUSLY_SKIP_PYPROJECT_VALIDATION=true``, allowing users to bypass + the validation of ``pyproject.toml``. + This option should be used only as a last resort when resolving dependency + issues, as it may lead to improper functioning. + Users who enable this setting are responsible for ensuring that ``pyproject.toml`` + complies with setuptools requirements. (#4611) + + .. attention:: + This environment variable was removed in a later version of ``setuptools``. + +- Require Python 3.9 or later. (#4718) +- Remove dependency on ``importlib_resources`` + and the vendored copy of the library. + Instead, ``setuptools`` consistently rely on stdlib's ``importlib.resources`` + (available on Python 3.9+). (#4718) +- Setuptools' ``bdist_wheel`` implementation no longer produces wheels with + the ``m`` SOABI flag (pymalloc-related). + This flag was removed on Python 3.8+ (see :obj:`sys.abiflags`). (#4718) +- Updated vendored packaging version to 24.2. (#4740) + + +Bugfixes +-------- + +- Merge with pypa/distutils@251797602, including fix for dirutil.mkpath handling in pypa/distutils#304. + + +v75.3.0 +======= + +Features +-------- + +- Allowed using `dict` as an ordered type in ``setuptools.dist.check_requirements`` -- by :user:`Avasam` (#4575) + + +Bugfixes +-------- + +- Ensured methods in ``setuptools.modified`` preferably raise a consistent + ``distutils.errors.DistutilsError`` type + (except in the deprecated use case of ``SETUPTOOLS_USE_DISTUTILS=stdlib``) + -- by :user:`Avasam` (#4567) +- Fix the ABI tag when building a wheel using the debug build of Python 3.13 on Windows. Previously, the ABI tag was missing the ``"d"`` flag. (#4674) +- Fix clashes for ``optional-dependencies`` in ``pyproject.toml`` and + ``extra_requires`` in ``setup.cfg/setup.py``. + As per PEP 621, ``optional-dependencies`` have to be honoured and dynamic + behaviour is not allowed. (#4696) + + +Misc +---- + +- #4560 + + +v75.2.0 +======= + +Features +-------- + +- Made errors when parsing ``Distribution`` data more explicit about the expected type (``tuple[str, ...] | list[str]``) -- by :user:`Avasam` (#4578) + + +Bugfixes +-------- + +- Fix a `TypeError` when a ``Distribution``'s old included attribute was a `tuple` -- by :user:`Avasam` (#4578) +- Add workaround for ``bdist_wheel --dist-info-dir`` errors + when customisation does not inherit from setuptools. (#4684) + + +v75.1.1 +======= + +Bugfixes +-------- + +- Re-use pre-existing ``.dist-info`` dir when creating wheels via the build backend APIs (PEP 517) and the ``metadata_directory`` argument is passed -- by :user:`pelson`. (#1825) +- Changed ``egg_info`` command to avoid adding an empty ``.egg-info`` directory + while iterating over entry-points. + This avoids triggering integration problems with ``importlib.metadata``/``importlib_metadata`` + (reference: pypa/pyproject-hooks#206). (#4680) + + +v75.1.0 +======= + +Features +-------- + +- Deprecated ``bdist_wheel.universal`` configuration. (#4617) + + +Bugfixes +-------- + +- Removed reference to upload_docs module in entry points. (#4650) + + +v75.0.0 +======= + +Features +-------- + +- Declare also the dependencies used by distutils (adds jaraco.collections). + + +Deprecations and Removals +------------------------- + +- Removed upload_docs command. (#2971) +- Merge with pypa/distutils@7283751. Removed the register and upload commands and the config module that backs them (pypa/distutils#294). Removed the borland compiler. Replaced vendored dependencies with natural dependencies. Cygwin C compiler now gets compilers from sysconfig (pypa/distutils#296). (#4649) + + +v74.1.3 +======= + +Bugfixes +-------- + +- Fix cross-platform compilation using ``distutils._msvccompiler.MSVCCompiler`` -- by :user:`saschanaz` and :user:`Avasam` (#4648) + + +v74.1.2 +======= + +Bugfixes +-------- + +- Fixed TypeError in sdist filelist processing by adding support for pathlib Paths for the build_base. (#4615) +- Removed degraded and deprecated ``test_integration`` (easy_install) from the test suite. (#4632) + + +v74.1.1 +======= + +Bugfixes +-------- + +- Fixed TypeError in ``msvc.EnvironmentInfo.return_env`` when no runtime redistributables are installed. (#1902) + + +v74.1.0 +======= + +Features +-------- + +- Added support for defining ``ext-modules`` via ``pyproject.toml`` + (**EXPERIMENTAL**, may change in future releases). (#4568) + + +Bugfixes +-------- + +- Merge with pypa/distutils@3dcdf8567, removing the duplicate vendored copy of packaging. (#4622) +- Restored ``setuptools.msvc.Environmentinfo`` as it is used externally. (#4625) + + +v74.0.0 +======= + +Features +-------- + +- Changed the type of error raised by ``setuptools.command.easy_install.CommandSpec.from_param`` on unsupported argument from `AttributeError` to `TypeError` -- by :user:`Avasam` (#4548) +- Added detection of ARM64 variant of MSVC -- by :user:`saschanaz` (#4553) +- Made ``setuptools.package_index.Credential`` a `typing.NamedTuple` -- by :user:`Avasam` (#4585) +- Reraise error from ``setuptools.command.easy_install.auto_chmod`` instead of nonsensical ``TypeError: 'Exception' object is not subscriptable`` -- by :user:`Avasam` (#4593) +- Fully typed all collection attributes in ``pkg_resources`` -- by :user:`Avasam` (#4598) +- Automatically exclude ``.tox|.nox|.venv`` directories from ``sdist``. (#4603) + + +Deprecations and Removals +------------------------- + +- Removed the monkeypatching of distutils._msvccompiler. Now all compiler logic is consolidated in distutils. (#4600) +- Synced with pypa/distutils@58fe058e4, including consolidating Visual Studio 2017 support (#4600, pypa/distutils#289), removal of deprecated legacy MSVC compiler modules (pypa/distutils#287), suppressing of errors when the home directory is missing (pypa/distutils#278), removal of wininst binaries (pypa/distutils#282). (#4606) + + +Misc +---- + +- #4592 + + +v73.0.1 +======= + +Bugfixes +-------- + +- Remove `abc.ABCMeta` metaclass from abstract classes. `pypa/setuptools#4503 `_ had an unintended consequence of causing potential ``TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases`` -- by :user:`Avasam` (#4579) + + +v73.0.0 +======= + +Features +-------- + +- Mark abstract base classes and methods with `abc.ABC` and `abc.abstractmethod` -- by :user:`Avasam` (#4503) +- Changed the order of type checks in ``setuptools.command.easy_install.CommandSpec.from_param`` to support any `collections.abc.Iterable` of `str` param -- by :user:`Avasam` (#4505) + + +Bugfixes +-------- + +- Prevent an error in ``bdist_wheel`` if ``compression`` is set to a `str` (even if valid) after finalizing options but before running the command. -- by :user:`Avasam` (#4383) +- Raises an exception when ``py_limited_api`` is used in a build with + ``Py_GIL_DISABLED``. This is currently not supported (python/cpython#111506). (#4420) +- Synced with pypa/distutils@30b7331 including fix for modified check on empty sources (pypa/distutils#284). + + +Deprecations and Removals +------------------------- + +- ``setuptools`` is replacing the usages of :pypi:`ordered_set` with simple + instances of ``dict[Hashable, None]``. This is done to remove the extra + dependency and it is possible because since Python 3.7, ``dict`` maintain + insertion order. (#4574) + + +Misc +---- + +- #4534, #4546, #4554, #4559, #4565 + + +v72.2.0 +======= + +Features +-------- + +- Merged with pypa/distutils@b7ee725f3 including: Support for Pathlike objects in data files and extensions (pypa/distutils#272, pypa/distutils#237), native support for C++ compilers (pypa/distutils#228) and removed unused get_msvcr() (pypa/distutils#274). (#4538) + + +v72.1.0 +======= + +Features +-------- + +- Restore the tests command and deprecate access to the module. (#4519) (#4520) + + +v72.0.0 +======= + +Deprecations and Removals +------------------------- + +- The test command has been removed. Users relying on 'setup.py test' will need to migrate to another test runner or pin setuptools before this version. (#931) + + +v71.1.0 +======= + +Features +-------- + +- Added return types to typed public functions -- by :user:`Avasam` + + Marked ``pkg_resources`` as ``py.typed`` -- by :user:`Avasam` (#4409) + + +Misc +---- + +- #4492 + + +v71.0.4 +======= + +Bugfixes +-------- + +- Removed lingering unused code around Distribution._patched_dist. (#4489) + + +v71.0.3 +======= + +Bugfixes +-------- + +- Reset the backports module when enabling vendored packages. (#4476) + + +v71.0.2 +======= + +Bugfixes +-------- + +- Include all vendored files in the sdist. (#4480) + + +v71.0.1 +======= + +Bugfixes +-------- + +- Restored package data that went missing in 71.0. This change also incidentally causes tests to be installed once again. (#4475) + + +v71.0.0 +======= + +Deprecations and Removals +------------------------- + +- Now setuptools declares its own dependencies in the ``core`` extra. Dependencies are still vendored for bootstrapping purposes, but setuptools will prefer installed dependencies if present. The ``core`` extra is used for informational purposes and should *not* be declared in package metadata (e.g. ``build-requires``). Downstream packagers can de-vendor by simply removing the ``setuptools/_vendor`` directory. Since Setuptools now prefers installed dependencies, those installing to an environment with old, incompatible dependencies will not work. In that case, either uninstall the incompatible dependencies or upgrade them to satisfy those declared in ``core``. (#2825) + + +v70.3.0 +======= + +Features +-------- + +- Support for loading distutils from the standard library is now deprecated, including use of SETUPTOOLS_USE_DISTUTILS=stdlib and importing distutils before importing setuptools. (#4137) + + +Bugfixes +-------- + +- Bugfix for building Cython extension on Windows (pypa/distutils#268). + + +v70.2.0 +======= + +Features +-------- + +- Updated distutils including significant changes to support Cygwin and mingw compilers. (#4444) + + +Bugfixes +-------- + +- Fix distribution name normalisation (:pep:`625`) for valid versions that are + not canonical (e.g. ``1.0-2``). (#4434) + + +v70.1.1 +======= + +Misc +---- + +- #4429 + + +v70.1.0 +======= + +Features +-------- + +- Adopted the ``bdist_wheel`` command from the ``wheel`` project -- by :user:`agronholm` (#1386) +- Improve error message when ``pkg_resources.ZipProvider`` tries to extract resources with a missing Egg -- by :user:`Avasam` + + Added variables and parameter type annotations to ``pkg_resources`` to be nearly on par with typeshed.\* -- by :user:`Avasam` + \* Excluding ``TypeVar`` and ``overload``. Return types are currently inferred. (#4246) +- Migrated Setuptools' own config to pyproject.toml (#4310) + + +Bugfixes +-------- + +- Prevent a ``TypeError: 'NoneType' object is not callable`` when ``shutil_rmtree`` is called without an ``onexc`` parameter on Python<=3.11 -- by :user:`Avasam` (#4382) +- Replace use of mktemp with can_symlink from the stdlib test suite. (#4403) +- Improvement for ``attr:`` directives in configuration to handle + more edge cases related to complex ``package_dir``. (#4405) +- Fix accidental implicit string concatenation. (#4411) + + +Misc +---- + +- #4365, #4422 + + +v70.0.0 +======= + +Features +-------- + +- Emit a warning when ``[tools.setuptools]`` is present in ``pyproject.toml`` and will be ignored. -- by :user:`SnoopJ` (#4150) +- Improved `AttributeError` error message if ``pkg_resources.EntryPoint.require`` is called without extras or distribution + Gracefully "do nothing" when trying to activate a ``pkg_resources.Distribution`` with a `None` location, rather than raising a `TypeError` + -- by :user:`Avasam` (#4262) +- Typed the dynamically defined variables from ``pkg_resources`` -- by :user:`Avasam` (#4267) +- Modernized and refactored VCS handling in package_index. (#4332) + + +Bugfixes +-------- + +- In install command, use super to call the superclass methods. Avoids race conditions when monkeypatching from _distutils_system_mod occurs late. (#4136) +- Fix finder template for lenient editable installs of implicit nested namespaces + constructed by using ``package_dir`` to reorganise directory structure. (#4278) +- Fix an error with `UnicodeDecodeError` handling in ``pkg_resources`` when trying to read files in UTF-8 with a fallback -- by :user:`Avasam` (#4348) + + +Improved Documentation +---------------------- + +- Uses RST substitution to put badges in 1 line. (#4312) + + +Deprecations and Removals +------------------------- + +- Further adoption of UTF-8 in ``setuptools``. + This change regards mostly files produced and consumed during the build process + (e.g. metadata files, script wrappers, automatically updated config files, etc..) + Although precautions were taken to minimize disruptions, some edge cases might + be subject to backwards incompatibility. + + Support for ``"locale"`` encoding is now **deprecated**. (#4309) +- Remove ``setuptools.convert_path`` after long deprecation period. + This function was never defined by ``setuptools`` itself, but rather a + side-effect of an import for internal usage. (#4322) +- Remove fallback for customisations of ``distutils``' ``build.sub_command`` after long + deprecated period. + Users are advised to import ``build`` directly from ``setuptools.command.build``. (#4322) +- Removed ``typing_extensions`` from vendored dependencies -- by :user:`Avasam` (#4324) +- Remove deprecated ``setuptools.dep_util``. + The provided alternative is ``setuptools.modified``. (#4360) + + +Misc +---- + +- #4255, #4280, #4282, #4308, #4348 + + +v69.5.1 +======= + +No significant changes. + + +v69.5.0 +======= + +Features +-------- + +- Refresh unpinned vendored dependencies. (#4253) +- Updated vendored packaging to version 24.0. (#4301) + + +v69.4.2 +======= + +Bugfixes +-------- + +- Merged bugfix for pypa/distutils#246. + + +v69.4.1 +======= + +No significant changes. + + +v69.4.0 +======= + +Features +-------- + +- Merged with pypa/distutils@55982565e, including interoperability improvements for rfc822_escape (pypa/distutils#213), dynamic resolution of config_h_filename for Python 3.13 compatibility (pypa/distutils#219), added support for the z/OS compiler (pypa/distutils#216), modernized compiler options in unixcompiler (pypa/distutils#214), fixed accumulating flags bug after compile/link (pypa/distutils#207), fixed enconding warnings (pypa/distutils#236), and general quality improvements (pypa/distutils#234). (#4298) + + +v69.3.1 +======= + +Bugfixes +-------- + +- Remove attempt to canonicalize the version. It's already canonical enough. (#4302) + + +v69.3.0 +======= + +Features +-------- + +- Support PEP 625 by canonicalizing package name and version in filenames + per + `the spec `_. + Projects whose names contain uppercase characters, dashes, or periods will + now see their sdist names normalized to match the standard and the format + previously seen in wheels. For example: + + - ``zope.interface`` -> ``zope_interface`` + - ``CherryPy`` -> ``cherrypy`` + - ``foo-bar_baz`` -> ``foo_bar_baz`` + + Projects are encouraged to adopt this change to align with standards and + other backend build systems. (#3593) + + +v69.2.0 +======= + +Features +-------- + +- Explicitly use ``encoding="locale"`` for ``.pth`` files whenever possible, + to reduce ``EncodingWarnings``. + This avoid errors with UTF-8 (see discussion in python/cpython#77102). (#4265) + + +Bugfixes +-------- + +- Clarify some ``pkg_resources`` methods return ``bytes``, not ``str``. Also return an empty ``bytes`` in ``EmptyProvider._get`` -- by :user:`Avasam` (#4243) +- Return an empty ``list`` by default in ``pkg_resources.ResourceManager.cleanup_resources`` -- by :user:`Avasam` (#4244) +- Made ``pkg_resoursces.NullProvider``'s ``has_metadata`` and ``metadata_isdir`` methods return actual booleans like all other Providers. -- by :user:`Avasam` (#4254) + + +Misc +---- + +- #4237, #4238, #4241, #4260, #4261, #4263 + + +v69.1.1 +======= + +Bugfixes +-------- + +- Fix argument order of ``--config-settings["--build-option"]`` arguments. + This was broken by `. (#4217) + + +Misc +---- + +- #4231 + + +v69.1.0 +======= + +Features +-------- + +- Updated and removed obsolete Python < 3.8 code and comments. -- by :user:`Avasam` (#4096) +- Updated ``pkg_resources`` to use stdlib ``importlib.machinery`` instead of ``importlib_machinery`` -- by :user:`Avasam` (#4097) + + +Bugfixes +-------- + +- In tests, rely on pytest-home for reusable fixture. (#4072) +- Explicitly marked as ``Protocol`` and fixed missing ``self`` argument in interfaces ``pkg_resources.IMetadataProvider`` and ``pkg_resources.IResourceProvider`` -- by :user:`Avasam` (#4144) +- Restored expectation that egg-link files would be named with dash separators for compatibility with pip prior to version 24. (#4167) + + +Improved Documentation +---------------------- + +- Updated documentation referencing obsolete Python 3.7 code. -- by :user:`Avasam` (#4096) +- Changed ``versionadded`` for "Type information included by default" feature from ``v68.3.0`` to ``v69.0.0`` -- by :user:`Avasam` (#4182) +- Described the auto-generated files -- by :user:`VladimirFokow` (#4198) +- Updated "Quickstart" to describe the current status of ``setup.cfg`` and ``pyproject.toml`` -- by :user:`VladimirFokow` (#4200) + + +v69.0.3 +======= + +Bugfixes +-------- + +- Retain valid names with underscores in egg_info. + + +v69.0.2 +======= + +Bugfixes +-------- + +- Added missing estimated date for removing ``setuptools.dep_util`` (deprecated in v69.0.0). (#4131) + + +v69.0.1 +======= + +Bugfixes +-------- + +- Fixed imports of ``setuptools.dep_util.newer_group``. + A deprecation warning is issued instead of a hard failure. (#4126) + + +v69.0.0 +======= + +Features +-------- + +- Include type information (``py.typed``, ``*.pyi``) by default (#3136) -- by :user:`Danie-1`, + **EXPERIMENTAL**. (#3136) +- Exported ``distutils.dep_util`` and ``setuptools.dep_util`` through ``setuptools.modified`` -- by :user:`Avasam` (#4069) +- Merged with pypa/distutils@7a04cbda0fc714. + + +Bugfixes +-------- + +- Replaced hardcoded numeric values with :obj:`dis.opmap`, + fixing problem with 3.13.0a1. (#4094) + + +Deprecations and Removals +------------------------- + +- Configuring project ``version`` and ``egg_info.tag_*`` in such a way that + results in invalid version strings (according to :pep:`440`) is no longer permitted. (#4066) +- Removed deprecated ``egg_base`` option from ``dist_info``. + Note that the ``dist_info`` command is considered internal to the way + ``setuptools`` build backend works and not intended for + public usage. (#4066) +- The parsing of the deprecated ``metadata.license_file`` and + ``metadata.requires`` fields in ``setup.cfg`` is no longer supported. + Users are expected to move to ``metadata.license_files`` and + ``options.install_requires`` (respectively). (#4066) +- Passing ``config_settings`` to ``setuptools.build_meta`` with + deprecated values for ``--global-option`` is no longer allowed. (#4066) +- Removed deprecated ``namespace-packages`` from ``pyproject.toml``. + Users are asked to use + :doc:`implicit namespace packages ` + (as defined in :pep:`420`). (#4066) +- Added strict enforcement for ``project.dynamic`` in ``pyproject.toml``. + This removes the transitional ability of users configuring certain parameters + via ``setup.py`` without making the necessary changes to ``pyproject.toml`` + (as mandated by :pep:`621`). (#4066) +- Removed handling of ``--config-settings["--build-option"]`` in ``setuptools.build_meta`` + from build-backend API hooks *other than* ``build_wheel``. + This was motivate by `errors caused when passing this option + `_. (#4079) + + +v68.2.2 +======= + +Bugfixes +-------- + +- Improve backwards compatibility with deprecated CLI practices. (#4048) + + +v68.2.1 +======= + +Bugfixes +-------- + +- Avoid using caching attributes in ``Distribution.metadata`` for requirements. + This is done for backwards compatibility with customizations that attempt to + modify ``install_requires`` or ``extras_require`` at a late point (still not + recommended). (#4043) + + +Misc +---- + +- #4045 + + +v68.2.0 +======= + +Features +-------- + +- Rework how ``setuptools`` internally handles ``dependencies/install_requires`` + and ``optional-dependencies/extras_require``. (#3903) +- Improve the generated ``PKG-INFO`` files, by adding ``Requires-Dist`` fields. + Previously, these fields would be omitted in favour of a non-standard + ``*.egg-info/requires.txt`` file (which is still generated for the time being). (#3904) +- Improve atomicity when writing ``PKG-INFO`` files to avoid race + conditions with ``importlib.metadata``. (#3904) + + +Bugfixes +-------- + +- Fix the name given to the ``*-nspkg.pth`` files in editable installs, + ensuring they are unique per distribution. (#4041) +- Workaround some limitations on ``pkg_resources``-style legacy namespaces in + the meta path finder for editable installations. (#4041) + + +Misc +---- + +- #4023, #4027, #4027 + + v68.1.2 ======= @@ -405,7 +1666,7 @@ v65.5.1 Misc ---- * #3638: Drop a test dependency on the ``mock`` package, always use :external+python:py:mod:`unittest.mock` -- by :user:`hroncok` -* #3659: Fixed REDoS vector in package_index. +* #3659: Fixed REDoS vector in package_index -- by :user:`SCH227` v65.5.0 @@ -1027,8 +2288,8 @@ Changes .. warning:: Please note that future releases of setuptools will halt the build process - if a ``pyproject.toml`` file that does not match doc:`the PyPA Specification - ` is given. + if a ``pyproject.toml`` file that does not match :doc:`the PyPA Specification + ` is given. * #3215: Updated ``pyproject.toml`` validation, as generated by ``validate-pyproject==0.6.1``. * #3218: Prevented builds from erroring if the project specifies metadata via ``pyproject.toml``, but uses other files (e.g. ``setup.py``) to complement it, @@ -6383,7 +7644,7 @@ setuptools * Fixed invalid URL error catching. Old Setuptools #20. -* Fixed invalid bootstraping with easy_install installation (Distribute #40). +* Fixed invalid bootstrapping with easy_install installation (Distribute #40). Thanks to Florian Schulze for the help. * Removed buildout/bootstrap.py. A new repository will create a specific diff --git a/README.rst b/README.rst index 699576551d..80dce9520c 100644 --- a/README.rst +++ b/README.rst @@ -1,40 +1,37 @@ -.. image:: https://img.shields.io/pypi/v/setuptools.svg +.. |pypi-version| image:: https://img.shields.io/pypi/v/setuptools.svg :target: https://pypi.org/project/setuptools -.. image:: https://img.shields.io/pypi/pyversions/setuptools.svg +.. |py-version| image:: https://img.shields.io/pypi/pyversions/setuptools.svg -.. image:: https://github.com/pypa/setuptools/workflows/tests/badge.svg +.. |test-badge| image:: https://github.com/pypa/setuptools/actions/workflows/main.yml/badge.svg :target: https://github.com/pypa/setuptools/actions?query=workflow%3A%22tests%22 :alt: tests -.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json - :target: https://github.com/astral-sh/ruff - :alt: Ruff +.. |ruff-badge| image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Ruff -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black - :alt: Code style: Black +.. |docs-badge| image:: https://img.shields.io/readthedocs/setuptools/latest.svg + :target: https://setuptools.pypa.io -.. image:: https://img.shields.io/readthedocs/setuptools/latest.svg - :target: https://setuptools.pypa.io - -.. image:: https://img.shields.io/badge/skeleton-2023-informational +.. |skeleton-badge| image:: https://img.shields.io/badge/skeleton-2026-informational :target: https://blog.jaraco.com/skeleton -.. image:: https://img.shields.io/codecov/c/github/pypa/setuptools/master.svg?logo=codecov&logoColor=white +.. |codecov-badge| image:: https://img.shields.io/codecov/c/github/pypa/setuptools/master.svg?logo=codecov&logoColor=white :target: https://codecov.io/gh/pypa/setuptools -.. image:: https://tidelift.com/badges/github/pypa/setuptools?style=flat +.. |tidelift-badge| image:: https://tidelift.com/badges/github/pypa/setuptools?style=flat :target: https://tidelift.com/subscription/pkg/pypi-setuptools?utm_source=pypi-setuptools&utm_medium=readme -.. image:: https://img.shields.io/discord/803025117553754132 +.. |discord-badge| image:: https://img.shields.io/discord/803025117553754132 :target: https://discord.com/channels/803025117553754132/815945031150993468 :alt: Discord -See the `Installation Instructions -`_ in the Python Packaging -User's Guide for instructions on installing, upgrading, and uninstalling -Setuptools. +|pypi-version| |py-version| |test-badge| |ruff-badge| |docs-badge| |skeleton-badge| |codecov-badge| |discord-badge| + +See the `Quickstart `_ +and the `User's Guide `_ for +instructions on how to use Setuptools. Questions and comments should be directed to `GitHub Discussions `_. diff --git a/_distutils_hack/__init__.py b/_distutils_hack/__init__.py index b951c2defd..94f71b99ec 100644 --- a/_distutils_hack/__init__.py +++ b/_distutils_hack/__init__.py @@ -1,18 +1,15 @@ # don't import any costly modules -import sys import os +import sys - -is_pypy = '__pypy__' in sys.builtin_module_names +report_url = ( + "https://github.com/pypa/setuptools/issues/new?template=distutils-deprecation.yml" +) def warn_distutils_present(): if 'distutils' not in sys.modules: return - if is_pypy and sys.version_info < (3, 7): - # PyPy for 3.6 unconditionally imports distutils, so bypass the warning - # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250 - return import warnings warnings.warn( @@ -30,7 +27,12 @@ def clear_distutils(): return import warnings - warnings.warn("Setuptools is replacing distutils.") + warnings.warn( + "Setuptools is replacing distutils. Support for replacing " + "an already imported distutils is deprecated. In the future, " + "this condition will fail. " + f"Register concerns at {report_url}" + ) mods = [ name for name in sys.modules @@ -45,6 +47,16 @@ def enabled(): Allow selection of distutils by environment variable. """ which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local') + if which == 'stdlib': + import warnings + + warnings.warn( + "Reliance on distutils from stdlib is deprecated. Users " + "must rely on setuptools to provide the distutils module. " + "Avoid importing distutils or import setuptools first, " + "and avoid setting SETUPTOOLS_USE_DISTUTILS=stdlib. " + f"Register concerns at {report_url}" + ) return which == 'local' @@ -78,7 +90,7 @@ def do_override(): class _TrivialRe: - def __init__(self, *patterns): + def __init__(self, *patterns) -> None: self._patterns = patterns def match(self, string): @@ -90,7 +102,7 @@ def find_spec(self, fullname, path, target=None): # optimization: only consider top level modules and those # found in the CPython test suite. if path is not None and not fullname.startswith('test.'): - return + return None method_name = 'spec_for_{fullname}'.format(**locals()) method = getattr(self, method_name, lambda: None) @@ -98,7 +110,7 @@ def find_spec(self, fullname, path, target=None): def spec_for_distutils(self): if self.is_cpython(): - return + return None import importlib import importlib.abc @@ -115,7 +127,7 @@ def spec_for_distutils(self): # setuptools from the path but only after the hook # has been loaded. Ref #2980. # In either case, fall back to stdlib behavior. - return + return None class DistutilsLoader(importlib.abc.Loader): def create_module(self, spec): @@ -204,10 +216,10 @@ def add_shim(): class shim: - def __enter__(self): + def __enter__(self) -> None: insert_shim() - def __exit__(self, exc, value, tb): + def __exit__(self, exc: object, value: object, tb: object) -> None: _remove_shim() diff --git a/conftest.py b/conftest.py index 94d5cdd8b5..023857d499 100644 --- a/conftest.py +++ b/conftest.py @@ -1,8 +1,8 @@ +import platform import sys import pytest - pytest_plugins = 'setuptools.tests.fixtures' @@ -24,6 +24,7 @@ def pytest_addoption(parser): def pytest_configure(config): config.addinivalue_line("markers", "integration: integration tests") config.addinivalue_line("markers", "uses_network: tests may try to download files") + _IntegrationTestSpeedups.disable_plugins_already_run(config) collect_ignore = [ @@ -31,29 +32,44 @@ def pytest_configure(config): 'setuptools/tests/mod_with_constant.py', 'setuptools/_distutils', '_distutils_hack', - 'setuptools/extern', - 'pkg_resources/extern', - 'pkg_resources/tests/data', 'setuptools/_vendor', - 'pkg_resources/_vendor', 'setuptools/config/_validate_pyproject', + 'setuptools/modified.py', + 'setuptools/tests/bdist_wheel_testdata', ] -if sys.version_info < (3, 6): - collect_ignore.append('docs/conf.py') # uses f-strings - collect_ignore.append('pavement.py') - - if sys.version_info < (3, 9) or sys.platform == 'cygwin': collect_ignore.append('tools/finalize.py') @pytest.fixture(autouse=True) def _skip_integration(request): - running_integration_tests = request.config.getoption("--integration") - is_integration_test = request.node.get_closest_marker("integration") - if running_integration_tests and not is_integration_test: - pytest.skip("running integration tests only") - if not running_integration_tests and is_integration_test: - pytest.skip("skipping integration tests") + _IntegrationTestSpeedups.conditional_skip(request) + + +class _IntegrationTestSpeedups: + """Speed-up integration tests by only running what does not run in other tests.""" + + RUNS_ON_NORMAL_TESTS = ("checkdocks", "cov", "mypy", "perf", "ruff") + + @classmethod + def disable_plugins_already_run(cls, config): + if config.getoption("--integration"): + for plugin in cls.RUNS_ON_NORMAL_TESTS: # no need to run again + config.pluginmanager.set_blocked(plugin) + + @staticmethod + def conditional_skip(request): + running_integration_tests = request.config.getoption("--integration") + is_integration_test = request.node.get_closest_marker("integration") + if running_integration_tests and not is_integration_test: + pytest.skip("running integration tests only") + if not running_integration_tests and is_integration_test: + pytest.skip("skipping integration tests") + + +@pytest.fixture +def windows_only(): + if platform.system() != 'Windows': + pytest.skip("Windows only") diff --git a/docs/build_meta.rst b/docs/build_meta.rst index aa4f190712..5cb383227e 100644 --- a/docs/build_meta.rst +++ b/docs/build_meta.rst @@ -60,10 +60,8 @@ being used to package your scripts and install from source). To use it with build-backend = "setuptools.build_meta" ``build_meta`` implements ``setuptools``' build system support. -The ``setuptools`` package implements the ``build_sdist`` -command and the ``wheel`` package implements the ``build_wheel`` -command; the latter is a dependency of the former -exposed via :pep:`517` hooks. +The ``setuptools`` package implements the ``build_sdist`` and +``build_wheel`` commands. Use ``setuptools``' :ref:`declarative config ` to specify the package information in ``setup.cfg``:: diff --git a/docs/conf.py b/docs/conf.py index 29f2c8bb10..2a9e50837a 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,3 +1,5 @@ +from __future__ import annotations + extensions = [ 'sphinx.ext.autodoc', 'jaraco.packaging.sphinx', @@ -45,15 +47,19 @@ ), dict( pattern=r'Old Setuptools #(?P\d+)', - url='http://bugs.python.org/setuptools/issue{old_setuptools}', + url='https://bugs.python.org/setuptools/issue{old_setuptools}', ), dict( pattern=r'Jython #(?P\d+)', - url='http://bugs.jython.org/issue{jython}', + url='https://bugs.jython.org/issue{jython}', ), dict( pattern=r'(Python #|bpo-)(?P\d+)', - url='http://bugs.python.org/issue{python}', + url='https://bugs.python.org/issue{python}', + ), + dict( + pattern=r'\bpython/cpython#(?P\d+)', + url='{GH}/python/cpython/issues/{cpython}', ), dict( pattern=r'Interop #(?P\d+)', @@ -89,6 +95,7 @@ # Be strict about any broken references nitpicky = True +nitpick_ignore: list[tuple[str, str]] = [] # Include Python intersphinx mapping to prevent failures # jaraco/skeleton#51 @@ -100,47 +107,17 @@ # Preserve authored syntax for defaults autodoc_preserve_defaults = True -intersphinx_mapping.update( - { - 'pip': ('https://pip.pypa.io/en/latest', None), - 'build': ('https://pypa-build.readthedocs.io/en/latest', None), - 'PyPUG': ('https://packaging.python.org/en/latest/', None), - 'packaging': ('https://packaging.pypa.io/en/latest/', None), - 'twine': ('https://twine.readthedocs.io/en/stable/', None), - 'importlib-resources': ( - 'https://importlib-resources.readthedocs.io/en/latest', - None, - ), - } -) - -# Support tooltips on references -extensions += ['hoverxref.extension'] -hoverxref_auto_ref = True -hoverxref_intersphinx = [ - 'python', - 'pip', - 'build', - 'PyPUG', - 'packaging', - 'twine', - 'importlib-resources', -] - -# Add support for linking usernames -github_url = 'https://github.com' -github_repo_org = 'pypa' -github_repo_name = 'setuptools' -github_repo_slug = f'{github_repo_org}/{github_repo_name}' -github_repo_url = f'{github_url}/{github_repo_slug}' -github_sponsors_url = f'{github_url}/sponsors' +# Add support for linking usernames, PyPI projects, Wikipedia pages +github_url = 'https://github.com/' extlinks = { - 'user': (f'{github_sponsors_url}/%s', '@%s'), # noqa: WPS323 - 'pypi': ('https://pypi.org/project/%s', '%s'), # noqa: WPS323 - 'wiki': ('https://wikipedia.org/wiki/%s', '%s'), # noqa: WPS323 + 'user': (f'{github_url}%s', '@%s'), + 'pypi': ('https://pypi.org/project/%s', '%s'), + 'wiki': ('https://wikipedia.org/wiki/%s', '%s'), } extensions += ['sphinx.ext.extlinks'] +# local + # Ref: https://github.com/python-attrs/attrs/pull/571/files\ # #diff-85987f48f1258d9ee486e3191495582dR82 default_role = 'any' @@ -159,6 +136,9 @@ "color-brand-primary": "#E5B62F", # "yellow" "color-brand-content": "#E5B62F", }, + "source_repository": "https://github.com/pypa/setuptools/", + "source_branch": "main", + "source_directory": "docs/", } # Redirect old docs so links and references in the ecosystem don't break @@ -166,6 +146,7 @@ redirects = { "userguide/keywords": "/deprecated/changed_keywords.html", "userguide/commands": "/deprecated/commands.html", + "pkg_resources": "/deprecated/pkg_resources.html", } # Add support for inline tabs @@ -174,24 +155,25 @@ # Support for distutils # Ref: https://stackoverflow.com/a/30624034/595220 -nitpick_ignore = [ +nitpick_ignore += [ ('c:func', 'SHGetSpecialFolderPath'), # ref to MS docs + ('envvar', 'DIST_EXTRA_CONFIG'), # undocumented ('envvar', 'DISTUTILS_DEBUG'), # undocumented ('envvar', 'HOME'), # undocumented ('envvar', 'PLAT'), # undocumented - ('envvar', 'DIST_EXTRA_CONFIG'), # undocumented ('py:attr', 'CCompiler.language_map'), # undocumented ('py:attr', 'CCompiler.language_order'), # undocumented - ('py:class', 'distutils.dist.Distribution'), # undocumented - ('py:class', 'distutils.extension.Extension'), # undocumented ('py:class', 'BorlandCCompiler'), # undocumented ('py:class', 'CCompiler'), # undocumented ('py:class', 'CygwinCCompiler'), # undocumented + ('py:class', 'distutils.dist.Distribution'), # undocumented ('py:class', 'distutils.dist.DistributionMetadata'), # undocumented + ('py:class', 'distutils.extension.Extension'), # undocumented ('py:class', 'FileList'), # undocumented ('py:class', 'IShellLink'), # ref to MS docs ('py:class', 'MSVCCompiler'), # undocumented ('py:class', 'OptionDummy'), # undocumented + ('py:class', 'setuptools.dist.Distribution'), # undocumented ('py:class', 'UnixCCompiler'), # undocumented ('py:exc', 'CompileError'), # undocumented ('py:exc', 'DistutilsExecError'), # undocumented @@ -201,8 +183,7 @@ ('py:exc', 'PreprocessError'), # undocumented ('py:exc', 'setuptools.errors.PlatformError'), # sphinx cannot find it ('py:func', 'distutils.CCompiler.new_compiler'), # undocumented - # undocumented: - ('py:func', 'distutils.dist.DistributionMetadata.read_pkg_file'), + ('py:func', 'distutils.dist.DistributionMetadata.read_pkg_file'), # undocumented ('py:func', 'distutils.file_util._copy_file_contents'), # undocumented ('py:func', 'distutils.log.debug'), # undocumented ('py:func', 'distutils.spawn.find_executable'), # undocumented @@ -213,7 +194,12 @@ # Allow linking objects on other Sphinx sites seamlessly: intersphinx_mapping.update( - python=('https://docs.python.org/3', None), + # python=('https://docs.python.org/3', None), + python=('https://docs.python.org/3.11', None), + # ^-- Python 3.11 is required because it still contains `distutils`. + # Just leaving it as `3` would imply 3.12+, but that causes an + # error with the cross references to distutils functions. + # Inventory cache may cause errors, deleting it solves the problem. ) # Add support for the unreleased "next-version" change notes @@ -232,7 +218,7 @@ html_static_path = ['images'] # should contain the folder with icons # Add support for nice Not Found 404 pages -# extensions += ['notfound.extension'] # readthedocs/sphinx-notfound-page#219 +extensions += ['notfound.extension'] # List of dicts with HTML attributes # static-file points to files in the html_static_path (href is computed) @@ -251,3 +237,16 @@ }, # rel="apple-touch-icon" does not support SVG yet ] + +intersphinx_mapping.update({ + 'pip': ('https://pip.pypa.io/en/stable', None), + 'build': ('https://build.pypa.io/en/stable', None), + 'PyPUG': ('https://packaging.python.org/en/latest', None), + 'pytest': ('https://docs.pytest.org/en/stable', None), + 'packaging': ('https://packaging.pypa.io/en/latest', None), + 'twine': ('https://twine.readthedocs.io/en/stable', None), + 'importlib-resources': ( + 'https://importlib-resources.readthedocs.io/en/latest', + None, + ), +}) diff --git a/docs/deprecated/distutils-legacy.rst b/docs/deprecated/distutils-legacy.rst index 8112f12eae..166fcd584a 100644 --- a/docs/deprecated/distutils-legacy.rst +++ b/docs/deprecated/distutils-legacy.rst @@ -28,6 +28,8 @@ As Distutils is deprecated, any usage of functions or objects from distutils is ``distutils.command.{build_clib,build_ext,build_py,sdist}`` → ``setuptools.command.*`` +``distutils.dep_util`` → ``setuptools.modified`` + ``distutils.log`` → :mod:`logging` (standard library) ``distutils.version.*`` → :doc:`packaging.version.* ` diff --git a/docs/deprecated/distutils/apiref.rst b/docs/deprecated/distutils/apiref.rst index 278471a256..de689edfa4 100644 --- a/docs/deprecated/distutils/apiref.rst +++ b/docs/deprecated/distutils/apiref.rst @@ -361,7 +361,7 @@ This module provides the following functions. are not given. -.. function:: new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0) +.. function:: new_compiler(plat=None, compiler=None, verbose=False, dry_run=False, force=False) Factory function to generate an instance of some CCompiler subclass for the supplied platform/compiler combination. *plat* defaults to ``os.name`` (eg. @@ -383,7 +383,7 @@ This module provides the following functions. to :command:`build`, :command:`build_ext`, :command:`build_clib`). -.. class:: CCompiler([verbose=0, dry_run=0, force=0]) +.. class:: CCompiler([verbose=False, dry_run=False, force=False]) The abstract base class :class:`CCompiler` defines the interface that must be implemented by real compiler classes. The class also has some utility methods @@ -517,7 +517,7 @@ This module provides the following functions. list) to do the job. - .. method:: CCompiler.find_library_file(dirs, lib[, debug=0]) + .. method:: CCompiler.find_library_file(dirs, lib[, debug=False]) Search the specified list of directories for a static or shared library file *lib* and return the full path to that file. If *debug* is true, look for a @@ -580,7 +580,7 @@ This module provides the following functions. The following methods invoke stages in the build process. - .. method:: CCompiler.compile(sources[, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None]) + .. method:: CCompiler.compile(sources[, output_dir=None, macros=None, include_dirs=None, debug=False, extra_preargs=None, extra_postargs=None, depends=None]) Compile one or more source files. Generates object files (e.g. transforms a :file:`.c` file to a :file:`.o` file.) @@ -624,7 +624,7 @@ This module provides the following functions. Raises :exc:`CompileError` on failure. - .. method:: CCompiler.create_static_lib(objects, output_libname[, output_dir=None, debug=0, target_lang=None]) + .. method:: CCompiler.create_static_lib(objects, output_libname[, output_dir=None, debug=False, target_lang=None]) Link a bunch of stuff together to create a static library file. The "bunch of stuff" consists of the list of object files supplied as *objects*, the extra @@ -648,7 +648,7 @@ This module provides the following functions. Raises :exc:`LibError` on failure. - .. method:: CCompiler.link(target_desc, objects, output_filename[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None]) + .. method:: CCompiler.link(target_desc, objects, output_filename[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=False, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None]) Link a bunch of stuff together to create an executable or shared library file. @@ -690,21 +690,21 @@ This module provides the following functions. Raises :exc:`LinkError` on failure. - .. method:: CCompiler.link_executable(objects, output_progname[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, target_lang=None]) + .. method:: CCompiler.link_executable(objects, output_progname[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, debug=False, extra_preargs=None, extra_postargs=None, target_lang=None]) Link an executable. *output_progname* is the name of the file executable, while *objects* are a list of object filenames to link in. Other arguments are as for the :meth:`link` method. - .. method:: CCompiler.link_shared_lib(objects, output_libname[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None]) + .. method:: CCompiler.link_shared_lib(objects, output_libname[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=False, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None]) Link a shared library. *output_libname* is the name of the output library, while *objects* is a list of object filenames to link in. Other arguments are as for the :meth:`link` method. - .. method:: CCompiler.link_shared_object(objects, output_filename[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None]) + .. method:: CCompiler.link_shared_object(objects, output_filename[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=False, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None]) Link a shared object. *output_filename* is the name of the shared object that will be created, while *objects* is a list of object filenames to link in. @@ -726,14 +726,14 @@ This module provides the following functions. use by the various concrete subclasses. - .. method:: CCompiler.executable_filename(basename[, strip_dir=0, output_dir='']) + .. method:: CCompiler.executable_filename(basename[, strip_dir=False, output_dir='']) Returns the filename of the executable for the given *basename*. Typically for non-Windows platforms this is the same as the basename, while Windows will get a :file:`.exe` added. - .. method:: CCompiler.library_filename(libname[, lib_type='static', strip_dir=0, output_dir='']) + .. method:: CCompiler.library_filename(libname[, lib_type='static', strip_dir=False, output_dir='']) Returns the filename for the given library name on the current platform. On Unix a library with *lib_type* of ``'static'`` will typically be of the form @@ -741,13 +741,13 @@ This module provides the following functions. :file:`liblibname.so`. - .. method:: CCompiler.object_filenames(source_filenames[, strip_dir=0, output_dir='']) + .. method:: CCompiler.object_filenames(source_filenames[, strip_dir=False, output_dir='']) Returns the name of the object files for the given source files. *source_filenames* should be a list of filenames. - .. method:: CCompiler.shared_object_filename(basename[, strip_dir=0, output_dir='']) + .. method:: CCompiler.shared_object_filename(basename[, strip_dir=False, output_dir='']) Returns the name of a shared object file for the given file name *basename*. @@ -884,7 +884,7 @@ This module provides a few functions for creating archive files, such as tarballs or zipfiles. -.. function:: make_archive(base_name, format[, root_dir=None, base_dir=None, verbose=0, dry_run=0]) +.. function:: make_archive(base_name, format[, root_dir=None, base_dir=None, verbose=False, dry_run=False]) Create an archive file (eg. ``zip`` or ``tar``). *base_name* is the name of the file to create, minus any format-specific extension; *format* is the @@ -900,7 +900,7 @@ tarballs or zipfiles. Added support for the ``xztar`` format. -.. function:: make_tarball(base_name, base_dir[, compress='gzip', verbose=0, dry_run=0]) +.. function:: make_tarball(base_name, base_dir[, compress='gzip', verbose=False, dry_run=False]) 'Create an (optional compressed) archive as a tar file from all files in and under *base_dir*. *compress* must be ``'gzip'`` (the default), @@ -915,7 +915,7 @@ tarballs or zipfiles. Added support for the ``xz`` compression. -.. function:: make_zipfile(base_name, base_dir[, verbose=0, dry_run=0]) +.. function:: make_zipfile(base_name, base_dir[, verbose=False, dry_run=False]) Create a zip file from all files in and under *base_dir*. The output zip file will be named *base_name* + :file:`.zip`. Uses either the :mod:`zipfile` Python @@ -978,7 +978,7 @@ This module provides functions for operating on directories and trees of directories. -.. function:: mkpath(name[, mode=0o777, verbose=0, dry_run=0]) +.. function:: mkpath(name[, mode=0o777, verbose=False, dry_run=False]) Create a directory and any missing ancestor directories. If the directory already exists (or if *name* is the empty string, which means the current @@ -989,7 +989,7 @@ directories. directories actually created. -.. function:: create_tree(base_dir, files[, mode=0o777, verbose=0, dry_run=0]) +.. function:: create_tree(base_dir, files[, mode=0o777, verbose=False, dry_run=False]) Create all the empty directories under *base_dir* needed to put *files* there. *base_dir* is just the name of a directory which doesn't necessarily exist @@ -999,7 +999,7 @@ directories. :func:`mkpath`. -.. function:: copy_tree(src, dst[, preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=0, dry_run=0]) +.. function:: copy_tree(src, dst[, preserve_mode=True, preserve_times=True, preserve_symlinks=False, update=False, verbose=False, dry_run=False]) Copy an entire directory tree *src* to a new location *dst*. Both *src* and *dst* must be directory names. If *src* is not a directory, raise @@ -1021,12 +1021,12 @@ directories. Files in *src* that begin with :file:`.nfs` are skipped (more information on these files is available in answer D2 of the `NFS FAQ page - `_). + `_). .. versionchanged:: 3.3.1 NFS files are ignored. -.. function:: remove_tree(directory[, verbose=0, dry_run=0]) +.. function:: remove_tree(directory[, verbose=False, dry_run=False]) Recursively remove *directory* and all files and directories underneath it. Any errors are ignored (apart from being reported to ``sys.stdout`` if *verbose* is @@ -1043,7 +1043,7 @@ directories. This module contains some utility functions for operating on individual files. -.. function:: copy_file(src, dst[, preserve_mode=1, preserve_times=1, update=0, link=None, verbose=0, dry_run=0]) +.. function:: copy_file(src, dst[, preserve_mode=True, preserve_times=True, update=False, link=None, verbose=False, dry_run=False]) Copy file *src* to *dst*. If *dst* is a directory, then *src* is copied there with the same name; otherwise, it must be a filename. (If the file exists, it @@ -1216,7 +1216,7 @@ other utility module. .. % Should probably be moved into the standard library. -.. function:: execute(func, args[, msg=None, verbose=0, dry_run=0]) +.. function:: execute(func, args[, msg=None, verbose=False, dry_run=False]) Perform some action that affects the outside world (for instance, writing to the filesystem). Such actions are special because they are disabled by the @@ -1234,7 +1234,7 @@ other utility module. :exc:`ValueError` if *val* is anything else. -.. function:: byte_compile(py_files[, optimize=0, force=0, prefix=None, base_dir=None, verbose=1, dry_run=0, direct=None]) +.. function:: byte_compile(py_files[, optimize=0, force=False, prefix=None, base_dir=None, verbose=True, dry_run=False, direct=None]) Byte-compile a collection of Python source files to :file:`.pyc` files in a :file:`__pycache__` subdirectory (see :pep:`3147` and :pep:`488`). diff --git a/docs/deprecated/distutils/configfile.rst b/docs/deprecated/distutils/configfile.rst index ab199dcaf7..e012e5d233 100644 --- a/docs/deprecated/distutils/configfile.rst +++ b/docs/deprecated/distutils/configfile.rst @@ -96,7 +96,7 @@ configuration file for this distribution: .. code-block:: ini [build_ext] - inplace=1 + inplace=true This will affect all builds of this module distribution, whether or not you explicitly specify :command:`build_ext`. If you include :file:`setup.cfg` in @@ -131,13 +131,6 @@ Note that the ``doc_files`` option is simply a whitespace-separated string split across multiple lines for readability. -.. seealso:: - - :ref:`inst-config-syntax` in "Installing Python Modules" - More information on the configuration files is available in the manual for - system administrators. - - .. rubric:: Footnotes .. [#] This ideal probably won't be achieved until auto-configuration is fully diff --git a/docs/deprecated/distutils/examples.rst b/docs/deprecated/distutils/examples.rst index 00eef73fa9..54866cb261 100644 --- a/docs/deprecated/distutils/examples.rst +++ b/docs/deprecated/distutils/examples.rst @@ -335,4 +335,4 @@ loads its values:: .. % \section{Putting it all together} -.. _docutils: http://docutils.sourceforge.net +.. _docutils: https://docutils.sourceforge.io diff --git a/docs/deprecated/distutils/packageindex.rst b/docs/deprecated/distutils/packageindex.rst index ccb9a598b2..27ea717a78 100644 --- a/docs/deprecated/distutils/packageindex.rst +++ b/docs/deprecated/distutils/packageindex.rst @@ -6,11 +6,10 @@ The Python Package Index (PyPI) ******************************* -The `Python Package Index (PyPI)`_ stores metadata describing distributions -packaged with distutils and other publishing tools, as well the distribution -archives themselves. +The `Python Package Index (PyPI) `_ stores +metadata describing distributions packaged with distutils and +other publishing tools, as well the distribution archives +themselves. -References to up to date PyPI documentation can be found at -:ref:`publishing-python-packages`. - -.. _Python Package Index (PyPI): https://pypi.org +The best resource for working with PyPI is the +`Python Packaging User Guide `_. diff --git a/docs/deprecated/distutils/setupscript.rst b/docs/deprecated/distutils/setupscript.rst index ec9cf34ed7..de68a5c320 100644 --- a/docs/deprecated/distutils/setupscript.rst +++ b/docs/deprecated/distutils/setupscript.rst @@ -274,7 +274,7 @@ search path, though, you can find that directory using the Distutils :mod:`distutils.sysconfig` module:: from distutils.sysconfig import get_python_inc - incdir = os.path.join(get_python_inc(plat_specific=1), 'Numerical') + incdir = os.path.join(get_python_inc(plat_specific=True), 'Numerical') setup(..., Extension(..., include_dirs=[incdir]), ) @@ -644,7 +644,7 @@ Notes: 'long string' Multiple lines of plain text in reStructuredText format (see - http://docutils.sourceforge.net/). + https://docutils.sourceforge.io/). 'list of strings' See below. diff --git a/docs/deprecated/distutils/uploading.rst b/docs/deprecated/distutils/uploading.rst index 4c391cab07..f5c4c619ab 100644 --- a/docs/deprecated/distutils/uploading.rst +++ b/docs/deprecated/distutils/uploading.rst @@ -4,5 +4,6 @@ Uploading Packages to the Package Index *************************************** -References to up to date PyPI documentation can be found at -:ref:`publishing-python-packages`. +See the +`Python Packaging User Guide `_ +for the best guidance on uploading packages. diff --git a/docs/deprecated/index.rst b/docs/deprecated/index.rst index 0ea66cf644..9db1729a40 100644 --- a/docs/deprecated/index.rst +++ b/docs/deprecated/index.rst @@ -23,3 +23,13 @@ objectives. distutils-legacy functionalities commands + pkg_resources + +Notes for Consumers of Packages Built with Setuptools +===================================================== + + +.. toctree:: + :maxdepth: 1 + + sdist-reproducibility diff --git a/docs/pkg_resources.rst b/docs/deprecated/pkg_resources.rst similarity index 97% rename from docs/pkg_resources.rst rename to docs/deprecated/pkg_resources.rst index d5ebffab55..fd0f37ba2b 100644 --- a/docs/pkg_resources.rst +++ b/docs/deprecated/pkg_resources.rst @@ -2,7 +2,54 @@ Package Discovery and Resource Access using ``pkg_resources`` ============================================================= -The ``pkg_resources`` module distributed with ``setuptools`` provides an API +.. attention:: **This documentation is retained solely for historical purposes** + + ``pkg_resources`` has long been **discouraged** due to architectural + limitations that led to persistent performance issues. + These limitations were inherent to its design (e.g. importing on startup, + scanning the entire environment for metadata, and eager, global + working‑set management) and could not be corrected. + + .. version-deprecated:: v67.5.0 + ``pkg_resources`` issued official deprecation warnings as early as + ``setuptools`` **v67.5.0**. + + .. version-removed:: v82.0.0 + ``pkg_resources`` is no longer maintained, no longer used internally by + ``setuptools``, and is no longer included in current + distributions/installations as of ``setuptools`` **v82.0.0**. + + Projects must migrate away from ``pkg_resources``. The recommended + replacements are: + + * Resource access: use :mod:`importlib.resources` + (or its backport :pypi:`importlib_resources`). + * Distribution metadata & entry points: use :mod:`importlib.metadata` + (or its backport :pypi:`importlib_metadata`). + * Requirement and version parsing: use :pypi:`packaging`. + This includes parsing and evaluating ``extras`` and markers via + ``packaging.requirements.Requirement`` and ``packaging.markers.Marker``. + Note that automatic installation or detection of extras is not provided; + projects requiring that behaviour must implement it themselves using + a combination of ``packaging``, ``importlib.metadata`` and other tools + as building blocks. + * Coexistence of multiple versions of a package: please consider using a different + approach, as this functionality is not supported by Python itself. + Alternatives include isolated environments and orchestration tools + (:mod:`venv`, :pypi:`tox`, :pypi:`nox`, etc.). + * Handling of ``.egg`` distributions: please consider using a different + approach, as the ``.egg`` and ``easy_install`` mechanisms have also been + discontinued. + Please use currently supported packaging formats + (see :external+PyPUG:doc:`specifications/section-distribution-formats`) + and build/installation workflows (see :pep:`517`). + + **Note:** The following documentation may no longer accurately describe the + behaviour of the distributed package and has been frozen at the last + ``setuptools`` release that still contained ``pkg_resources``. + + +The ``pkg_resources`` module provides an API for Python libraries to access their resource files, and for extensible applications and frameworks to automatically discover plugins. It also provides runtime support for using C extensions that are inside zipfile-format @@ -10,15 +57,6 @@ eggs, support for merging packages that have separately-distributed modules or subpackages, and APIs for managing Python's current "working set" of active packages. -.. attention:: - Use of ``pkg_resources`` is deprecated in favor of - :mod:`importlib.resources`, :mod:`importlib.metadata` - and their backports (:pypi:`importlib_resources`, :pypi:`importlib_metadata`). - Some useful APIs are also provided by :pypi:`packaging` (e.g. requirements - and version parsing). - Users should refrain from new usage of ``pkg_resources`` and - should work to port to importlib-based solutions. - -------- Overview @@ -108,7 +146,7 @@ eggs (For more information about these terms and concepts, see also this `architectural overview`_ of ``pkg_resources`` and Python Eggs in general.) -.. _architectural overview: http://mail.python.org/pipermail/distutils-sig/2005-June/004652.html +.. _architectural overview: https://mail.python.org/pipermail/distutils-sig/2005-June/004652.html .. ----------------- diff --git a/docs/deprecated/python_eggs.rst b/docs/deprecated/python_eggs.rst index 59d1adc55b..4bb099e01b 100644 --- a/docs/deprecated/python_eggs.rst +++ b/docs/deprecated/python_eggs.rst @@ -131,12 +131,12 @@ egg filename is as follows:: name ["-" version ["-py" pyver ["-" required_platform]]] "." ext -The "name" and "version" should be escaped using the ``to_filename()`` -function provided by ``pkg_resources``, after first processing them with -``safe_name()`` and ``safe_version()`` respectively. These latter two -functions can also be used to later "unescape" these parts of the -filename. (For a detailed description of these transformations, please -see the "Parsing Utilities" section of the ``pkg_resources`` manual.) +The "name" and "version" should be escaped using ``pkg_resources`` functions +``safe_name()`` and ``safe_version()`` respectively then using +``to_filename()``. Note that the escaping is irreversible and the original +name can only be retrieved from the distribution metadata. For a detailed +description of these transformations, please see the "Parsing Utilities" +section of the ``pkg_resources`` manual. The "pyver" string is the Python major version, as found in the first 3 characters of ``sys.version``. "required_platform" is essentially @@ -193,6 +193,14 @@ Python version, or platform information is included. When the runtime searches for available eggs, ``.egg-link`` files are opened and the actual egg file/directory name is read from them. +Note: Due to `pypa/setuptools#4167 +`_, the name in the egg-link +filename does not match the filename components used in similar files, but +instead presents with dash separators instead of underscore separators. For +compatibility with pip prior to version 24.0, these dash separators are +retained. In a future release, pip 24 or later will be required and the +underscore separators will be used. + Each ``.egg-link`` file should contain a single file or directory name, with no newlines. This filename should be the base location of one or more eggs. That is, the name must either end in ``.egg``, or else it diff --git a/docs/deprecated/sdist-reproducibility.rst b/docs/deprecated/sdist-reproducibility.rst new file mode 100644 index 0000000000..208f594763 --- /dev/null +++ b/docs/deprecated/sdist-reproducibility.rst @@ -0,0 +1,202 @@ +=========================================================================================== +Drawbacks of installing source distributions (``sdist``) and how to improve reproducibility +=========================================================================================== + + +.. admonition:: Scope and audience + + This page contains relevant information for **package consumers** (people + installing third-party projects that may have been built with Setuptools). + It explains why installing from :external+PyPUG:term:`Source Distributions + ` can be less predictable than installing + from :external+PyPUG:term:`wheels `, and contains tips on how to improve + **installation-time** reproducibility. It does **not** describe how to build + packages with Setuptools, nor is it a statement of policy about what + publishers must do [#publishing]_. + + +The ``sdist`` format was one of the first packaging formats to be created by the +Python community (predating the advent of ``wheel``). Although very +useful today to distribute and share Python libraries and applications, +``sdist``\s are notoriously difficult to work with in circumstances that +require high build reproducibility and tolerance to disruptions. + +This guide reviews the concept of ``sdist``, highlights its potential uses +and drawbacks and explores potential practices to improve build reproducibility +when relying on ``sdist``\s. + + +What is an ``sdist``? +===================== + +You can read more about the ``sdist`` format and its ``wheel`` counterpart in +:external+PyPUG:doc:`discussions/package-formats`, but for the sake of this +document an ``sdist`` can be considered a simple ``.tar.gz`` archive that +contains all the files necessary to build a Python project that later will be +installed in the end-user's environment. + +The most defining characteristic of the ``sdist`` format is its +platform-independence, as the distributions do not include binary executable files. +This format is very flexible and, although usually composed by a simple copy +of the source code files with some extra metadata files added, it can also include +platform-independent code automatically generated during the build +phase [#examples]_. + + +When is an ``sdist`` useful? +============================ + +Sometimes it can be tricky to distribute Python packages that contain binary +extensions, especially when they are built for platforms that do not define a +cross-version stable ABI_. +Moreover package indexes like PyPI_ may restrict their offer to a handful of +well-known platforms. +Finally, for certain edge cases, the build process may require machine specific +parameters. + +In this context, distributing code via ``sdist``\s becomes a valuable fallback. +It allows users in other platforms to access the source code +and attempt to recompile the extensions locally. + + +What are the drawbacks of an ``sdist``? +======================================= + +Despite their usefulness, working with ``sdist``\s can be challenging. One +major difficulty is reconstructing a compatible build environment in which the +``sdist`` can be processed into a ``wheel``, especially when it comes to build +dependencies. + +While :pep:`518` introduced a standard for declaring build dependencies +distributed as Python packages (e.g. via PyPI), many projects also rely on +non-Python dependencies, such as compilers and binary system-level libraries, +that are not declared as a standard metadata. These dependencies can vary +significantly across systems and its installation is often not automated and +undocumented, i.e., simply assumed to be present. + +Another issue is *tooling drift*: even if a project was originally buildable +from its ``sdist``, changes in the build dependencies (e.g., updates, +deprecations and security fixes) can break compatibility over time [#pinning]_. +This is a natural tendency of software systems and especially true for older +projects. + +Therefore, mission-critical systems and environments that cannot afford +unforeseen/unintended interruptions should not rely on ``sdist``\s. +If your project or product requires high reliability and minimal disruption, +you should adapt your workflow to increase resiliency and reproducibility or +disallow ``sdist``\s all together. + + +How to improve reproducibility in your workflow and avoid ``sdist`` drawbacks? +============================================================================== + +The first step to improve your workflow is to determine whether your workflow +is directly or indirectly relying on ``sdist``\s — and to prevent them from being +compiled on demand. + +Installers like ``pip`` or ``uv`` have options that help with this. +For example, you can set the environment variable |PIP_ONLY_BINARY|_ with +the value ``:all:``, to prevent ``sdist``\s from being installed +(see the corresponding `uv alternative`_). +When this setting is enabled, any installation that fails will indicate which +packages are not available as ``wheel``\s, helping you pinpoint installations +relying on ``sdist``\s. + +Once these packages are identified, the next step is to build them in +a controlled environment. +You can use ``pip``\'s |PIP_CONSTRAINT|_ / |PIP_BUILD_CONSTRAINT|_ +environment variables or the +|build-constraint|_ ``uv``\'s CLI option to enforce specific versions of +Python packages [#build-isolation]_. + +To further improve the consistency of OS-level tools and libraries, +you can leverage your CI/CD provider's configuration method, for example +`GitHub Workflows`_, `Bitbucket Pipelines`_, `GitLab CI/CD`_, Jenkins_, +CircleCI_ or Semaphore_. + +Alternatively, you can use containers (e.g. docker_, nerdctl_ or podman_), +immutable operating system distributions or package managers (e.g. `NixOS/Nix`_) +or configuration management tools (e.g. Ansible_, chef_ or puppet_) +to implement `Infrastructure as Code`_ (IaC) and ensure build environments +are reproducible and version-controlled. + +Consider caching the resulting ``wheel``\s +locally via |wheelhouse directories|_ or hosting them in +*private package indexes* (such as devpi_). +This allows you to serve pre-built distributions internally, +which reduces reliance on external sources, improves build stability, +and often results in faster workflows as a welcome side effect. + +Finally, it's important to regularly audit your pinned or cached (build) +dependencies for known security vulnerabilities and critical bug fixes and/or +update them accordingly. +This can be done through an *out-of-band* workflow — such as a scheduled job +or a monthly CI/CD pipeline — that does not interfere with your +mission-critical or low-tolerance environments. This approach ensures that your +systems remain secure and up to date without compromising the stability of your +primary workflows. + + +.. rubric:: Footnotes + +.. [#publishing] + The PyPA recommendation, documented in the `packaging tutorial`_, is to + publish both ``sdists`` and ``wheels``. + +.. [#examples] + Examples of platform-independent generated code in ``sdist``\s include + ``.pyx`` files transpiled into ``.c`` and Python code created from + ``.proto``, JSON schema or grammar files, etc. + +.. [#pinning] + Although developers can try to minimize the impact of tooling drift by + locking the version of build dependencies, this approach also has + its own drawbacks. In fact, it is very common in the Python community to + avoid specifying version caps. For a deeper discussion on this topic, see: + https://iscinumpy.dev/post/bound-version-constraints/ and + https://hynek.me/articles/semver-will-not-save-you/. + +.. [#build-isolation] + When a virtual environment with hand picked versions of build dependencies + is crafted (either manually or via tools supporting one of the + :external+PyPUG:doc:`specifications/pylock-toml` or + :external+pip:doc:`reference/requirements-file-format`), it is also possible + to use features like |no-isolation|_, |no-build-isolation|_ or the + `equivalent uv settings`_ to ensure packages are built against the currently + active virtual environment. + + +.. _ABI: https://en.wikipedia.org/wiki/Application_binary_interface +.. _PyPI: https://pypi.org +.. |PIP_ONLY_BINARY| replace:: ``PIP_ONLY_BINARY`` +.. _PIP_ONLY_BINARY: https://pip.pypa.io/en/stable/cli/pip_install/#cmdoption-only-binary +.. _uv alternative: https://docs.astral.sh/uv/reference/settings/#pip_only-binary +.. |PIP_CONSTRAINT| replace:: ``PIP_CONSTRAINT`` +.. _PIP_CONSTRAINT: https://pip.pypa.io/en/stable/cli/pip_install/#cmdoption-c +.. |PIP_BUILD_CONSTRAINT| replace:: ``PIP_BUILD_CONSTRAINT`` +.. _PIP_BUILD_CONSTRAINT: https://pip.pypa.io/en/stable/cli/pip_download/#cmdoption-build-constraint +.. |build-constraint| replace:: ``--build-constraint`` +.. _build-constraint: https://docs.astral.sh/uv/concepts/projects/build/#build-constraints +.. _GitHub Workflows: https://docs.github.com/en/actions/writing-workflows +.. _Bitbucket Pipelines: https://www.atlassian.com/software/bitbucket/features/pipelines +.. _GitLab CI/CD: https://docs.gitlab.com/ci/ +.. _Jenkins: https://www.jenkins.io/doc/ +.. _CircleCI: https://circleci.com +.. _Semaphore: https://semaphore.io +.. _docker: https://www.docker.com +.. _nerdctl: https://github.com/containerd/nerdctl +.. _podman: https://podman.io +.. _NixOS/Nix: https://nixos.org +.. _Ansible: https://docs.ansible.com +.. _chef: https://docs.chef.io +.. _puppet: https://www.puppet.com/docs/index.html +.. _Infrastructure as Code: https://en.wikipedia.org/wiki/Infrastructure_as_code +.. |wheelhouse directories| replace:: *"wheelhouse" directories* +.. _wheelhouse directories: https://pip.pypa.io/en/stable/cli/pip_wheel/#examples +.. _devpi: https://doc.devpi.net/ +.. |no-isolation| replace:: ``--no-isolation`` +.. _no-isolation: https://build.pypa.io/en/stable/#python--m-build---no-isolation +.. |no-build-isolation| replace:: ``--no-build-isolation`` +.. _no-build-isolation: https://pip.pypa.io/en/stable/cli/pip_install/#cmdoption-no-build-isolation +.. _equivalent uv settings: https://docs.astral.sh/uv/concepts/projects/config/#build-isolation +.. _packaging tutorial: https://packaging.python.org/en/latest/tutorials/packaging-projects/#generating-distribution-archives diff --git a/docs/development/developer-guide.rst b/docs/development/developer-guide.rst index 88ac282a87..917594cd34 100644 --- a/docs/development/developer-guide.rst +++ b/docs/development/developer-guide.rst @@ -109,7 +109,7 @@ To build the docs locally, use tox:: $ tox -e docs -.. _Sphinx: http://www.sphinx-doc.org/en/master/ +.. _Sphinx: https://www.sphinx-doc.org/en/master/ .. _published documentation: https://setuptools.pypa.io/en/latest/ --------------------- @@ -122,8 +122,7 @@ cannot be declared as they won't be resolved soon enough to build setuptools from source. Eventually, this limitation may be lifted as PEP 517/518 reach ubiquitous adoption, but for now, Setuptools cannot declare dependencies other than through -``setuptools/_vendor/vendored.txt`` and -``pkg_resources/_vendor/vendored.txt``. +``setuptools/_vendor/vendored.txt``. All the dependencies specified in these files are "vendorized" using a simple Python script ``tools/vendor.py``. @@ -131,3 +130,58 @@ simple Python script ``tools/vendor.py``. To refresh the dependencies, run the following command:: $ tox -e vendor + + +------------------------------------ +Code conventions and other practices +------------------------------------ + +Setuptools utilizes the `skeleton `_ +framework as a foundation for sharing reusable maintenance tasks +across different projects in the ecosystem. + +This also means that the project adheres to the same coding conventions +and other practices described in the `skeleton documentation +`_. + +Moreover, changes in the code base should be kept as compatible as possible +to ``skeleton`` to avoid merge conflicts, or accidental regressions on +periodical merges. + +Finally, the ``setuptools/_distutils`` directory should not be modified +directly when contributing to the ``setuptools`` project. +Instead, this directory is maintained as a separated project in +https://github.com/pypa/distutils, and periodically merged into ``setuptools``. + + +---------------- +Type annotations +---------------- + +Most standards and best practices are enforced by +`Ruff `_'s ``ANN2``, ``FA``, ``PYI``, ``UP`` +and ``YTT`` rules. + +Explicit return types have to be added for typed public functions whose +parameters are *all* annotated. This is enforced by ``ANN2``, but it's worth noting +that this is due to mypy inferring ``Any`` even for simple return types. Mypy also +doesn't count functions with missing parameter annotations as "typed". (see +`python/mypy#4409 `_, +`python/mypy#10149 `_ and +`python/mypy#6646 `_). +Otherwise, return annotations can be omitted to reduce verbosity, +especially for complex return types. + +Instead of typing an explicit return type annotation as +``Generator[..., None, None]``, we'll prefer using an ``Iterator`` as it is more +concise and conceptually easier to deal with. Returning a ``Generator`` with no +``yield`` type or ``send`` type can sometimes be considered as exposing +implementation details. See +`Y058 `_. + +Avoid importing private type-checking-only symbols. These are often +`typeshed `_ internal details and are not +guaranteed to be stable. +Importing from ``_typeshed`` or ``typing_extensions`` is fine, but if you find +yourself importing the same symbol in ``TYPE_CHECKING`` blocks a lot, consider +implementing an alias directly in ``setuptools``. diff --git a/docs/history.rst b/docs/history.rst index 4f302ca06b..7a4bb4dbee 100644 --- a/docs/history.rst +++ b/docs/history.rst @@ -5,6 +5,9 @@ History ******* +.. meta:: + :keywords: changelog + .. towncrier-draft-entries:: DRAFT, unreleased as on |today| .. include:: ../NEWS (links).rst diff --git a/docs/index.rst b/docs/index.rst index 3e6b021648..a2163422f6 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -9,7 +9,7 @@ designed to facilitate packaging Python projects. It helps developers to easily share reusable code (in the form of a library) and programs (e.g., CLI/GUI tools implemented in Python), that can be installed -with :pypi:`pip` and uploaded to `PyPI `_. +with :pypi:`pip` and uploaded to `PyPI `_. .. sidebar-links:: :home: @@ -21,7 +21,6 @@ with :pypi:`pip` and uploaded to `PyPI `_. User guide build_meta - pkg_resources references/keywords setuptools diff --git a/docs/references/keywords.rst b/docs/references/keywords.rst index 6173e3c228..41d30c33d4 100644 --- a/docs/references/keywords.rst +++ b/docs/references/keywords.rst @@ -182,11 +182,32 @@ extensions). .. _keyword/data_files: ``data_files`` - .. warning:: - ``data_files`` is deprecated. It does not work with wheels, so it - should be avoided. + .. attention:: + **DISCOURAGED** - This is an advanced feature and it is + *not intended to work with absolute paths*. + All files listed in ``data_files`` will be installed in paths relative + to a directory decided by the package installer (e.g. `pip`). + This usually results in nesting under a virtual environment. + We **STRONGLY ADVISE AGAINST** using this setting for things like + application launchers, desktop files or anything that requires + system-wide installation [#manpages]_, unless you have extensive + experience in Python packaging and have carefully considered all the + drawbacks, limitations and problems of this method. + Also note that this feature is provided *as is* with no plans of + further changes. + + .. tip:: + See :doc:`/userguide/datafiles` for an alternative method that uses the + package directory itself and works well with :mod:`importlib.resources`, + or consider using libraries such as :pypi:`platformdirs` for creating + and managing files at runtime (i.e., **not** during the installation). - A list of strings specifying the data files to install. + A sequence of ``(directory, files)`` pairs specifying the data files to install + (``directory`` is a :class:`str`, ``files`` is a sequence of :class:`str`). + Each ``(directory, files)`` pair in the sequence specifies the installation directory + and the files to install there. + +.. _discussion in Python discourse: https://discuss.python.org/t/should-there-be-a-new-standard-for-installing-arbitrary-data-files/7853/63 .. _keyword/package_dir: @@ -499,3 +520,10 @@ extensions). An arbitrary map of URL names to hyperlinks, allowing more extensible documentation of where various resources can be found than the simple ``url`` and ``download_url`` options provide. + + +.. [#manpages] It is common for developers to attempt using ``data_files`` for manpages. + Please note however that depending on the installation directory, this will + not work out of the box - often the final user is required to change the + ``MANPATH`` environment variable. + See the `discussion in Python discourse`_ for more details. diff --git a/docs/setuptools.rst b/docs/setuptools.rst index 5317058945..ce1962706c 100644 --- a/docs/setuptools.rst +++ b/docs/setuptools.rst @@ -3,9 +3,8 @@ Building and Distributing Packages with Setuptools ================================================== ``Setuptools`` is a collection of enhancements to the Python ``distutils`` -that allow developers to more easily build and -distribute Python packages, especially ones that have dependencies on other -packages. +that allow developers to more easily build Python packages, including those +that have dependencies on other packages and C/C++ extension modules. Packages built and distributed using ``setuptools`` look to the user like ordinary Python packages based on the ``distutils``. @@ -21,9 +20,9 @@ Feature Highlights: individually in setup.py * Automatically include all relevant files in your source distributions, - without needing to create a |MANIFEST.in|_ file, and without having to force - regeneration of the ``MANIFEST`` file when your source tree changes - [#manifest]_. + without needing to create a :ref:`MANIFEST.in ` file, + and without having to force regeneration of the ``MANIFEST`` file when your + source tree changes [#manifest]_. * Automatically generate wrapper scripts or Windows (console and GUI) .exe files for any number of "main" functions in your project. (Note: this is not @@ -221,7 +220,3 @@ set of steps to reproduce. any special C header). See :ref:`Controlling files in the distribution` and :doc:`userguide/datafiles` for more information about complex scenarios, if you want to include other types of files. - - -.. |MANIFEST.in| replace:: ``MANIFEST.in`` -.. _MANIFEST.in: https://packaging.python.org/en/latest/guides/using-manifest-in/ diff --git a/docs/userguide/datafiles.rst b/docs/userguide/datafiles.rst index 5cd576e0b7..72a658ee9c 100644 --- a/docs/userguide/datafiles.rst +++ b/docs/userguide/datafiles.rst @@ -2,6 +2,15 @@ Data Files Support ==================== +In the Python ecosystem, the term "data files" is used in various complex scenarios +and can have nuanced meanings. For the purposes of this documentation, +we define "data files" as non-Python files that are installed alongside Python +modules and packages on the user's machine when they install a +:term:`distribution ` via :term:`wheel `. + +These files are typically intended for use at **runtime** by the package itself or +to influence the behavior of other packages or systems. + Old packaging installation methods in the Python ecosystem have traditionally allowed installation of "data files", which are placed in a platform-specific location. However, the most common use case @@ -10,12 +19,20 @@ by including the data files **inside the package directory**. Setuptools focuses on this most common type of data files and offers three ways of specifying which files should be included in your packages, as described in -the following sections. +the following section. -include_package_data -==================== -First, you can simply use the ``include_package_data`` keyword. +Configuration Options +===================== + + +.. _include-package-data: + +1. ``include_package_data`` +--------------------------- + +First, you can use the ``include_package_data`` keyword. + For example, if the package tree looks like this:: project_root_directory @@ -28,7 +45,38 @@ For example, if the package tree looks like this:: ├── data1.txt └── data2.txt -and you supply this configuration: +When **at least one** of the following conditions are met: + +1. These files are included via the :ref:`MANIFEST.in ` file, + like so:: + + include src/mypkg/*.txt + include src/mypkg/*.rst + +2. They are being tracked by a revision control system such as Git, Mercurial + or SVN, **AND** you have configured an appropriate plugin such as + :pypi:`setuptools-scm` or :pypi:`setuptools-svn`. + (See the section below on :ref:`Adding Support for Revision + Control Systems` for information on how to configure such plugins.) + +then all the ``.txt`` and ``.rst`` files will be included into +the source distribution. + +To further include them into the ``wheels``, you can use the +``include_package_data`` keyword: + +.. tab:: pyproject.toml + + .. code-block:: toml + + [tool.setuptools] + # ... + # By default, include-package-data is true in pyproject.toml, + # so you do NOT have to specify this line. + include-package-data = true + + [tool.setuptools.packages.find] + where = ["src"] .. tab:: setup.cfg @@ -56,35 +104,18 @@ and you supply this configuration: include_package_data=True ) -.. tab:: pyproject.toml - - .. code-block:: toml - - [tool.setuptools] - # ... - # By default, include-package-data is true in pyproject.toml, so you do - # NOT have to specify this line. - include-package-data = true - - [tool.setuptools.packages.find] - where = ["src"] - -then all the ``.txt`` and ``.rst`` files will be automatically installed with -your package, provided: - -1. These files are included via the |MANIFEST.in|_ file, like so:: +.. note:: + .. versionadded:: v61.0.0 + The default value for ``tool.setuptools.include-package-data`` is ``true`` + when projects are configured via ``pyproject.toml``. + This behaviour differs from ``setup.cfg`` and ``setup.py`` + (where ``include_package_data`` is ``False`` by default), which was not changed + to ensure backwards compatibility with existing projects. - include src/mypkg/*.txt - include src/mypkg/*.rst +.. _package-data: -2. OR, they are being tracked by a revision control system such as Git, Mercurial - or SVN, and you have configured an appropriate plugin such as - :pypi:`setuptools-scm` or :pypi:`setuptools-svn`. - (See the section below on :ref:`Adding Support for Revision - Control Systems` for information on how to write such plugins.) - -package_data -============ +2. ``package_data`` +------------------- By default, ``include_package_data`` considers **all** non ``.py`` files found inside the package directory (``src/mypkg`` in this case) as data files, and includes those that @@ -107,6 +138,16 @@ For example, if the package tree looks like this:: then you can use the following configuration to capture the ``.txt`` and ``.rst`` files as data files: +.. tab:: pyproject.toml + + .. code-block:: toml + + [tool.setuptools.packages.find] + where = ["src"] + + [tool.setuptools.package-data] + mypkg = ["*.txt", "*.rst"] + .. tab:: setup.cfg .. code-block:: ini @@ -137,29 +178,19 @@ data files: package_data={"mypkg": ["*.txt", "*.rst"]} ) -.. tab:: pyproject.toml - - .. code-block:: toml - - [tool.setuptools.packages.find] - where = ["src"] - - [tool.setuptools.package-data] - mypkg = ["*.txt", "*.rst"] - The ``package_data`` argument is a dictionary that maps from package names to lists of glob patterns. Note that the data files specified using the ``package_data`` -option neither require to be included within a |MANIFEST.in|_ file, nor -require to be added by a revision control system plugin. +option neither require to be included within a :ref:`MANIFEST.in ` +file, nor require to be added by a revision control system plugin. .. note:: If your glob patterns use paths, you *must* use a forward slash (``/``) as - the path separator, even if you are on Windows. Setuptools automatically + the path separator, even if you are on Windows. ``setuptools`` automatically converts slashes to appropriate platform-specific separators at build time. -.. note:: - Glob patterns do not automatically match dotfiles (directory or file names - starting with a dot (``.``)). To include such files, you must explicitly start +.. important:: + Glob patterns do not automatically match dotfiles, i.e., directory or file names + starting with a dot (``.``). To include such files, you must explicitly start the pattern with a dot, e.g. ``.*`` to match ``.gitignore``. If you have multiple top-level packages and a common pattern of data files for all these @@ -180,6 +211,17 @@ Here, both packages ``mypkg1`` and ``mypkg2`` share a common pattern of having ` data files. However, only ``mypkg1`` has ``.rst`` data files. In such a case, if you want to use the ``package_data`` option, the following configuration will work: +.. tab:: pyproject.toml + + .. code-block:: toml + + [tool.setuptools.packages.find] + where = ["src"] + + [tool.setuptools.package-data] + "*" = ["*.txt"] + mypkg1 = ["data1.rst"] + .. tab:: setup.cfg .. code-block:: ini @@ -210,31 +252,40 @@ use the ``package_data`` option, the following configuration will work: package_data={"": ["*.txt"], "mypkg1": ["data1.rst"]}, ) -.. tab:: pyproject.toml - - .. code-block:: toml - - [tool.setuptools.packages.find] - where = ["src"] - - [tool.setuptools.package-data] - "*" = ["*.txt"] - mypkg1 = ["data1.rst"] - Notice that if you list patterns in ``package_data`` under the empty string ``""`` in ``setup.py``, and the asterisk ``*`` in ``setup.cfg`` and ``pyproject.toml``, these patterns are used to find files in every package. For example, we use ``""`` or ``*`` to indicate that the ``.txt`` files from all packages should be captured as data files. +These placeholders are treated as a special case, ``setuptools`` **do not** +support glob patterns on package names for this configuration +(patterns are only supported on the file paths). Also note how we can continue to specify patterns for individual packages, i.e. we specify that ``data1.rst`` from ``mypkg1`` alone should be captured as well. .. note:: - When building an ``sdist``, the datafiles are also drawn from the - ``package_name.egg-info/SOURCES.txt`` file, so make sure that this is removed if - the ``setup.py`` ``package_data`` list is updated before calling ``setup.py``. + When building an ``sdist``, the data files are also drawn from the + ``package_name.egg-info/SOURCES.txt`` file which works as a form of cache. + So make sure that this file is removed if ``package_data`` is updated, + before re-building the package. -exclude_package_data -==================== +.. attention:: + In Python any directory is considered a package + (even if it does not contain ``__init__.py``, + see *native namespaces packages* on :doc:`PyPUG:guides/packaging-namespace-packages`). + Therefore, if you are not relying on :doc:`automatic discovery `, + you *SHOULD* ensure that **all** packages (including the ones that don't + contain any Python files) are included in the ``packages`` configuration + (see :doc:`/userguide/package_discovery` for more information). + + Moreover, it is advisable to use full packages name using the dot + notation instead of a nested path, to avoid error prone configurations. + Please check :ref:`section subdirectories ` below. + + +.. _exclude-package-data: + +3. ``exclude_package_data`` +--------------------------- Sometimes, the ``include_package_data`` or ``package_data`` options alone aren't sufficient to precisely define what files you want included. For example, @@ -249,6 +300,16 @@ Supposing you want to prevent these files from being included in the installation (they are not relevant to Python or the package), then you could use the ``exclude_package_data`` option: +.. tab:: pyproject.toml + + .. code-block:: toml + + [tool.setuptools.packages.find] + where = ["src"] + + [tool.setuptools.exclude-package-data] + mypkg = [".gitattributes"] + .. tab:: setup.cfg .. code-block:: ini @@ -280,16 +341,6 @@ use the ``exclude_package_data`` option: exclude_package_data={"mypkg": [".gitattributes"]}, ) -.. tab:: pyproject.toml - - .. code-block:: toml - - [tool.setuptools.packages.find] - where = ["src"] - - [tool.setuptools.exclude-package-data] - mypkg = [".gitattributes"] - The ``exclude_package_data`` option is a dictionary mapping package names to lists of wildcard patterns, just like the ``package_data`` option. And, just as with that option, you can use the empty string key ``""`` in ``setup.py`` and the @@ -299,6 +350,68 @@ Any files that match these patterns will be *excluded* from installation, even if they were listed in ``package_data`` or were included as a result of using ``include_package_data``. +.. _interplay_package_data_keywords: + +Interplay between these keywords +-------------------------------- + +Meanwhile, to further clarify the interplay between these three keywords, +to include certain data file into the source distribution, the following +logic condition has to be met:: + + MANIFEST.in or (package-data and not exclude-package-data) + +In plain language, the file should be either: + +1. included in ``MANIFEST.in``; or + +2. selected by ``package-data`` AND not excluded by ``exclude-package-data``. + +To include some data file into the ``.whl``:: + + (not exclude-package-data) and ((include-package-data and MANIFEST.in) or package-data) + +In other words, the file should not be excluded by ``exclude-package-data`` +(highest priority), AND should be either: + +1. selected by ``package-data``; or + +2. selected by ``MANIFEST.in`` AND use ``include-package-data = true``. + +Summary +------- + +In summary, the three options allow you to: + +``include_package_data`` + Accept all data files and directories matched by + :ref:`MANIFEST.in ` or added by + a :ref:`plugin `. + +``package_data`` + Specify additional patterns to match files that may or may + not be matched by :ref:`MANIFEST.in ` + or added by a :ref:`plugin `. + +``exclude_package_data`` + Specify patterns for data files and directories that should *not* be + included when a package is installed, even if they would otherwise have + been included due to the use of the preceding options. + +.. note:: + Due to the way the build process works, a data file that you + include in your project and then stop including may be "orphaned" in your + project's build directories, requiring you to manually deleting them. + This may also be important for your users and contributors + if they track intermediate revisions of your project using Subversion; be sure + to let them know when you make changes that remove files from inclusion so they + can also manually delete them. + + See also troubleshooting information in :ref:`Caching and Troubleshooting`. + + +.. _subdir-data-files: + Subdirectory for Data Files =========================== @@ -320,8 +433,28 @@ Here, the ``.rst`` files are placed under a ``data`` subdirectory inside ``mypkg while the ``.txt`` files are directly under ``mypkg``. In this case, the recommended approach is to treat ``data`` as a namespace package -(refer :pep:`420`). With ``package_data``, -the configuration might look like this: +(refer :pep:`420`). This way, you can rely on the same methods described above, +using either :ref:`package-data` or :ref:`include-package-data`. +For the sake of completeness, we include below configuration examples +for the subdirectory structure, but please refer to the detailed +information in the previous sections of this document. + +With :ref:`package-data`, the configuration might look like this: + +.. tab:: pyproject.toml + + .. code-block:: toml + + # Scanning for namespace packages in the ``src`` directory is true by + # default in pyproject.toml, so you do NOT need to include the + # `tool.setuptools.packages.find` if it looks like the following: + # [tool.setuptools.packages.find] + # namespaces = true + # where = ["src"] + + [tool.setuptools.package-data] + mypkg = ["*.txt"] + "mypkg.data" = ["*.rst"] .. tab:: setup.cfg @@ -357,28 +490,31 @@ the configuration might look like this: } ) +In other words, we allow ``setuptools`` to scan for namespace packages in the ``src`` directory, +which enables the ``data`` directory to be identified, and then, we separately specify data +files for the root package ``mypkg``, and the namespace package ``data`` under the package +``mypkg``. + +Alternatively, you can also rely on :ref:`include-package-data`. +Note that this is the default behaviour in ``pyproject.toml``, but you need to +manually enable scanning of namespace packages in ``setup.cfg`` or ``setup.py``: + .. tab:: pyproject.toml .. code-block:: toml + [tool.setuptools] + # ... + # By default, include-package-data is true in pyproject.toml, so you do + # NOT have to specify this line. + include-package-data = true + [tool.setuptools.packages.find] # scanning for namespace packages is true by default in pyproject.toml, so - # you do NOT need to include the following line. + # you need NOT include this configuration. namespaces = true where = ["src"] - [tool.setuptools.package-data] - mypkg = ["*.txt"] - "mypkg.data" = ["*.rst"] - -In other words, we allow Setuptools to scan for namespace packages in the ``src`` directory, -which enables the ``data`` directory to be identified, and then, we separately specify data -files for the root package ``mypkg``, and the namespace package ``data`` under the package -``mypkg``. - -With ``include_package_data`` the configuration is simpler: you simply need to enable -scanning of namespace packages in the ``src`` directory and the rest is handled by Setuptools. - .. tab:: setup.cfg .. code-block:: ini @@ -404,49 +540,9 @@ scanning of namespace packages in the ``src`` directory and the rest is handled include_package_data=True, ) -.. tab:: pyproject.toml - - .. code-block:: toml - - [tool.setuptools] - # ... - # By default, include-package-data is true in pyproject.toml, so you do - # NOT have to specify this line. - include-package-data = true - - [tool.setuptools.packages.find] - # scanning for namespace packages is true by default in pyproject.toml, so - # you need NOT include the following line. - namespaces = true - where = ["src"] - -Summary -======= - -In summary, the three options allow you to: - -``include_package_data`` - Accept all data files and directories matched by |MANIFEST.in|_ or added by - a :ref:`plugin `. - -``package_data`` - Specify additional patterns to match files that may or may - not be matched by |MANIFEST.in|_ or added by - a :ref:`plugin `. - -``exclude_package_data`` - Specify patterns for data files and directories that should *not* be - included when a package is installed, even if they would otherwise have - been included due to the use of the preceding options. - -.. note:: - Due to the way the build process works, a data file that you - include in your project and then stop including may be "orphaned" in your - project's build directories, requiring you to run ``setup.py clean --all`` to - fully remove them. This may also be important for your users and contributors - if they track intermediate revisions of your project using Subversion; be sure - to let them know when you make changes that remove files from inclusion so they - can run ``setup.py clean --all``. +To avoid common mistakes with :ref:`include-package-data`, +please ensure :ref:`MANIFEST.in ` is properly set +or use a revision control system plugin (see :doc:`/userguide/miscellaneous`). .. _Accessing Data Files at Runtime: @@ -516,6 +612,20 @@ See :doc:`importlib-resources:using` for detailed instructions. pre-existing file is found. +Data Files from Plugins and Extensions +====================================== + +You can resort to a :doc:`native/implicit namespace package +` (as a container for files) +if you want plugins and extensions to your package to contribute with package data files. +This way, all files will be listed during runtime +when :doc:`using importlib.resources `. +Note that, although not strictly guaranteed, mainstream Python package managers, +like :pypi:`pip` and derived tools, will install files belong to multiple distributions +that share a same namespace into the same directory in the file system. +This means that the overhead for :mod:`importlib.resources` will be minimum. + + Non-Package Data Files ====================== @@ -537,7 +647,3 @@ run time be included **inside the package**. .. [#files_api] Reference: https://importlib-resources.readthedocs.io/en/latest/using.html#migrating-from-legacy .. [#namespace_support] Reference: https://github.com/python/importlib_resources/pull/196#issuecomment-734520374 - - -.. |MANIFEST.in| replace:: ``MANIFEST.in`` -.. _MANIFEST.in: https://packaging.python.org/en/latest/guides/using-manifest-in/ diff --git a/docs/userguide/declarative_config.rst b/docs/userguide/declarative_config.rst index fa104b10e3..2f650e1746 100644 --- a/docs/userguide/declarative_config.rst +++ b/docs/userguide/declarative_config.rst @@ -11,12 +11,10 @@ Configuring setuptools using ``setup.cfg`` files build API) is desired, a ``setup.py`` file containing a ``setup()`` function call is still required even if your configuration resides in ``setup.cfg``. -``Setuptools`` allows using configuration files (usually :file:`setup.cfg`) -to define a package’s metadata and other options that are normally supplied -to the ``setup()`` function (declarative config). +``Setuptools`` allows using configuration files (for example, :file:`setup.cfg`) +to define a package’s metadata and other options (declarative config). -This approach not only allows automation scenarios but also reduces -boilerplate code in some cases. +This approach allows automation scenarios and can reduce boilerplate code. .. _example-setup-config: @@ -39,10 +37,10 @@ boilerplate code in some cases. zip_safe = False include_package_data = True packages = find: - python_requires = >=3.7 + python_requires = >=3.8 install_requires = requests - importlib-metadata; python_version<"3.8" + importlib-metadata; python_version<"3.10" [options.package_data] * = *.txt, *.rst @@ -135,6 +133,24 @@ value associated with ``""`` in the ``package_dir`` dictionary. Please see :doc:`package discovery ` for more details. +Interpolation +============= + +Config files are parsed using :mod:`configparser` with +`interpolation `_ +enabled. As a result, one config value may reference another. This +feature may be used, for example, in defining extras: + +.. code-block:: ini + + [options.extras_require] + tester = + pytest==3.3.2 + pytest-sugar + dev = + pytest-xdist + %(tester)s + Specifying values ================= @@ -155,13 +171,25 @@ Type names used below: Special directives: -* ``attr:`` - Value is read from a module attribute. ``attr:`` supports - callables and iterables; unsupported types are cast using ``str()``. +* ``attr:`` - Value is read from a module attribute. + + It is advisable to use literal values together with ``attr:`` (e.g. ``str``, + ``tuple[str]``, see :func:`ast.literal_eval`). This is recommend + in order to support the common case of a literal value assigned to a variable + in a module containing (directly or indirectly) third-party imports. - In order to support the common case of a literal value assigned to a variable - in a module containing (directly or indirectly) third-party imports, ``attr:`` first tries to read the value from the module by examining the - module's AST. If that fails, ``attr:`` falls back to importing the module. + module's AST. If that fails, ``attr:`` falls back to importing the module, + using :func:`importlib.util.spec_from_file_location` recommended recipe + (see :ref:`example on Python docs ` + about "Importing a source file directly"). + Note however that importing the module is error prone since your package is + not installed yet. You may also need to manually add the project directory to + ``sys.path`` (via ``setup.py``) in order to be able to do that. + + When the module is imported, ``attr:`` supports + callables and iterables; unsupported types are cast using ``str()``. + * ``file:`` - Value is read from a list of files and then concatenated @@ -259,11 +287,11 @@ data_files section 40.6.0 [# [options] install_requires = - importlib-metadata; python_version<"3.8" + importlib-metadata; python_version<"3.10" [options.extras_require] all = - importlib-metadata; python_version < "3.8" + importlib-metadata; python_version<"3.10" .. [#opt-3] The ``find:`` and ``find_namespace:`` directive can be further configured in a dedicated subsection ``options.packages.find``. This subsection accepts the diff --git a/docs/userguide/dependency_management.rst b/docs/userguide/dependency_management.rst index 0feb346dc5..38ca7bdff7 100644 --- a/docs/userguide/dependency_management.rst +++ b/docs/userguide/dependency_management.rst @@ -18,10 +18,11 @@ Build system requirement ======================== After organizing all the scripts and files and getting ready for packaging, -there needs to be a way to specify what programs and libraries are actually needed -do the packaging (in our case, ``setuptools`` of course). -This needs to be specified in your ``pyproject.toml`` file -(if you have forgot what this is, go to :doc:`/userguide/quickstart` or :doc:`/build_meta`): +there needs to be a way to specify what programs and libraries (build backend) +are actually needed to build the package for distribution. For Setuptools, the +requisite library is ``setuptools``. Specify the build backend in a +``pyproject.toml`` file (see also :doc:`/userguide/quickstart` or +:doc:`/build_meta`): .. code-block:: toml @@ -29,13 +30,44 @@ This needs to be specified in your ``pyproject.toml`` file requires = ["setuptools"] #... -Please note that you should also include here any other ``setuptools`` plugin -(e.g., :pypi:`setuptools-scm`, :pypi:`setuptools-golang`, :pypi:`setuptools-rust`) +Also include any other ``setuptools`` plugins +(e.g., :pypi:`setuptools_scm`, :pypi:`setuptools-golang`, :pypi:`setuptools-rust`) or build-time dependency (e.g., :pypi:`Cython`, :pypi:`cppy`, :pypi:`pybind11`). +.. code-block:: toml + + [build-system] + requires = ["setuptools", "cython", "setuptools_scm"] + + +If the project depends on a feature introduced in a specific version of Setuptools, +it is good practice to specify it as a lower bound: + +.. code-block:: toml + + [build-system] + requires = ["setuptools >= 61.2"] + +Some may be tempted to also include an upper-bound for yet unreleased major +versions (e.g. ``setuptools <= 70``) or pin to a specific version (e.g. +``setuptools == 70.0.4``) in order to avoid the project being uninstallable +should those backward-incompatible changes affect this release of the project. +Setuptools maintainers recommend strongly against this precautionary approach. +The team primarily maintains one release, the latest monotonically-increasing +release, and encourages users to use that latest release (work at HEAD). As a +result, the team is cognizant of and takes responsibility for making +backward-incompatible changes and aims to mitigate the impact of any breaking +changes prior to releasing that change. By pinning against an unreleased +version, it causes toil (maintenance burden) for each and every project that +does the pinning (and the consumers that use it) and increases the risk of +erosion if maintenance is unsustained. This tradeoff between reproducibility +and compatibility is especially stark because Setuptools frequently releases +backward-incompatible releases for a variety of reasons, many of which won't +affect a given project. + .. note:: In previous versions of ``setuptools``, - this used to be accomplished with the ``setup_requires`` keyword but is + the ``setup_requires`` keyword performed a similar function but is now considered deprecated in favor of the :pep:`517` style described above. To peek into how this legacy keyword is used, consult our :doc:`guide on deprecated practice (WIP) `. diff --git a/docs/userguide/development_mode.rst b/docs/userguide/development_mode.rst index 9a79b08a93..881bc3a920 100644 --- a/docs/userguide/development_mode.rst +++ b/docs/userguide/development_mode.rst @@ -197,13 +197,6 @@ works (still within the context of :pep:`660`). Users are encouraged to try out the new editable installation techniques and make the necessary adaptations. -.. note:: - Newer versions of ``pip`` no longer run the fallback command - ``python setup.py develop`` when the ``pyproject.toml`` file is present. - This means that setting the environment variable - ``SETUPTOOLS_ENABLE_FEATURES="legacy-editable"`` - will have no effect when installing a package with ``pip``. - How editable installations work ------------------------------- @@ -236,6 +229,25 @@ More information is available on the text of :pep:`PEP 660 <660#what-to-put-in-t used. +Debugging Tips +-------------- + +If encountering problems installing a project in editable mode, +follow these recommended steps to help debug: + +- Try to install the project normally, without using the editable mode. + Does the error still persist? + (If it does, try fixing the problem before attempting the editable mode). +- When using binary extensions, make sure all OS-level + dependencies are installed (e.g. compilers, toolchains, binary libraries, ...). +- Try the latest version of setuptools (maybe the error was already fixed). +- When the project or its dependencies are using any setuptools extension + or customization, make sure they support the editable mode. + +After following the steps above, if the problem still persists and +you think this is related to how setuptools handles editable installations, +please submit a `reproducible example `_ at `the bug tracker `_. + ---- .. rubric:: Notes diff --git a/docs/userguide/entry_point.rst b/docs/userguide/entry_point.rst index 4aa7f9a27c..c8022c3d4f 100644 --- a/docs/userguide/entry_point.rst +++ b/docs/userguide/entry_point.rst @@ -486,9 +486,10 @@ entry points remains the same as for console/GUI scripts, and is discussed in th .. tip:: The recommended approach for loading and importing entry points is the :mod:`importlib.metadata` module, - which is a part of the standard library since Python 3.8. For older versions of - Python, its backport :pypi:`importlib_metadata` should be used. While using the - backport, the only change that has to be made is to replace ``importlib.metadata`` + which is a part of the standard library since Python 3.8 and is non-provisional + since Python 3.10. For older versions of Python, its backport + :pypi:`importlib_metadata` should be used. While using the backport, the only + change that has to be made is to replace ``importlib.metadata`` with ``importlib_metadata``, i.e. .. code-block:: python diff --git a/docs/userguide/ext_modules.rst b/docs/userguide/ext_modules.rst index 8c193856ac..4abc3dcd04 100644 --- a/docs/userguide/ext_modules.rst +++ b/docs/userguide/ext_modules.rst @@ -27,22 +27,41 @@ and all project metadata configuration in the ``pyproject.toml`` file: version = "0.42" To instruct setuptools to compile the ``foo.c`` file into the extension module -``mylib.foo``, we need to add a ``setup.py`` file similar to the following: +``mylib.foo``, we need to define an appropriate configuration in either +``pyproject.toml`` [#pyproject.toml]_ or ``setup.py`` file , +similar to the following: -.. code-block:: python +.. tab:: pyproject.toml - from setuptools import Extension, setup + .. code-block:: toml - setup( - ext_modules=[ - Extension( - name="mylib.foo", # as it would be imported - # may include packages/namespaces separated by `.` - - sources=["foo.c"], # all sources are compiled into a single binary file - ), + [tool.setuptools] + ext-modules = [ + {name = "mylib.foo", sources = ["foo.c"]} ] - ) + +.. tab:: setup.py + + .. code-block:: python + + from setuptools import Extension, setup + + setup( + ext_modules=[ + Extension( + name="mylib.foo", + sources=["foo.c"], + ), + ] + ) + +The ``name`` value corresponds to how the extension module would be +imported and may include packages/namespaces separated by ``.``. +The ``sources`` value is a list of all source files that are compiled +into a single binary file. +Optionally any other parameter of :class:`setuptools.Extension` can be defined +in the configuration file (but in the case of ``pyproject.toml`` they must be +written using :wiki:`kebab-case` convention). .. seealso:: You can find more information on the `Python docs about C/C++ extensions`_. @@ -91,8 +110,7 @@ The compiler options appear in the command line in the following order: .. Reference: "compiler_so" and distutils.ccompiler.gen_preprocess_options, CCompiler.compile, UnixCCompiler._compile -* first, the options provided by the ``sysconfig`` variable ``CFLAGS``, -* then, the options provided by the environment variables ``CFLAGS`` and ``CPPFLAGS``, +* first, the options provided by the environment variables ``CFLAGS`` and ``CPPFLAGS``, * then, the options provided by the ``sysconfig`` variable ``CCSHARED``, * then, a ``-I`` option for each element of ``Extension.include_dirs``, * finally, the options provided by ``Extension.extra_compile_args``. @@ -143,7 +161,10 @@ your ``pyproject.toml``: .. code-block:: toml [build-system] - requires = [..., "cython"] + requires = [ + # ..., + "cython", + ] Alternatively, you can include the ``.c`` code that is pre-compiled by Cython into your source distribution, alongside the original ``.pyx`` files (this @@ -165,6 +186,16 @@ Extension API Reference .. autoclass:: setuptools.Extension +---- + +.. rubric:: Notes + +.. [#pyproject.toml] + Declarative configuration of extension modules via ``pyproject.toml`` was + introduced recently and is still considered experimental. + Therefore it might change in future versions of ``setuptools``. + + .. _Python docs about C/C++ extensions: https://docs.python.org/3/extending/extending.html .. _Cython: https://cython.readthedocs.io/en/stable/index.html .. _directory options: https://gcc.gnu.org/onlinedocs/gcc/Directory-Options.html diff --git a/docs/userguide/extension.rst b/docs/userguide/extension.rst index e1e37b5db1..b0eb9f53c3 100644 --- a/docs/userguide/extension.rst +++ b/docs/userguide/extension.rst @@ -122,7 +122,7 @@ a non-``None`` value. Here's an example validation function:: """Verify that value is True, False, 0, or 1""" if bool(value) != value: raise SetupError( - "%r must be a boolean value (got %r)" % (attr,value) + f"{attr!r} must be a boolean value (got {value!r}" ) Your function should accept three arguments: the ``Distribution`` object, @@ -293,7 +293,7 @@ A few important points for writing revision control file finders: inform the user of the missing program(s). -.. _distutils: https://docs.python.org/3.9/library/distutils.html +.. _distutils: https://setuptools.pypa.io/en/latest/deprecated/distutils/index.html Final Remarks diff --git a/docs/userguide/index.rst b/docs/userguide/index.rst index d631c5d8ac..fd9947ee79 100644 --- a/docs/userguide/index.rst +++ b/docs/userguide/index.rst @@ -25,6 +25,7 @@ Contents :maxdepth: 1 quickstart + interfaces package_discovery dependency_management development_mode diff --git a/docs/userguide/interfaces.rst b/docs/userguide/interfaces.rst new file mode 100644 index 0000000000..ad747b48d5 --- /dev/null +++ b/docs/userguide/interfaces.rst @@ -0,0 +1,186 @@ +Supported Interfaces +==================== + +Setuptools is a complicated library with many interface surfaces and challenges. In addition to its primary purpose as a packaging build backend, Setuptools also has historically served as a standalone builder, installer, uploader, metadata provider, and more. Additionally, because it's implemented as a Python library, its entire functionality is incidentally exposed as a library. + +In addition to operating as a library, because newer versions of Setuptools are often used to build older (sometimes decades-old) packages, it has a high burden of stability. + +In order to have the ability to make sensible changes to the project, downstream developers and consumers should avoid depending on internal implementation details of the library and should rely only on the supported interfaces: + +- *Tier 1*: APIs required by modern PyPA packaging standards (:pep:`517`, :pep:`660`) and Documented APIs for customising build behavior or creating plugins (:doc:`/userguide/extension`, :doc:`/references/keywords`): + + These APIs are expected to be extremely stable and have deprecation notices and periods prior to backward incompatible changes or removals. + + Please note that *functional and integration tests* capture specific behaviors and expectations about how the library and system is intended to work for outside users; + and *code comments and docstrings* (including in tests) may provide specific protections to limit the changes to behaviors on which a downstream consumer can rely. + +- *Tier 2*: Documented ``distutils`` APIs: + + ``setuptools`` strives to honor the interfaces provided by ``distutils`` and + will coordinate with the ``pypa/distutils`` repository so that the + appropriate deprecation notices are issued. + + In principle, these are documented in :doc:`/deprecated/distutils/apiref`. + Please note however that when a suitable replacement is available or advised, + the existing ``distutils`` API is considered deprecated and should not be used + (see :pep:`632#migration-advice` and :doc:`/deprecated/distutils-legacy`). + +Depending on other behaviors is risky and subject to future breakage. If a project wishes to consider using interfaces that aren't covered above, consider requesting those interfaces to be added prior to depending on them (perhaps through a pull request implementing the change and relevant regression tests). + +Please check further information about deprecated and unsupported behaviors in :doc:`/deprecated/index`. + + +Support Policy Exceptions +------------------------- + +Behaviors and interfaces explicitly documented/advertised as deprecated, +or that :obj:`issue deprecation warnings ` +will be supported up to the end of the announced deprecation period. + +However there are a few circumstances in which the Setuptools' maintainers +reserve the right of speeding up the deprecation cycle and shortening deprecation periods: + +1. When security vulnerabilities are identified in specific code paths and the + reworking existing APIs is not viable. +2. When standards in the Python packaging ecosystem externally drive non-backward + compatible changes in the code base. +3. When changes in behavior are externally driven by 3rd-party dependencies + and code maintained outside of the ``pypa/setuptools`` repository. + +Note that these are exceptional circumstances and that the project will +carefully attempt to find alternatives before resorting to unscheduled removals. + +.. important:: + In the context of ``setuptools``, the introduction of :py:mod:`warnings` + (including deprecation warnings) is not considered a breaking change *per se*. + Instead it is considered a backwards compatible *communication action* that + precedes an upcoming breaking change. This is becauset code + containing warnings typically does not fail and can successfully terminate + execution, unless users explicitly opt into transforming those warnings + into errors (e.g., via Python's :external+python:ref:`-W option or + PYTHONWARNINGS environment variable `). + + +What to do when deprecation periods are undefined? +-------------------------------------------------- + +In some cases it is difficult to define how long Setuptools will take +to remove certain features, behaviors or APIs. +For example, it may be complicated to assess how wide-spread the usage +of a certain feature is in the ecosystem. + +Therefore, Setuptools may start to issue deprecation warnings without a clear due date. +This occurs because we want to notify consumers about upcoming breaking +changes as soon as possible so that they can start working in migration plans. + +This does not mean that users should treat this deprecation as low priority or +interpret the lack of due date as a signal that a breaking change will never happen. + +The advised course of action is for users to create a migration plan +as soon as they have identified to be subject to a Setuptools deprecation. + +Setuptools may introduce relatively short deprecation periods (e.g. 6 months) +when a deprecation warning has already been issued for a long period without a +explicit due date. + + +How to stay on top of upcoming deprecations? +-------------------------------------------- + +It is a good idea to employ an automated test suite with relatively good +coverage in your project and keep an eye on the logs. +You can also automate this process by forwarding the standard output/error +streams to a log file and using heuristics to identify deprecations +(e.g. by searching for the word ``deprecation`` or ``deprecated``). +You may need to increase the level of verbosity of your output as +some tools may hide log messages by default (e.g. via ``pip -vv install ...``). + +Additionally, if you are supporting a project that depends on Setuptools, +you can implement a CI workflow that leverages +:external+python:ref:`Python warning filters ` +to improve the visibility of warnings. + +This workflow can be comprised, for example, of 3 iterative steps that require +developers to acknowledge the deprecation warnings: + +1. Leverage Python Warning's Filter to transform warnings into exceptions during automated tests. +2. Devise a migration plan: + + - It is a good idea to track deprecations as if they were issues, + and apply project management techniques to monitor the progress in handling them. + - Determine which parts of your code are affected and understand + the changes required to eliminate the warnings. + +3. Modify the warning's filter you are using in the CI to not fail + with the newly identified exceptions (e.g. by using the ``default`` action + with a specific category or regular expression for the warning message). + This can be done globally for the whole test suite or locally in a + test-by-test basis. + +Test tools like :pypi:`pytest` offer CLI and configuration options +to facilitate controlling the warning's filter (see :external+pytest:doc:`how-to/capture-warnings`). + +Note that there are many ways to incorporate such workflow in your CI. +For example, if you have enough deployment resources and consider +deprecation warning management to be a day-to-day development test +you can set the warning's filter directly on your main CI loop. +On the other hand if you have critical timelines and cannot afford CI jobs +occasionally failing to flag maintenance, you can consider scheduling a +periodic CI run separated from your main/mission-critical workflow. + + +What does "support" mean? +------------------------- + +Setuptools is a non-profit community-driven open source project and as such +the word "support" is used in a best-effort manner and with limited scope. +For example, it is not always possible to quickly provide fixes for bugs. + +We appreciate the patience of the community and incentivise users +impacted by bugs to contribute to fixes in the form of +:doc:`PR submissions `, to speed-up the process. + +When we say "a certain feature is supported" we mean that we will do our best +to ensure this feature keeps working as documented. +Note however that, as in any system, unintended breakages may happen. +We appreciate the community understand and `considerate feedback`_. + +.. _considerate feedback: https://opensource.how/etiquette/ + + +What to do after the deprecation period ends? +--------------------------------------------- + +If you have limited development resources and is not able to +devise a migration plan before Setuptools removes a deprecated feature, +you can still resort to restricting the version of Setuptools to be installed. +This usually includes modifying ``[build-system] requires`` in ``pyproject.toml`` +and/or specifying ``pip`` :external+pip:ref:`Constraints Files` via +the ``PIP_CONSTRAINT`` environment variable (or passing |build-constraint-uv|_). +Please avoid however to preemptively add version constraints if not necessary, +(you can read more about this in https://iscinumpy.dev/post/bound-version-constraints/). + +.. |build-constraint-uv| replace:: ``--build-constraint`` to ``uv`` +.. _build-constraint-uv: https://docs.astral.sh/uv/concepts/projects/build/#build-constraints + + +A note on "Public Names" +------------------------ + +Python devs may be used to the convention that private members are prefixed +with an ``_`` (underscore) character and that any member not marked by this +public. Due to the history and legacy of Setuptools this is not necessarily +the case [#private]_. + +In this project, "public interfaces" are defined as interfaces explicitly +documented for 3rd party consumption. + +When accessing a member in the ``setuptools`` package, please make sure it is +documented for external usage. Also note that names imported from different +modules/submodules are considered internal implementation details unless +explicitly listed in ``__all__``. The fact that they are accessible in the +namespace of the ``import``-er module is a mere side effect of the way Python works. + +.. [#private] + While names prefixed by ``_`` are always considered private, + not necessary the absence of the prefix signals public members. diff --git a/docs/userguide/miscellaneous.rst b/docs/userguide/miscellaneous.rst index 19908e05ad..1b493fba3b 100644 --- a/docs/userguide/miscellaneous.rst +++ b/docs/userguide/miscellaneous.rst @@ -4,11 +4,50 @@ Controlling files in the distribution ===================================== For the most common use cases, ``setuptools`` will automatically find out which -files are necessary for distributing the package. -These include all :term:`pure Python modules ` in the -``py_modules`` or ``packages`` configuration, and the C sources (but not C -headers) listed as part of extensions when creating a :term:`source -distribution (or "sdist")`. +files are necessary for distributing the package. More precisely, the following +files are included in a source distribution by default: + +- :term:`pure Python module ` files implied by the ``py-modules`` and ``packages`` + configuration parameters in ``pyproject.toml`` and/or equivalent + in ``setup.cfg``/``setup.py``; +- C source files mentioned in the ``ext_modules`` or ``libraries`` + ``setup()`` arguments; +- Files that match the following glob patterns: ``tests/test*.py``, + ``test/test*.py``; +- Scripts specified by the ``scripts-files`` configuration parameter + in ``pyproject.toml`` or ``scripts`` in ``setup.py``/``setup.cfg``; +- All files specified by the ``package-data`` and ``data-files`` + configuration parameters in ``pyproject.toml`` and/or equivalent + in ``setup.cfg``/``setup.py``; +- The file specified by the ``license_file`` option in ``setup.cfg``; +- All files specified by the ``license-files`` configuration parameter + in ``pyproject.toml`` and/or equivalent in ``setup.cfg``/``setup.py``; + note that if you don't explicitly set this parameter, ``setuptools`` + will include any files that match the following glob patterns: + ``LICEN[CS]E*``, ``COPYING*``, ``NOTICE*``, ``AUTHORS**``; +- ``pyproject.toml``; +- ``setup.cfg``; +- ``setup.py``; +- ``README``, ``README.txt``, ``README.rst`` or ``README.md``; +- ``MANIFEST.in`` + +Please note that the list above is guaranteed to work with the last stable version +of ``setuptools``. The behavior of older versions might differ. + +.. note:: + .. versionadded:: v69.0.0 + ``setuptools`` will attempt to include type information files + by default in the distribution + (``.pyi`` and ``py.typed``, as specified in :pep:`561`), + as long as they are contained inside of a package directory + (for the time being there is no automatic support for top-level ``.pyi`` files). + + *Please note however that this feature is* **EXPERIMENTAL** *and may change in + the future.* + + If you have ``.pyi`` and ``py.typed`` files in your project, but do not + wish to distribute them, you can opt out by setting + :doc:`exclude-package-data ` to remove them. However, when building more complex packages (e.g. packages that include non-Python files, or that need to use custom C headers), you might find that @@ -30,8 +69,6 @@ to specify any files that the default file location algorithm doesn't catch. This file contains instructions that tell ``setuptools`` which files exactly should be part of the ``sdist`` (or not). -A comprehensive guide to ``MANIFEST.in`` syntax is available at the -:doc:`PyPA's Packaging User Guide `. .. attention:: Please note that ``setuptools`` supports the ``MANIFEST.in``, @@ -48,6 +85,58 @@ A comprehensive guide to ``MANIFEST.in`` syntax is available at the files inside a set of directories) and then fine tune the file selection by removing the excess or adding isolated files. + +A :file:`MANIFEST.in` file consists of commands, one per line, instructing +setuptools to add or remove some set of files from the sdist. The commands +are: + +========================================================= ================================================================================================== +Command Description +========================================================= ================================================================================================== +:samp:`include {pat1} {pat2} ...` Add all files matching any of the listed patterns + (Files must be given as paths relative to the root of the project) +:samp:`exclude {pat1} {pat2} ...` Remove all files matching any of the listed patterns + (Files must be given as paths relative to the root of the project) +:samp:`recursive-include {dir-pattern} {pat1} {pat2} ...` Add all files under directories matching ``dir-pattern`` that match any of the listed patterns +:samp:`recursive-exclude {dir-pattern} {pat1} {pat2} ...` Remove all files under directories matching ``dir-pattern`` that match any of the listed patterns +:samp:`global-include {pat1} {pat2} ...` Add all files anywhere in the source tree matching any of the listed patterns +:samp:`global-exclude {pat1} {pat2} ...` Remove all files anywhere in the source tree matching any of the listed patterns +:samp:`graft {dir-pattern}` Add all files under directories matching ``dir-pattern`` +:samp:`prune {dir-pattern}` Remove all files under directories matching ``dir-pattern`` +========================================================= ================================================================================================== + +The patterns here are glob-style patterns: ``*`` matches zero or more regular +filename characters (on Unix, everything except forward slash; on Windows, +everything except backslash and colon); ``?`` matches a single regular filename +character, and ``[chars]`` matches any one of the characters between the square +brackets (which may contain character ranges, e.g., ``[a-z]`` or +``[a-fA-F0-9]``). Setuptools also has support for ``**`` matching +zero or more characters including forward slash, backslash, and colon. + +Directory patterns are relative to the root of the project directory; e.g., +``graft example*`` will include a directory named :file:`examples` in the +project root but will not include :file:`docs/examples/`. + +File & directory names in :file:`MANIFEST.in` should be ``/``-separated; +setuptools will automatically convert the slashes to the local platform's +appropriate directory separator. + +Commands are processed in the order they appear in the :file:`MANIFEST.in` +file. For example, given the commands: + +.. code-block:: bash + + graft tests + global-exclude *.py[cod] + +the contents of the directory tree :file:`tests` will first be added to the +sdist, and then after that all files in the sdist with a ``.pyc``, ``.pyo``, or +``.pyd`` extension will be removed from the sdist. If the commands were in the +opposite order, then ``*.pyc`` files etc. would be only be removed from what +was already in the sdist before adding :file:`tests`, and if :file:`tests` +happened to contain any ``*.pyc`` files, they would end up included in the +sdist because the exclusion happened before they were included. + An example of ``MANIFEST.in`` for a simple project that organized according to a :ref:`src-layout` is: @@ -81,6 +170,20 @@ binary extensions during the build process, or included in the final See :doc:`/userguide/datafiles` for more information. + +.. _Caching and Troubleshooting: + +Caching and Troubleshooting +=========================== + +Setuptools automatically creates a few directories to host build artefacts and +cache files, such as ``build``, ``dist``, ``*.egg-info``. While cache is +useful to speed up incremental builds, in some edge cases it might become +stale. If you feel that caching is causing problems to your build, specially +after changes in configuration or in the directory/file structure., consider +removing ``build``, ``dist``, ``*.egg-info`` [#PKG-INFO]_ before rebuilding or +reinstalling your project. + ---- .. [#build-process] @@ -96,5 +199,9 @@ binary extensions during the build process, or included in the final :term:`Virtual Environment`. Therefore it only contains items that are required during runtime. +.. [#PKG-INFO] + When working from an extracted sdist (e.g. for patching), you might also consider removing + the ``PKG-INFO`` file to force its recreation. + .. _git: https://git-scm.com .. _mercurial: https://www.mercurial-scm.org diff --git a/docs/userguide/package_discovery.rst b/docs/userguide/package_discovery.rst index 6a7bdbf8da..c33877e1f6 100644 --- a/docs/userguide/package_discovery.rst +++ b/docs/userguide/package_discovery.rst @@ -88,8 +88,9 @@ exactly to the directory structure, you also need to configure ``package_dir``: package_dir = { "mypkg": "lib", # mypkg.module corresponds to lib/module.py "mypkg.subpkg1": "lib1", # mypkg.subpkg1.module1 corresponds to lib1/module1.py - "mypkg.subpkg2": "lib2" # mypkg.subpkg2.module2 corresponds to lib2/module2.py + "mypkg.subpkg2": "lib2", # mypkg.subpkg2.module2 corresponds to lib2/module2.py # ... + } ) .. tab:: pyproject.toml diff --git a/docs/userguide/pyproject_config.rst b/docs/userguide/pyproject_config.rst index 103d10ede2..0b37749064 100644 --- a/docs/userguide/pyproject_config.rst +++ b/docs/userguide/pyproject_config.rst @@ -29,8 +29,8 @@ be used with ``setuptools``. It contains two TOML tables (identified by the The ``build-system`` table is used to tell the build frontend (e.g. :pypi:`build` or :pypi:`pip`) to use ``setuptools`` and any other plugins (e.g. ``setuptools-scm``) to build the package. -The ``project`` table contains metadata fields as described by -:doc:`PyPUG:specifications/declaring-project-metadata` guide. +The ``project`` table contains metadata fields as described by the +:doc:`PyPUG:guides/writing-pyproject-toml` guide. .. _example-pyproject-config: @@ -47,16 +47,16 @@ The ``project`` table contains metadata fields as described by ] description = "My package description" readme = "README.rst" - requires-python = ">=3.7" + requires-python = ">=3.8" keywords = ["one", "two"] - license = {text = "BSD-3-Clause"} + license = "BSD-3-Clause" classifiers = [ "Framework :: Django", "Programming Language :: Python :: 3", ] dependencies = [ "requests", - 'importlib-metadata; python_version<"3.8"', + 'importlib-metadata; python_version<"3.10"', ] dynamic = ["version"] @@ -67,8 +67,16 @@ The ``project`` table contains metadata fields as described by [project.scripts] my-script = "my_package.module:function" - # ... other project metadata fields as specified in: - # https://packaging.python.org/en/latest/specifications/declaring-project-metadata/ + # ... other project metadata fields as listed in: + # https://packaging.python.org/en/latest/guides/writing-pyproject-toml/ + +.. important:: + Support for + :external+PyPUG:ref:`project.license-files ` + and SPDX license expressions in + :external+PyPUG:ref:`project.license ` (:pep:`639`) + were introduced in version 77.0.0. + .. _setuptools-table: @@ -88,6 +96,10 @@ file, and can be set via the ``tool.setuptools`` table: Key Value Type (TOML) Notes ========================= =========================== ========================= ``py-modules`` array See tip below. +``ext-modules`` array of **Experimental** - Each item corresponds to a + tables/inline-tables :class:`setuptools.Extension` object and may define + the associated parameters in :wiki:`kebab-case`. + See :doc:`/userguide/ext_modules`. ``packages`` array or ``find`` directive See tip below. ``package-dir`` table/inline-table Used when explicitly/manually listing ``packages``. ------------------------- --------------------------- ------------------------- @@ -96,7 +108,8 @@ Key Value Type (TOML) Notes See :doc:`/userguide/datafiles`. ``exclude-package-data`` table/inline-table Empty by default. See :doc:`/userguide/datafiles`. ------------------------- --------------------------- ------------------------- -``license-files`` array of glob patterns **Provisional** - likely to change with :pep:`639` +``license-files`` array of glob patterns **Deprecated** - use ``project.license-files`` instead. See + :external+PyPUG:ref:`Writing your pyproject.toml ` (by default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``) ``data-files`` table/inline-table **Discouraged** - check :doc:`/userguide/datafiles`. Whenever possible, consider using data files inside the package directories. @@ -192,7 +205,7 @@ corresponding entry is required in the ``tool.setuptools.dynamic`` table dynamic = ["version", "readme"] # ... [tool.setuptools.dynamic] - version = {attr = "my_package.VERSION"} + version = {attr = "my_package.__version__"} # any module attribute compatible with ast.literal_eval readme = {file = ["README.rst", "USAGE.rst"]} In the ``dynamic`` table, the ``attr`` directive [#directives]_ will read an @@ -230,7 +243,7 @@ some of them dynamically. Also note that the file format for specifying dependencies resembles a ``requirements.txt`` file, however please keep in mind that all non-comment lines must conform with :pep:`508` -(``pip``-specify syntaxes, e.g. ``-c/-r/-e`` flags, are not supported). +(``pip`` specific syntaxes, e.g. ``-c/-r/-e`` and other flags, are not supported). .. note:: @@ -242,6 +255,20 @@ however please keep in mind that all non-comment lines must conform with :pep:`5 .. versionchanged:: 66.1.0 Newer versions of ``setuptools`` will automatically add these files to the ``sdist``. +It is advisable to use literal values together with ``attr`` (e.g. ``str``, +``tuple[str]``, see :func:`ast.literal_eval`). This is recommend +in order to support the common case of a literal value assigned to a variable +in a module containing (directly or indirectly) third-party imports. + +``attr`` first tries to read the value from the module by examining the +module's AST. If that fails, ``attr`` falls back to importing the module, +using :func:`importlib.util.spec_from_file_location` recommended recipe +(see :ref:`example on Python docs ` +about "Importing a source file directly"). +Note however that importing the module is error prone since your package is +not installed yet. You may also need to manually add the project directory to +``sys.path`` (via ``setup.py``) in order to be able to do that. + ---- .. rubric:: Notes @@ -266,7 +293,7 @@ however please keep in mind that all non-comment lines must conform with :pep:`5 directive for ``tool.setuptools.dynamic.version``. .. [#attr] ``attr`` is meant to be used when the module attribute is statically - specified (e.g. as a string, list or tuple). As a rule of thumb, the + specified (e.g. as a string). As a rule of thumb, the attribute should be able to be parsed with :func:`ast.literal_eval`, and should not be modified or re-assigned. diff --git a/docs/userguide/quickstart.rst b/docs/userguide/quickstart.rst index 2afab9e54c..606654f86c 100644 --- a/docs/userguide/quickstart.rst +++ b/docs/userguide/quickstart.rst @@ -7,7 +7,7 @@ Installation You can install the latest version of ``setuptools`` using :pypi:`pip`:: - pip install --upgrade setuptools + pip install --upgrade setuptools[core] Most of the times, however, you don't have to... @@ -56,13 +56,23 @@ containing a ``build-system`` section similar to the example below: This section declares what are your build system dependencies, and which library will be used to actually do the packaging. +.. note:: + + Package maintainers might be tempted to use ``setuptools[core]`` as the + requirement, given the guidance above. Avoid doing so, as the extra + is currently considered an internal implementation detail and is likely + to go away in the future and the Setuptools team will not support + compatibility for problems arising from packages published with this + extra declared. Vendored packages will satisfy the dependencies in + the most common isolated build scenarios. + .. note:: Historically this documentation has unnecessarily listed ``wheel`` in the ``requires`` list, and many projects still do that. This is - not recommended. The backend automatically adds ``wheel`` dependency - when it is required, and listing it explicitly causes it to be - unnecessarily required for source distribution builds. + not recommended, as the backend no longer requires the ``wheel`` + package, and listing it explicitly causes it to be unnecessarily + required for source distribution builds. You should only include ``wheel`` in ``requires`` if you need to explicitly access it during build time (e.g. if your project needs a ``setup.py`` script that imports ``wheel``). @@ -85,7 +95,7 @@ The following example demonstrates a minimum configuration version = "0.0.1" dependencies = [ "requests", - 'importlib-metadata; python_version<"3.8"', + 'importlib-metadata; python_version<"3.10"', ] See :doc:`/userguide/pyproject_config` for more information. @@ -101,7 +111,8 @@ The following example demonstrates a minimum configuration [options] install_requires = requests - importlib-metadata; python_version < "3.8" + importlib-metadata; python_version<"3.10" + See :doc:`/userguide/declarative_config` for more information. @@ -116,7 +127,7 @@ The following example demonstrates a minimum configuration version='0.0.1', install_requires=[ 'requests', - 'importlib-metadata; python_version == "3.8"', + 'importlib-metadata; python_version<"3.10"', ], ) @@ -188,7 +199,7 @@ Package discovery ----------------- For projects that follow a simple directory structure, ``setuptools`` should be able to automatically detect all :term:`packages ` and -:term:`namespaces `. However, complex projects might include +:term:`namespaces `. However, complex projects might include additional folders and supporting files that not necessarily should be distributed (or that can confuse ``setuptools`` auto discovery algorithm). @@ -229,7 +240,7 @@ found, as shown in the example below: .. code-block:: python - from setuptools import find_packages # or find_namespace_packages + from setuptools import setup, find_packages # or find_namespace_packages setup( # ... @@ -390,8 +401,8 @@ For the simplest use, you can simply use the ``include_package_data`` keyword: ) This tells setuptools to install any data files it finds in your packages. -The data files must be specified via the |MANIFEST.in|_ file -or automatically added by a :ref:`Revision Control System plugin +The data files must be specified via the :ref:`MANIFEST.in ` +file or automatically added by a :ref:`Revision Control System plugin `. For more details, see :doc:`datafiles`. @@ -417,7 +428,7 @@ See :doc:`development_mode` for more information. If you have a version of ``pip`` older than v21.1 or is using a different packaging-related tool that does not support :pep:`660`, you might need to keep a - ``setup.py`` file in file in your repository if you want to use editable + ``setup.py`` file in your repository if you want to use editable installs. A simple script will suffice, for example: @@ -432,6 +443,17 @@ See :doc:`development_mode` for more information. :doc:`pyproject.toml ` and/or :doc:`setup.cfg ` +.. note:: + + When building from source code (for example, by ``python -m build`` + or ``pip install -e .``) + some directories hosting build artefacts and cache files may be + created, such as ``build``, ``dist``, ``*.egg-info`` [#cache]_. + You can configure your version control system to ignore them + (see `GitHub's .gitignore template + `_ + for an example). + Uploading your package to PyPI ------------------------------ @@ -441,14 +463,23 @@ distribution so others can use it. This functionality is provided by `. -Transitioning from ``setup.py`` to ``setup.cfg`` ------------------------------------------------- +Transitioning from ``setup.py`` to declarative config +----------------------------------------------------- To avoid executing arbitrary scripts and boilerplate code, we are transitioning -into a full-fledged ``setup.cfg`` to declare your package information instead -of running ``setup()``. This inevitably brings challenges due to a different -syntax. :doc:`Here ` we provide a quick guide to -understanding how ``setup.cfg`` is parsed by ``setuptools`` to ease the pain of -transition. +from defining all your package information by running ``setup()`` to doing this +declaratively - by using ``pyproject.toml`` (or older ``setup.cfg``). + +To ease the challenges of transitioning, we provide a quick +:doc:`guide ` to understanding how ``pyproject.toml`` +is parsed by ``setuptools``. (Alternatively, here is the +:doc:`guide ` for ``setup.cfg``). + +.. note:: + + The approach ``setuptools`` would like to take is to eventually use a single + declarative format (``pyproject.toml``) instead of maintaining 2 + (``pyproject.toml`` / ``setup.cfg``). Yet, chances are, ``setup.cfg`` will + continue to be maintained for a long time. .. _packaging-resources: @@ -459,9 +490,6 @@ Packaging in Python can be hard and is constantly evolving. up-to-date references that can help you when it is time to distribute your work. -.. |MANIFEST.in| replace:: ``MANIFEST.in`` -.. _MANIFEST.in: https://packaging.python.org/en/latest/guides/using-manifest-in/ - ---- @@ -478,4 +506,9 @@ up-to-date references that can help you when it is time to distribute your work. supported in those files (e.g. C extensions). See :ref:`note `. +.. [#cache] + If you feel that caching is causing problems to your build, specially after changes in the + configuration files, consider removing ``build``, ``dist``, ``*.egg-info`` before + rebuilding or installing your project. + .. _PyPI: https://pypi.org diff --git a/mypy.ini b/mypy.ini index b6f972769e..979e5af00c 100644 --- a/mypy.ini +++ b/mypy.ini @@ -1,5 +1,70 @@ [mypy] -ignore_missing_imports = True -# required to support namespace packages -# https://github.com/python/mypy/issues/14057 +## upstream + +# Is the project well-typed? +strict = False + +# Early opt-in even when strict = False +# warn_unused_ignores = True # Disabled until we have distutils stubs for Python 3.12+ +warn_redundant_casts = True +enable_error_code = ignore-without-code + +# Support namespace packages per https://github.com/python/mypy/issues/14057 explicit_package_bases = True + +disable_error_code = + # Disable due to many false positives + overload-overlap, + +## local + +# CI should test for all versions, local development gets hints for oldest supported +# But our testing setup doesn't allow passing CLI arguments, so local devs have to set this manually. +# python_version = 3.9 + +exclude = (?x)( + # Avoid scanning Python files in generated folders + ^build/ + | ^.tox/ + | ^.eggs/ + | ^setuptools/config/_validate_pyproject/ + # These are vendored + | ^setuptools/_vendor/ + | ^setuptools/_distutils/ + ) + +[mypy-setuptools.*] +disable_error_code = + # DistributionMetadata.license_files and DistributionMetadata.license_file + # are dynamically patched in setuptools/_core_metadata.py + # and no DistributionMetadata subclass exists in setuptools + attr-defined, + # See issue described below about distutils across Python versions + has-type, + +# distutils doesn't exist on Python 3.12, unfortunately, this means typing +# will be missing for subclasses of distutils on Python 3.12 until either: +# - support for `SETUPTOOLS_USE_DISTUTILS=stdlib` is dropped (#3625) +# for setuptools to import `_distutils` directly +# - or non-stdlib distutils typings are exposed +[mypy-distutils.*] +ignore_missing_imports = True + +# wheel: does not intend on exposing a programmatic API https://github.com/pypa/wheel/pull/610#issuecomment-2081687671 +[mypy-wheel.*] +follow_untyped_imports = True + +# The following are not marked as py.typed: +# - jaraco: Since mypy 1.12, the root name of the untyped namespace package gets called-out too +# - jaraco.develop: https://github.com/jaraco/jaraco.develop/issues/22 +# - jaraco.envs: https://github.com/jaraco/jaraco.envs/issues/7 +# - jaraco.packaging: https://github.com/jaraco/jaraco.packaging/issues/20 +# - jaraco.path: https://github.com/jaraco/jaraco.path/issues/2 +[mypy-jaraco,jaraco.develop.*,jaraco.envs,jaraco.packaging.*,jaraco.path] +follow_untyped_imports = True + +# Even when excluding a module, import issues can show up due to following import +# https://github.com/python/mypy/issues/11936#issuecomment-1466764006 +[mypy-setuptools.config._validate_pyproject.*,setuptools._vendor.*,setuptools._distutils.*] +follow_imports = silent +# silent => ignore errors when following imports diff --git a/newsfragments/+0af71c41.feature.rst b/newsfragments/+0af71c41.feature.rst new file mode 100644 index 0000000000..d8c8faf72f --- /dev/null +++ b/newsfragments/+0af71c41.feature.rst @@ -0,0 +1 @@ +Require Python 3.10 or later. diff --git a/newsfragments/3903.feature.rst b/newsfragments/3903.feature.rst deleted file mode 100644 index ac6c00a2fb..0000000000 --- a/newsfragments/3903.feature.rst +++ /dev/null @@ -1,2 +0,0 @@ -Rework how ``setuptools`` internally handles ``dependencies/install_requires`` -and ``optional-dependencies/extras_require``. diff --git a/newsfragments/3904.feature.1.rst b/newsfragments/3904.feature.1.rst deleted file mode 100644 index 114553846e..0000000000 --- a/newsfragments/3904.feature.1.rst +++ /dev/null @@ -1,3 +0,0 @@ -Improve the generated ``PKG-INFO`` files, by adding ``Requires-Dist`` fields. -Previously, these fields would be omitted in favour of a non-standard -``*.egg-info/requires.txt`` file (which is still generated for the time being). diff --git a/newsfragments/3904.feature.2.rst b/newsfragments/3904.feature.2.rst deleted file mode 100644 index 0c80d33c06..0000000000 --- a/newsfragments/3904.feature.2.rst +++ /dev/null @@ -1,2 +0,0 @@ -Improve atomicity when writing ``PKG-INFO`` files to avoid race -conditions with ``importlib.metadata``. diff --git a/newsfragments/4023.misc.rst b/newsfragments/4023.misc.rst deleted file mode 100644 index 9a0c2e7736..0000000000 --- a/newsfragments/4023.misc.rst +++ /dev/null @@ -1,2 +0,0 @@ -Avoid circular imports (particularly between ``setuptools/{__init__,dist,monkey}.py``), -or at least delay them, so tools like ``sphinx`` don't have problems analysing the codebase. diff --git a/newsfragments/4027.misc.1.rst b/newsfragments/4027.misc.1.rst deleted file mode 100644 index 2c84450f0f..0000000000 --- a/newsfragments/4027.misc.1.rst +++ /dev/null @@ -1 +0,0 @@ -Removed ``pandas`` from integration tests. diff --git a/newsfragments/4027.misc.2.rst b/newsfragments/4027.misc.2.rst deleted file mode 100644 index d33b85a6c6..0000000000 --- a/newsfragments/4027.misc.2.rst +++ /dev/null @@ -1 +0,0 @@ -Added ``pyyaml``, ``charset-normalizer`` and ``protobuf`` to integration tests. diff --git a/pkg_resources/__init__.py b/pkg_resources/__init__.py deleted file mode 100644 index 3baa1f3c24..0000000000 --- a/pkg_resources/__init__.py +++ /dev/null @@ -1,3361 +0,0 @@ -""" -Package resource API --------------------- - -A resource is a logical file contained within a package, or a logical -subdirectory thereof. The package resource API expects resource names -to have their path parts separated with ``/``, *not* whatever the local -path separator is. Do not use os.path operations to manipulate resource -names being passed into the API. - -The package resource API is designed to work with normal filesystem packages, -.egg files, and unpacked .egg files. It can also work in a limited way with -.zip files and with custom PEP 302 loaders that support the ``get_data()`` -method. - -This module is deprecated. Users are directed to :mod:`importlib.resources`, -:mod:`importlib.metadata` and :pypi:`packaging` instead. -""" - -import sys -import os -import io -import time -import re -import types -import zipfile -import zipimport -import warnings -import stat -import functools -import pkgutil -import operator -import platform -import collections -import plistlib -import email.parser -import errno -import tempfile -import textwrap -import inspect -import ntpath -import posixpath -import importlib -from pkgutil import get_importer - -try: - import _imp -except ImportError: - # Python 3.2 compatibility - import imp as _imp - -try: - FileExistsError -except NameError: - FileExistsError = OSError - -# capture these to bypass sandboxing -from os import utime - -try: - from os import mkdir, rename, unlink - - WRITE_SUPPORT = True -except ImportError: - # no write support, probably under GAE - WRITE_SUPPORT = False - -from os import open as os_open -from os.path import isdir, split - -try: - import importlib.machinery as importlib_machinery - - # access attribute to force import under delayed import mechanisms. - importlib_machinery.__name__ -except ImportError: - importlib_machinery = None - -from pkg_resources.extern.jaraco.text import ( - yield_lines, - drop_comment, - join_continuation, -) - -from pkg_resources.extern import platformdirs -from pkg_resources.extern import packaging - -__import__('pkg_resources.extern.packaging.version') -__import__('pkg_resources.extern.packaging.specifiers') -__import__('pkg_resources.extern.packaging.requirements') -__import__('pkg_resources.extern.packaging.markers') -__import__('pkg_resources.extern.packaging.utils') - -if sys.version_info < (3, 5): - raise RuntimeError("Python 3.5 or later is required") - -# declare some globals that will be defined later to -# satisfy the linters. -require = None -working_set = None -add_activation_listener = None -resources_stream = None -cleanup_resources = None -resource_dir = None -resource_stream = None -set_extraction_path = None -resource_isdir = None -resource_string = None -iter_entry_points = None -resource_listdir = None -resource_filename = None -resource_exists = None -_distribution_finders = None -_namespace_handlers = None -_namespace_packages = None - - -warnings.warn( - "pkg_resources is deprecated as an API. " - "See https://setuptools.pypa.io/en/latest/pkg_resources.html", - DeprecationWarning, - stacklevel=2, -) - - -_PEP440_FALLBACK = re.compile(r"^v?(?P(?:[0-9]+!)?[0-9]+(?:\.[0-9]+)*)", re.I) - - -class PEP440Warning(RuntimeWarning): - """ - Used when there is an issue with a version or specifier not complying with - PEP 440. - """ - - -parse_version = packaging.version.Version - - -_state_vars = {} - - -def _declare_state(vartype, **kw): - globals().update(kw) - _state_vars.update(dict.fromkeys(kw, vartype)) - - -def __getstate__(): - state = {} - g = globals() - for k, v in _state_vars.items(): - state[k] = g['_sget_' + v](g[k]) - return state - - -def __setstate__(state): - g = globals() - for k, v in state.items(): - g['_sset_' + _state_vars[k]](k, g[k], v) - return state - - -def _sget_dict(val): - return val.copy() - - -def _sset_dict(key, ob, state): - ob.clear() - ob.update(state) - - -def _sget_object(val): - return val.__getstate__() - - -def _sset_object(key, ob, state): - ob.__setstate__(state) - - -_sget_none = _sset_none = lambda *args: None - - -def get_supported_platform(): - """Return this platform's maximum compatible version. - - distutils.util.get_platform() normally reports the minimum version - of macOS that would be required to *use* extensions produced by - distutils. But what we want when checking compatibility is to know the - version of macOS that we are *running*. To allow usage of packages that - explicitly require a newer version of macOS, we must also know the - current version of the OS. - - If this condition occurs for any other platform with a version in its - platform strings, this function should be extended accordingly. - """ - plat = get_build_platform() - m = macosVersionString.match(plat) - if m is not None and sys.platform == "darwin": - try: - plat = 'macosx-%s-%s' % ('.'.join(_macos_vers()[:2]), m.group(3)) - except ValueError: - # not macOS - pass - return plat - - -__all__ = [ - # Basic resource access and distribution/entry point discovery - 'require', - 'run_script', - 'get_provider', - 'get_distribution', - 'load_entry_point', - 'get_entry_map', - 'get_entry_info', - 'iter_entry_points', - 'resource_string', - 'resource_stream', - 'resource_filename', - 'resource_listdir', - 'resource_exists', - 'resource_isdir', - # Environmental control - 'declare_namespace', - 'working_set', - 'add_activation_listener', - 'find_distributions', - 'set_extraction_path', - 'cleanup_resources', - 'get_default_cache', - # Primary implementation classes - 'Environment', - 'WorkingSet', - 'ResourceManager', - 'Distribution', - 'Requirement', - 'EntryPoint', - # Exceptions - 'ResolutionError', - 'VersionConflict', - 'DistributionNotFound', - 'UnknownExtra', - 'ExtractionError', - # Warnings - 'PEP440Warning', - # Parsing functions and string utilities - 'parse_requirements', - 'parse_version', - 'safe_name', - 'safe_version', - 'get_platform', - 'compatible_platforms', - 'yield_lines', - 'split_sections', - 'safe_extra', - 'to_filename', - 'invalid_marker', - 'evaluate_marker', - # filesystem utilities - 'ensure_directory', - 'normalize_path', - # Distribution "precedence" constants - 'EGG_DIST', - 'BINARY_DIST', - 'SOURCE_DIST', - 'CHECKOUT_DIST', - 'DEVELOP_DIST', - # "Provider" interfaces, implementations, and registration/lookup APIs - 'IMetadataProvider', - 'IResourceProvider', - 'FileMetadata', - 'PathMetadata', - 'EggMetadata', - 'EmptyProvider', - 'empty_provider', - 'NullProvider', - 'EggProvider', - 'DefaultProvider', - 'ZipProvider', - 'register_finder', - 'register_namespace_handler', - 'register_loader_type', - 'fixup_namespace_packages', - 'get_importer', - # Warnings - 'PkgResourcesDeprecationWarning', - # Deprecated/backward compatibility only - 'run_main', - 'AvailableDistributions', -] - - -class ResolutionError(Exception): - """Abstract base for dependency resolution errors""" - - def __repr__(self): - return self.__class__.__name__ + repr(self.args) - - -class VersionConflict(ResolutionError): - """ - An already-installed version conflicts with the requested version. - - Should be initialized with the installed Distribution and the requested - Requirement. - """ - - _template = "{self.dist} is installed but {self.req} is required" - - @property - def dist(self): - return self.args[0] - - @property - def req(self): - return self.args[1] - - def report(self): - return self._template.format(**locals()) - - def with_context(self, required_by): - """ - If required_by is non-empty, return a version of self that is a - ContextualVersionConflict. - """ - if not required_by: - return self - args = self.args + (required_by,) - return ContextualVersionConflict(*args) - - -class ContextualVersionConflict(VersionConflict): - """ - A VersionConflict that accepts a third parameter, the set of the - requirements that required the installed Distribution. - """ - - _template = VersionConflict._template + ' by {self.required_by}' - - @property - def required_by(self): - return self.args[2] - - -class DistributionNotFound(ResolutionError): - """A requested distribution was not found""" - - _template = ( - "The '{self.req}' distribution was not found " - "and is required by {self.requirers_str}" - ) - - @property - def req(self): - return self.args[0] - - @property - def requirers(self): - return self.args[1] - - @property - def requirers_str(self): - if not self.requirers: - return 'the application' - return ', '.join(self.requirers) - - def report(self): - return self._template.format(**locals()) - - def __str__(self): - return self.report() - - -class UnknownExtra(ResolutionError): - """Distribution doesn't have an "extra feature" of the given name""" - - -_provider_factories = {} - -PY_MAJOR = '{}.{}'.format(*sys.version_info) -EGG_DIST = 3 -BINARY_DIST = 2 -SOURCE_DIST = 1 -CHECKOUT_DIST = 0 -DEVELOP_DIST = -1 - - -def register_loader_type(loader_type, provider_factory): - """Register `provider_factory` to make providers for `loader_type` - - `loader_type` is the type or class of a PEP 302 ``module.__loader__``, - and `provider_factory` is a function that, passed a *module* object, - returns an ``IResourceProvider`` for that module. - """ - _provider_factories[loader_type] = provider_factory - - -def get_provider(moduleOrReq): - """Return an IResourceProvider for the named module or requirement""" - if isinstance(moduleOrReq, Requirement): - return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0] - try: - module = sys.modules[moduleOrReq] - except KeyError: - __import__(moduleOrReq) - module = sys.modules[moduleOrReq] - loader = getattr(module, '__loader__', None) - return _find_adapter(_provider_factories, loader)(module) - - -def _macos_vers(_cache=[]): - if not _cache: - version = platform.mac_ver()[0] - # fallback for MacPorts - if version == '': - plist = '/System/Library/CoreServices/SystemVersion.plist' - if os.path.exists(plist): - if hasattr(plistlib, 'readPlist'): - plist_content = plistlib.readPlist(plist) - if 'ProductVersion' in plist_content: - version = plist_content['ProductVersion'] - - _cache.append(version.split('.')) - return _cache[0] - - -def _macos_arch(machine): - return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine) - - -def get_build_platform(): - """Return this platform's string for platform-specific distributions - - XXX Currently this is the same as ``distutils.util.get_platform()``, but it - needs some hacks for Linux and macOS. - """ - from sysconfig import get_platform - - plat = get_platform() - if sys.platform == "darwin" and not plat.startswith('macosx-'): - try: - version = _macos_vers() - machine = os.uname()[4].replace(" ", "_") - return "macosx-%d.%d-%s" % ( - int(version[0]), - int(version[1]), - _macos_arch(machine), - ) - except ValueError: - # if someone is running a non-Mac darwin system, this will fall - # through to the default implementation - pass - return plat - - -macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)") -darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)") -# XXX backward compat -get_platform = get_build_platform - - -def compatible_platforms(provided, required): - """Can code for the `provided` platform run on the `required` platform? - - Returns true if either platform is ``None``, or the platforms are equal. - - XXX Needs compatibility checks for Linux and other unixy OSes. - """ - if provided is None or required is None or provided == required: - # easy case - return True - - # macOS special cases - reqMac = macosVersionString.match(required) - if reqMac: - provMac = macosVersionString.match(provided) - - # is this a Mac package? - if not provMac: - # this is backwards compatibility for packages built before - # setuptools 0.6. All packages built after this point will - # use the new macOS designation. - provDarwin = darwinVersionString.match(provided) - if provDarwin: - dversion = int(provDarwin.group(1)) - macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2)) - if ( - dversion == 7 - and macosversion >= "10.3" - or dversion == 8 - and macosversion >= "10.4" - ): - return True - # egg isn't macOS or legacy darwin - return False - - # are they the same major version and machine type? - if provMac.group(1) != reqMac.group(1) or provMac.group(3) != reqMac.group(3): - return False - - # is the required OS major update >= the provided one? - if int(provMac.group(2)) > int(reqMac.group(2)): - return False - - return True - - # XXX Linux and other platforms' special cases should go here - return False - - -def run_script(dist_spec, script_name): - """Locate distribution `dist_spec` and run its `script_name` script""" - ns = sys._getframe(1).f_globals - name = ns['__name__'] - ns.clear() - ns['__name__'] = name - require(dist_spec)[0].run_script(script_name, ns) - - -# backward compatibility -run_main = run_script - - -def get_distribution(dist): - """Return a current distribution object for a Requirement or string""" - if isinstance(dist, str): - dist = Requirement.parse(dist) - if isinstance(dist, Requirement): - dist = get_provider(dist) - if not isinstance(dist, Distribution): - raise TypeError("Expected string, Requirement, or Distribution", dist) - return dist - - -def load_entry_point(dist, group, name): - """Return `name` entry point of `group` for `dist` or raise ImportError""" - return get_distribution(dist).load_entry_point(group, name) - - -def get_entry_map(dist, group=None): - """Return the entry point map for `group`, or the full entry map""" - return get_distribution(dist).get_entry_map(group) - - -def get_entry_info(dist, group, name): - """Return the EntryPoint object for `group`+`name`, or ``None``""" - return get_distribution(dist).get_entry_info(group, name) - - -class IMetadataProvider: - def has_metadata(name): - """Does the package's distribution contain the named metadata?""" - - def get_metadata(name): - """The named metadata resource as a string""" - - def get_metadata_lines(name): - """Yield named metadata resource as list of non-blank non-comment lines - - Leading and trailing whitespace is stripped from each line, and lines - with ``#`` as the first non-blank character are omitted.""" - - def metadata_isdir(name): - """Is the named metadata a directory? (like ``os.path.isdir()``)""" - - def metadata_listdir(name): - """List of metadata names in the directory (like ``os.listdir()``)""" - - def run_script(script_name, namespace): - """Execute the named script in the supplied namespace dictionary""" - - -class IResourceProvider(IMetadataProvider): - """An object that provides access to package resources""" - - def get_resource_filename(manager, resource_name): - """Return a true filesystem path for `resource_name` - - `manager` must be an ``IResourceManager``""" - - def get_resource_stream(manager, resource_name): - """Return a readable file-like object for `resource_name` - - `manager` must be an ``IResourceManager``""" - - def get_resource_string(manager, resource_name): - """Return a string containing the contents of `resource_name` - - `manager` must be an ``IResourceManager``""" - - def has_resource(resource_name): - """Does the package contain the named resource?""" - - def resource_isdir(resource_name): - """Is the named resource a directory? (like ``os.path.isdir()``)""" - - def resource_listdir(resource_name): - """List of resource names in the directory (like ``os.listdir()``)""" - - -class WorkingSet: - """A collection of active distributions on sys.path (or a similar list)""" - - def __init__(self, entries=None): - """Create working set from list of path entries (default=sys.path)""" - self.entries = [] - self.entry_keys = {} - self.by_key = {} - self.normalized_to_canonical_keys = {} - self.callbacks = [] - - if entries is None: - entries = sys.path - - for entry in entries: - self.add_entry(entry) - - @classmethod - def _build_master(cls): - """ - Prepare the master working set. - """ - ws = cls() - try: - from __main__ import __requires__ - except ImportError: - # The main program does not list any requirements - return ws - - # ensure the requirements are met - try: - ws.require(__requires__) - except VersionConflict: - return cls._build_from_requirements(__requires__) - - return ws - - @classmethod - def _build_from_requirements(cls, req_spec): - """ - Build a working set from a requirement spec. Rewrites sys.path. - """ - # try it without defaults already on sys.path - # by starting with an empty path - ws = cls([]) - reqs = parse_requirements(req_spec) - dists = ws.resolve(reqs, Environment()) - for dist in dists: - ws.add(dist) - - # add any missing entries from sys.path - for entry in sys.path: - if entry not in ws.entries: - ws.add_entry(entry) - - # then copy back to sys.path - sys.path[:] = ws.entries - return ws - - def add_entry(self, entry): - """Add a path item to ``.entries``, finding any distributions on it - - ``find_distributions(entry, True)`` is used to find distributions - corresponding to the path entry, and they are added. `entry` is - always appended to ``.entries``, even if it is already present. - (This is because ``sys.path`` can contain the same value more than - once, and the ``.entries`` of the ``sys.path`` WorkingSet should always - equal ``sys.path``.) - """ - self.entry_keys.setdefault(entry, []) - self.entries.append(entry) - for dist in find_distributions(entry, True): - self.add(dist, entry, False) - - def __contains__(self, dist): - """True if `dist` is the active distribution for its project""" - return self.by_key.get(dist.key) == dist - - def find(self, req): - """Find a distribution matching requirement `req` - - If there is an active distribution for the requested project, this - returns it as long as it meets the version requirement specified by - `req`. But, if there is an active distribution for the project and it - does *not* meet the `req` requirement, ``VersionConflict`` is raised. - If there is no active distribution for the requested project, ``None`` - is returned. - """ - dist = self.by_key.get(req.key) - - if dist is None: - canonical_key = self.normalized_to_canonical_keys.get(req.key) - - if canonical_key is not None: - req.key = canonical_key - dist = self.by_key.get(canonical_key) - - if dist is not None and dist not in req: - # XXX add more info - raise VersionConflict(dist, req) - return dist - - def iter_entry_points(self, group, name=None): - """Yield entry point objects from `group` matching `name` - - If `name` is None, yields all entry points in `group` from all - distributions in the working set, otherwise only ones matching - both `group` and `name` are yielded (in distribution order). - """ - return ( - entry - for dist in self - for entry in dist.get_entry_map(group).values() - if name is None or name == entry.name - ) - - def run_script(self, requires, script_name): - """Locate distribution for `requires` and run `script_name` script""" - ns = sys._getframe(1).f_globals - name = ns['__name__'] - ns.clear() - ns['__name__'] = name - self.require(requires)[0].run_script(script_name, ns) - - def __iter__(self): - """Yield distributions for non-duplicate projects in the working set - - The yield order is the order in which the items' path entries were - added to the working set. - """ - seen = {} - for item in self.entries: - if item not in self.entry_keys: - # workaround a cache issue - continue - - for key in self.entry_keys[item]: - if key not in seen: - seen[key] = 1 - yield self.by_key[key] - - def add(self, dist, entry=None, insert=True, replace=False): - """Add `dist` to working set, associated with `entry` - - If `entry` is unspecified, it defaults to the ``.location`` of `dist`. - On exit from this routine, `entry` is added to the end of the working - set's ``.entries`` (if it wasn't already present). - - `dist` is only added to the working set if it's for a project that - doesn't already have a distribution in the set, unless `replace=True`. - If it's added, any callbacks registered with the ``subscribe()`` method - will be called. - """ - if insert: - dist.insert_on(self.entries, entry, replace=replace) - - if entry is None: - entry = dist.location - keys = self.entry_keys.setdefault(entry, []) - keys2 = self.entry_keys.setdefault(dist.location, []) - if not replace and dist.key in self.by_key: - # ignore hidden distros - return - - self.by_key[dist.key] = dist - normalized_name = packaging.utils.canonicalize_name(dist.key) - self.normalized_to_canonical_keys[normalized_name] = dist.key - if dist.key not in keys: - keys.append(dist.key) - if dist.key not in keys2: - keys2.append(dist.key) - self._added_new(dist) - - def resolve( - self, - requirements, - env=None, - installer=None, - replace_conflicting=False, - extras=None, - ): - """List all distributions needed to (recursively) meet `requirements` - - `requirements` must be a sequence of ``Requirement`` objects. `env`, - if supplied, should be an ``Environment`` instance. If - not supplied, it defaults to all distributions available within any - entry or distribution in the working set. `installer`, if supplied, - will be invoked with each requirement that cannot be met by an - already-installed distribution; it should return a ``Distribution`` or - ``None``. - - Unless `replace_conflicting=True`, raises a VersionConflict exception - if - any requirements are found on the path that have the correct name but - the wrong version. Otherwise, if an `installer` is supplied it will be - invoked to obtain the correct version of the requirement and activate - it. - - `extras` is a list of the extras to be used with these requirements. - This is important because extra requirements may look like `my_req; - extra = "my_extra"`, which would otherwise be interpreted as a purely - optional requirement. Instead, we want to be able to assert that these - requirements are truly required. - """ - - # set up the stack - requirements = list(requirements)[::-1] - # set of processed requirements - processed = {} - # key -> dist - best = {} - to_activate = [] - - req_extras = _ReqExtras() - - # Mapping of requirement to set of distributions that required it; - # useful for reporting info about conflicts. - required_by = collections.defaultdict(set) - - while requirements: - # process dependencies breadth-first - req = requirements.pop(0) - if req in processed: - # Ignore cyclic or redundant dependencies - continue - - if not req_extras.markers_pass(req, extras): - continue - - dist = self._resolve_dist( - req, best, replace_conflicting, env, installer, required_by, to_activate - ) - - # push the new requirements onto the stack - new_requirements = dist.requires(req.extras)[::-1] - requirements.extend(new_requirements) - - # Register the new requirements needed by req - for new_requirement in new_requirements: - required_by[new_requirement].add(req.project_name) - req_extras[new_requirement] = req.extras - - processed[req] = True - - # return list of distros to activate - return to_activate - - def _resolve_dist( - self, req, best, replace_conflicting, env, installer, required_by, to_activate - ): - dist = best.get(req.key) - if dist is None: - # Find the best distribution and add it to the map - dist = self.by_key.get(req.key) - if dist is None or (dist not in req and replace_conflicting): - ws = self - if env is None: - if dist is None: - env = Environment(self.entries) - else: - # Use an empty environment and workingset to avoid - # any further conflicts with the conflicting - # distribution - env = Environment([]) - ws = WorkingSet([]) - dist = best[req.key] = env.best_match( - req, ws, installer, replace_conflicting=replace_conflicting - ) - if dist is None: - requirers = required_by.get(req, None) - raise DistributionNotFound(req, requirers) - to_activate.append(dist) - if dist not in req: - # Oops, the "best" so far conflicts with a dependency - dependent_req = required_by[req] - raise VersionConflict(dist, req).with_context(dependent_req) - return dist - - def find_plugins(self, plugin_env, full_env=None, installer=None, fallback=True): - """Find all activatable distributions in `plugin_env` - - Example usage:: - - distributions, errors = working_set.find_plugins( - Environment(plugin_dirlist) - ) - # add plugins+libs to sys.path - map(working_set.add, distributions) - # display errors - print('Could not load', errors) - - The `plugin_env` should be an ``Environment`` instance that contains - only distributions that are in the project's "plugin directory" or - directories. The `full_env`, if supplied, should be an ``Environment`` - contains all currently-available distributions. If `full_env` is not - supplied, one is created automatically from the ``WorkingSet`` this - method is called on, which will typically mean that every directory on - ``sys.path`` will be scanned for distributions. - - `installer` is a standard installer callback as used by the - ``resolve()`` method. The `fallback` flag indicates whether we should - attempt to resolve older versions of a plugin if the newest version - cannot be resolved. - - This method returns a 2-tuple: (`distributions`, `error_info`), where - `distributions` is a list of the distributions found in `plugin_env` - that were loadable, along with any other distributions that are needed - to resolve their dependencies. `error_info` is a dictionary mapping - unloadable plugin distributions to an exception instance describing the - error that occurred. Usually this will be a ``DistributionNotFound`` or - ``VersionConflict`` instance. - """ - - plugin_projects = list(plugin_env) - # scan project names in alphabetic order - plugin_projects.sort() - - error_info = {} - distributions = {} - - if full_env is None: - env = Environment(self.entries) - env += plugin_env - else: - env = full_env + plugin_env - - shadow_set = self.__class__([]) - # put all our entries in shadow_set - list(map(shadow_set.add, self)) - - for project_name in plugin_projects: - for dist in plugin_env[project_name]: - req = [dist.as_requirement()] - - try: - resolvees = shadow_set.resolve(req, env, installer) - - except ResolutionError as v: - # save error info - error_info[dist] = v - if fallback: - # try the next older version of project - continue - else: - # give up on this project, keep going - break - - else: - list(map(shadow_set.add, resolvees)) - distributions.update(dict.fromkeys(resolvees)) - - # success, no need to try any more versions of this project - break - - distributions = list(distributions) - distributions.sort() - - return distributions, error_info - - def require(self, *requirements): - """Ensure that distributions matching `requirements` are activated - - `requirements` must be a string or a (possibly-nested) sequence - thereof, specifying the distributions and versions required. The - return value is a sequence of the distributions that needed to be - activated to fulfill the requirements; all relevant distributions are - included, even if they were already activated in this working set. - """ - needed = self.resolve(parse_requirements(requirements)) - - for dist in needed: - self.add(dist) - - return needed - - def subscribe(self, callback, existing=True): - """Invoke `callback` for all distributions - - If `existing=True` (default), - call on all existing ones, as well. - """ - if callback in self.callbacks: - return - self.callbacks.append(callback) - if not existing: - return - for dist in self: - callback(dist) - - def _added_new(self, dist): - for callback in self.callbacks: - callback(dist) - - def __getstate__(self): - return ( - self.entries[:], - self.entry_keys.copy(), - self.by_key.copy(), - self.normalized_to_canonical_keys.copy(), - self.callbacks[:], - ) - - def __setstate__(self, e_k_b_n_c): - entries, keys, by_key, normalized_to_canonical_keys, callbacks = e_k_b_n_c - self.entries = entries[:] - self.entry_keys = keys.copy() - self.by_key = by_key.copy() - self.normalized_to_canonical_keys = normalized_to_canonical_keys.copy() - self.callbacks = callbacks[:] - - -class _ReqExtras(dict): - """ - Map each requirement to the extras that demanded it. - """ - - def markers_pass(self, req, extras=None): - """ - Evaluate markers for req against each extra that - demanded it. - - Return False if the req has a marker and fails - evaluation. Otherwise, return True. - """ - extra_evals = ( - req.marker.evaluate({'extra': extra}) - for extra in self.get(req, ()) + (extras or (None,)) - ) - return not req.marker or any(extra_evals) - - -class Environment: - """Searchable snapshot of distributions on a search path""" - - def __init__( - self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR - ): - """Snapshot distributions available on a search path - - Any distributions found on `search_path` are added to the environment. - `search_path` should be a sequence of ``sys.path`` items. If not - supplied, ``sys.path`` is used. - - `platform` is an optional string specifying the name of the platform - that platform-specific distributions must be compatible with. If - unspecified, it defaults to the current platform. `python` is an - optional string naming the desired version of Python (e.g. ``'3.6'``); - it defaults to the current version. - - You may explicitly set `platform` (and/or `python`) to ``None`` if you - wish to map *all* distributions, not just those compatible with the - running platform or Python version. - """ - self._distmap = {} - self.platform = platform - self.python = python - self.scan(search_path) - - def can_add(self, dist): - """Is distribution `dist` acceptable for this environment? - - The distribution must match the platform and python version - requirements specified when this environment was created, or False - is returned. - """ - py_compat = ( - self.python is None - or dist.py_version is None - or dist.py_version == self.python - ) - return py_compat and compatible_platforms(dist.platform, self.platform) - - def remove(self, dist): - """Remove `dist` from the environment""" - self._distmap[dist.key].remove(dist) - - def scan(self, search_path=None): - """Scan `search_path` for distributions usable in this environment - - Any distributions found are added to the environment. - `search_path` should be a sequence of ``sys.path`` items. If not - supplied, ``sys.path`` is used. Only distributions conforming to - the platform/python version defined at initialization are added. - """ - if search_path is None: - search_path = sys.path - - for item in search_path: - for dist in find_distributions(item): - self.add(dist) - - def __getitem__(self, project_name): - """Return a newest-to-oldest list of distributions for `project_name` - - Uses case-insensitive `project_name` comparison, assuming all the - project's distributions use their project's name converted to all - lowercase as their key. - - """ - distribution_key = project_name.lower() - return self._distmap.get(distribution_key, []) - - def add(self, dist): - """Add `dist` if we ``can_add()`` it and it has not already been added""" - if self.can_add(dist) and dist.has_version(): - dists = self._distmap.setdefault(dist.key, []) - if dist not in dists: - dists.append(dist) - dists.sort(key=operator.attrgetter('hashcmp'), reverse=True) - - def best_match(self, req, working_set, installer=None, replace_conflicting=False): - """Find distribution best matching `req` and usable on `working_set` - - This calls the ``find(req)`` method of the `working_set` to see if a - suitable distribution is already active. (This may raise - ``VersionConflict`` if an unsuitable version of the project is already - active in the specified `working_set`.) If a suitable distribution - isn't active, this method returns the newest distribution in the - environment that meets the ``Requirement`` in `req`. If no suitable - distribution is found, and `installer` is supplied, then the result of - calling the environment's ``obtain(req, installer)`` method will be - returned. - """ - try: - dist = working_set.find(req) - except VersionConflict: - if not replace_conflicting: - raise - dist = None - if dist is not None: - return dist - for dist in self[req.key]: - if dist in req: - return dist - # try to download/install - return self.obtain(req, installer) - - def obtain(self, requirement, installer=None): - """Obtain a distribution matching `requirement` (e.g. via download) - - Obtain a distro that matches requirement (e.g. via download). In the - base ``Environment`` class, this routine just returns - ``installer(requirement)``, unless `installer` is None, in which case - None is returned instead. This method is a hook that allows subclasses - to attempt other ways of obtaining a distribution before falling back - to the `installer` argument.""" - if installer is not None: - return installer(requirement) - - def __iter__(self): - """Yield the unique project names of the available distributions""" - for key in self._distmap.keys(): - if self[key]: - yield key - - def __iadd__(self, other): - """In-place addition of a distribution or environment""" - if isinstance(other, Distribution): - self.add(other) - elif isinstance(other, Environment): - for project in other: - for dist in other[project]: - self.add(dist) - else: - raise TypeError("Can't add %r to environment" % (other,)) - return self - - def __add__(self, other): - """Add an environment or distribution to an environment""" - new = self.__class__([], platform=None, python=None) - for env in self, other: - new += env - return new - - -# XXX backward compatibility -AvailableDistributions = Environment - - -class ExtractionError(RuntimeError): - """An error occurred extracting a resource - - The following attributes are available from instances of this exception: - - manager - The resource manager that raised this exception - - cache_path - The base directory for resource extraction - - original_error - The exception instance that caused extraction to fail - """ - - -class ResourceManager: - """Manage resource extraction and packages""" - - extraction_path = None - - def __init__(self): - self.cached_files = {} - - def resource_exists(self, package_or_requirement, resource_name): - """Does the named resource exist?""" - return get_provider(package_or_requirement).has_resource(resource_name) - - def resource_isdir(self, package_or_requirement, resource_name): - """Is the named resource an existing directory?""" - return get_provider(package_or_requirement).resource_isdir(resource_name) - - def resource_filename(self, package_or_requirement, resource_name): - """Return a true filesystem path for specified resource""" - return get_provider(package_or_requirement).get_resource_filename( - self, resource_name - ) - - def resource_stream(self, package_or_requirement, resource_name): - """Return a readable file-like object for specified resource""" - return get_provider(package_or_requirement).get_resource_stream( - self, resource_name - ) - - def resource_string(self, package_or_requirement, resource_name): - """Return specified resource as a string""" - return get_provider(package_or_requirement).get_resource_string( - self, resource_name - ) - - def resource_listdir(self, package_or_requirement, resource_name): - """List the contents of the named resource directory""" - return get_provider(package_or_requirement).resource_listdir(resource_name) - - def extraction_error(self): - """Give an error message for problems extracting file(s)""" - - old_exc = sys.exc_info()[1] - cache_path = self.extraction_path or get_default_cache() - - tmpl = textwrap.dedent( - """ - Can't extract file(s) to egg cache - - The following error occurred while trying to extract file(s) - to the Python egg cache: - - {old_exc} - - The Python egg cache directory is currently set to: - - {cache_path} - - Perhaps your account does not have write access to this directory? - You can change the cache directory by setting the PYTHON_EGG_CACHE - environment variable to point to an accessible directory. - """ - ).lstrip() - err = ExtractionError(tmpl.format(**locals())) - err.manager = self - err.cache_path = cache_path - err.original_error = old_exc - raise err - - def get_cache_path(self, archive_name, names=()): - """Return absolute location in cache for `archive_name` and `names` - - The parent directory of the resulting path will be created if it does - not already exist. `archive_name` should be the base filename of the - enclosing egg (which may not be the name of the enclosing zipfile!), - including its ".egg" extension. `names`, if provided, should be a - sequence of path name parts "under" the egg's extraction location. - - This method should only be called by resource providers that need to - obtain an extraction location, and only for names they intend to - extract, as it tracks the generated names for possible cleanup later. - """ - extract_path = self.extraction_path or get_default_cache() - target_path = os.path.join(extract_path, archive_name + '-tmp', *names) - try: - _bypass_ensure_directory(target_path) - except Exception: - self.extraction_error() - - self._warn_unsafe_extraction_path(extract_path) - - self.cached_files[target_path] = 1 - return target_path - - @staticmethod - def _warn_unsafe_extraction_path(path): - """ - If the default extraction path is overridden and set to an insecure - location, such as /tmp, it opens up an opportunity for an attacker to - replace an extracted file with an unauthorized payload. Warn the user - if a known insecure location is used. - - See Distribute #375 for more details. - """ - if os.name == 'nt' and not path.startswith(os.environ['windir']): - # On Windows, permissions are generally restrictive by default - # and temp directories are not writable by other users, so - # bypass the warning. - return - mode = os.stat(path).st_mode - if mode & stat.S_IWOTH or mode & stat.S_IWGRP: - msg = ( - "Extraction path is writable by group/others " - "and vulnerable to attack when " - "used with get_resource_filename ({path}). " - "Consider a more secure " - "location (set with .set_extraction_path or the " - "PYTHON_EGG_CACHE environment variable)." - ).format(**locals()) - warnings.warn(msg, UserWarning) - - def postprocess(self, tempname, filename): - """Perform any platform-specific postprocessing of `tempname` - - This is where Mac header rewrites should be done; other platforms don't - have anything special they should do. - - Resource providers should call this method ONLY after successfully - extracting a compressed resource. They must NOT call it on resources - that are already in the filesystem. - - `tempname` is the current (temporary) name of the file, and `filename` - is the name it will be renamed to by the caller after this routine - returns. - """ - - if os.name == 'posix': - # Make the resource executable - mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777 - os.chmod(tempname, mode) - - def set_extraction_path(self, path): - """Set the base path where resources will be extracted to, if needed. - - If you do not call this routine before any extractions take place, the - path defaults to the return value of ``get_default_cache()``. (Which - is based on the ``PYTHON_EGG_CACHE`` environment variable, with various - platform-specific fallbacks. See that routine's documentation for more - details.) - - Resources are extracted to subdirectories of this path based upon - information given by the ``IResourceProvider``. You may set this to a - temporary directory, but then you must call ``cleanup_resources()`` to - delete the extracted files when done. There is no guarantee that - ``cleanup_resources()`` will be able to remove all extracted files. - - (Note: you may not change the extraction path for a given resource - manager once resources have been extracted, unless you first call - ``cleanup_resources()``.) - """ - if self.cached_files: - raise ValueError("Can't change extraction path, files already extracted") - - self.extraction_path = path - - def cleanup_resources(self, force=False): - """ - Delete all extracted resource files and directories, returning a list - of the file and directory names that could not be successfully removed. - This function does not have any concurrency protection, so it should - generally only be called when the extraction path is a temporary - directory exclusive to a single process. This method is not - automatically called; you must call it explicitly or register it as an - ``atexit`` function if you wish to ensure cleanup of a temporary - directory used for extractions. - """ - # XXX - - -def get_default_cache(): - """ - Return the ``PYTHON_EGG_CACHE`` environment variable - or a platform-relevant user cache dir for an app - named "Python-Eggs". - """ - return os.environ.get('PYTHON_EGG_CACHE') or platformdirs.user_cache_dir( - appname='Python-Eggs' - ) - - -def safe_name(name): - """Convert an arbitrary string to a standard distribution name - - Any runs of non-alphanumeric/. characters are replaced with a single '-'. - """ - return re.sub('[^A-Za-z0-9.]+', '-', name) - - -def safe_version(version): - """ - Convert an arbitrary string to a standard version string - """ - try: - # normalize the version - return str(packaging.version.Version(version)) - except packaging.version.InvalidVersion: - version = version.replace(' ', '.') - return re.sub('[^A-Za-z0-9.]+', '-', version) - - -def _forgiving_version(version): - """Fallback when ``safe_version`` is not safe enough - >>> parse_version(_forgiving_version('0.23ubuntu1')) - - >>> parse_version(_forgiving_version('0.23-')) - - >>> parse_version(_forgiving_version('0.-_')) - - >>> parse_version(_forgiving_version('42.+?1')) - - >>> parse_version(_forgiving_version('hello world')) - - """ - version = version.replace(' ', '.') - match = _PEP440_FALLBACK.search(version) - if match: - safe = match["safe"] - rest = version[len(safe) :] - else: - safe = "0" - rest = version - local = f"sanitized.{_safe_segment(rest)}".strip(".") - return f"{safe}.dev0+{local}" - - -def _safe_segment(segment): - """Convert an arbitrary string into a safe segment""" - segment = re.sub('[^A-Za-z0-9.]+', '-', segment) - segment = re.sub('-[^A-Za-z0-9]+', '-', segment) - return re.sub(r'\.[^A-Za-z0-9]+', '.', segment).strip(".-") - - -def safe_extra(extra): - """Convert an arbitrary string to a standard 'extra' name - - Any runs of non-alphanumeric characters are replaced with a single '_', - and the result is always lowercased. - """ - return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower() - - -def to_filename(name): - """Convert a project or version name to its filename-escaped form - - Any '-' characters are currently replaced with '_'. - """ - return name.replace('-', '_') - - -def invalid_marker(text): - """ - Validate text as a PEP 508 environment marker; return an exception - if invalid or False otherwise. - """ - try: - evaluate_marker(text) - except SyntaxError as e: - e.filename = None - e.lineno = None - return e - return False - - -def evaluate_marker(text, extra=None): - """ - Evaluate a PEP 508 environment marker. - Return a boolean indicating the marker result in this environment. - Raise SyntaxError if marker is invalid. - - This implementation uses the 'pyparsing' module. - """ - try: - marker = packaging.markers.Marker(text) - return marker.evaluate() - except packaging.markers.InvalidMarker as e: - raise SyntaxError(e) from e - - -class NullProvider: - """Try to implement resources and metadata for arbitrary PEP 302 loaders""" - - egg_name = None - egg_info = None - loader = None - - def __init__(self, module): - self.loader = getattr(module, '__loader__', None) - self.module_path = os.path.dirname(getattr(module, '__file__', '')) - - def get_resource_filename(self, manager, resource_name): - return self._fn(self.module_path, resource_name) - - def get_resource_stream(self, manager, resource_name): - return io.BytesIO(self.get_resource_string(manager, resource_name)) - - def get_resource_string(self, manager, resource_name): - return self._get(self._fn(self.module_path, resource_name)) - - def has_resource(self, resource_name): - return self._has(self._fn(self.module_path, resource_name)) - - def _get_metadata_path(self, name): - return self._fn(self.egg_info, name) - - def has_metadata(self, name): - if not self.egg_info: - return self.egg_info - - path = self._get_metadata_path(name) - return self._has(path) - - def get_metadata(self, name): - if not self.egg_info: - return "" - path = self._get_metadata_path(name) - value = self._get(path) - try: - return value.decode('utf-8') - except UnicodeDecodeError as exc: - # Include the path in the error message to simplify - # troubleshooting, and without changing the exception type. - exc.reason += ' in {} file at path: {}'.format(name, path) - raise - - def get_metadata_lines(self, name): - return yield_lines(self.get_metadata(name)) - - def resource_isdir(self, resource_name): - return self._isdir(self._fn(self.module_path, resource_name)) - - def metadata_isdir(self, name): - return self.egg_info and self._isdir(self._fn(self.egg_info, name)) - - def resource_listdir(self, resource_name): - return self._listdir(self._fn(self.module_path, resource_name)) - - def metadata_listdir(self, name): - if self.egg_info: - return self._listdir(self._fn(self.egg_info, name)) - return [] - - def run_script(self, script_name, namespace): - script = 'scripts/' + script_name - if not self.has_metadata(script): - raise ResolutionError( - "Script {script!r} not found in metadata at {self.egg_info!r}".format( - **locals() - ), - ) - script_text = self.get_metadata(script).replace('\r\n', '\n') - script_text = script_text.replace('\r', '\n') - script_filename = self._fn(self.egg_info, script) - namespace['__file__'] = script_filename - if os.path.exists(script_filename): - with open(script_filename) as fid: - source = fid.read() - code = compile(source, script_filename, 'exec') - exec(code, namespace, namespace) - else: - from linecache import cache - - cache[script_filename] = ( - len(script_text), - 0, - script_text.split('\n'), - script_filename, - ) - script_code = compile(script_text, script_filename, 'exec') - exec(script_code, namespace, namespace) - - def _has(self, path): - raise NotImplementedError( - "Can't perform this operation for unregistered loader type" - ) - - def _isdir(self, path): - raise NotImplementedError( - "Can't perform this operation for unregistered loader type" - ) - - def _listdir(self, path): - raise NotImplementedError( - "Can't perform this operation for unregistered loader type" - ) - - def _fn(self, base, resource_name): - self._validate_resource_path(resource_name) - if resource_name: - return os.path.join(base, *resource_name.split('/')) - return base - - @staticmethod - def _validate_resource_path(path): - """ - Validate the resource paths according to the docs. - https://setuptools.pypa.io/en/latest/pkg_resources.html#basic-resource-access - - >>> warned = getfixture('recwarn') - >>> warnings.simplefilter('always') - >>> vrp = NullProvider._validate_resource_path - >>> vrp('foo/bar.txt') - >>> bool(warned) - False - >>> vrp('../foo/bar.txt') - >>> bool(warned) - True - >>> warned.clear() - >>> vrp('/foo/bar.txt') - >>> bool(warned) - True - >>> vrp('foo/../../bar.txt') - >>> bool(warned) - True - >>> warned.clear() - >>> vrp('foo/f../bar.txt') - >>> bool(warned) - False - - Windows path separators are straight-up disallowed. - >>> vrp(r'\\foo/bar.txt') - Traceback (most recent call last): - ... - ValueError: Use of .. or absolute path in a resource path \ -is not allowed. - - >>> vrp(r'C:\\foo/bar.txt') - Traceback (most recent call last): - ... - ValueError: Use of .. or absolute path in a resource path \ -is not allowed. - - Blank values are allowed - - >>> vrp('') - >>> bool(warned) - False - - Non-string values are not. - - >>> vrp(None) - Traceback (most recent call last): - ... - AttributeError: ... - """ - invalid = ( - os.path.pardir in path.split(posixpath.sep) - or posixpath.isabs(path) - or ntpath.isabs(path) - ) - if not invalid: - return - - msg = "Use of .. or absolute path in a resource path is not allowed." - - # Aggressively disallow Windows absolute paths - if ntpath.isabs(path) and not posixpath.isabs(path): - raise ValueError(msg) - - # for compatibility, warn; in future - # raise ValueError(msg) - issue_warning( - msg[:-1] + " and will raise exceptions in a future release.", - DeprecationWarning, - ) - - def _get(self, path): - if hasattr(self.loader, 'get_data'): - return self.loader.get_data(path) - raise NotImplementedError( - "Can't perform this operation for loaders without 'get_data()'" - ) - - -register_loader_type(object, NullProvider) - - -def _parents(path): - """ - yield all parents of path including path - """ - last = None - while path != last: - yield path - last = path - path, _ = os.path.split(path) - - -class EggProvider(NullProvider): - """Provider based on a virtual filesystem""" - - def __init__(self, module): - super().__init__(module) - self._setup_prefix() - - def _setup_prefix(self): - # Assume that metadata may be nested inside a "basket" - # of multiple eggs and use module_path instead of .archive. - eggs = filter(_is_egg_path, _parents(self.module_path)) - egg = next(eggs, None) - egg and self._set_egg(egg) - - def _set_egg(self, path): - self.egg_name = os.path.basename(path) - self.egg_info = os.path.join(path, 'EGG-INFO') - self.egg_root = path - - -class DefaultProvider(EggProvider): - """Provides access to package resources in the filesystem""" - - def _has(self, path): - return os.path.exists(path) - - def _isdir(self, path): - return os.path.isdir(path) - - def _listdir(self, path): - return os.listdir(path) - - def get_resource_stream(self, manager, resource_name): - return open(self._fn(self.module_path, resource_name), 'rb') - - def _get(self, path): - with open(path, 'rb') as stream: - return stream.read() - - @classmethod - def _register(cls): - loader_names = ( - 'SourceFileLoader', - 'SourcelessFileLoader', - ) - for name in loader_names: - loader_cls = getattr(importlib_machinery, name, type(None)) - register_loader_type(loader_cls, cls) - - -DefaultProvider._register() - - -class EmptyProvider(NullProvider): - """Provider that returns nothing for all requests""" - - module_path = None - - _isdir = _has = lambda self, path: False - - def _get(self, path): - return '' - - def _listdir(self, path): - return [] - - def __init__(self): - pass - - -empty_provider = EmptyProvider() - - -class ZipManifests(dict): - """ - zip manifest builder - """ - - @classmethod - def build(cls, path): - """ - Build a dictionary similar to the zipimport directory - caches, except instead of tuples, store ZipInfo objects. - - Use a platform-specific path separator (os.sep) for the path keys - for compatibility with pypy on Windows. - """ - with zipfile.ZipFile(path) as zfile: - items = ( - ( - name.replace('/', os.sep), - zfile.getinfo(name), - ) - for name in zfile.namelist() - ) - return dict(items) - - load = build - - -class MemoizedZipManifests(ZipManifests): - """ - Memoized zipfile manifests. - """ - - manifest_mod = collections.namedtuple('manifest_mod', 'manifest mtime') - - def load(self, path): - """ - Load a manifest at path or return a suitable manifest already loaded. - """ - path = os.path.normpath(path) - mtime = os.stat(path).st_mtime - - if path not in self or self[path].mtime != mtime: - manifest = self.build(path) - self[path] = self.manifest_mod(manifest, mtime) - - return self[path].manifest - - -class ZipProvider(EggProvider): - """Resource support for zips and eggs""" - - eagers = None - _zip_manifests = MemoizedZipManifests() - - def __init__(self, module): - super().__init__(module) - self.zip_pre = self.loader.archive + os.sep - - def _zipinfo_name(self, fspath): - # Convert a virtual filename (full path to file) into a zipfile subpath - # usable with the zipimport directory cache for our target archive - fspath = fspath.rstrip(os.sep) - if fspath == self.loader.archive: - return '' - if fspath.startswith(self.zip_pre): - return fspath[len(self.zip_pre) :] - raise AssertionError("%s is not a subpath of %s" % (fspath, self.zip_pre)) - - def _parts(self, zip_path): - # Convert a zipfile subpath into an egg-relative path part list. - # pseudo-fs path - fspath = self.zip_pre + zip_path - if fspath.startswith(self.egg_root + os.sep): - return fspath[len(self.egg_root) + 1 :].split(os.sep) - raise AssertionError("%s is not a subpath of %s" % (fspath, self.egg_root)) - - @property - def zipinfo(self): - return self._zip_manifests.load(self.loader.archive) - - def get_resource_filename(self, manager, resource_name): - if not self.egg_name: - raise NotImplementedError( - "resource_filename() only supported for .egg, not .zip" - ) - # no need to lock for extraction, since we use temp names - zip_path = self._resource_to_zip(resource_name) - eagers = self._get_eager_resources() - if '/'.join(self._parts(zip_path)) in eagers: - for name in eagers: - self._extract_resource(manager, self._eager_to_zip(name)) - return self._extract_resource(manager, zip_path) - - @staticmethod - def _get_date_and_size(zip_stat): - size = zip_stat.file_size - # ymdhms+wday, yday, dst - date_time = zip_stat.date_time + (0, 0, -1) - # 1980 offset already done - timestamp = time.mktime(date_time) - return timestamp, size - - # FIXME: 'ZipProvider._extract_resource' is too complex (12) - def _extract_resource(self, manager, zip_path): # noqa: C901 - if zip_path in self._index(): - for name in self._index()[zip_path]: - last = self._extract_resource(manager, os.path.join(zip_path, name)) - # return the extracted directory name - return os.path.dirname(last) - - timestamp, size = self._get_date_and_size(self.zipinfo[zip_path]) - - if not WRITE_SUPPORT: - raise IOError( - '"os.rename" and "os.unlink" are not supported ' 'on this platform' - ) - try: - real_path = manager.get_cache_path(self.egg_name, self._parts(zip_path)) - - if self._is_current(real_path, zip_path): - return real_path - - outf, tmpnam = _mkstemp( - ".$extract", - dir=os.path.dirname(real_path), - ) - os.write(outf, self.loader.get_data(zip_path)) - os.close(outf) - utime(tmpnam, (timestamp, timestamp)) - manager.postprocess(tmpnam, real_path) - - try: - rename(tmpnam, real_path) - - except os.error: - if os.path.isfile(real_path): - if self._is_current(real_path, zip_path): - # the file became current since it was checked above, - # so proceed. - return real_path - # Windows, del old file and retry - elif os.name == 'nt': - unlink(real_path) - rename(tmpnam, real_path) - return real_path - raise - - except os.error: - # report a user-friendly error - manager.extraction_error() - - return real_path - - def _is_current(self, file_path, zip_path): - """ - Return True if the file_path is current for this zip_path - """ - timestamp, size = self._get_date_and_size(self.zipinfo[zip_path]) - if not os.path.isfile(file_path): - return False - stat = os.stat(file_path) - if stat.st_size != size or stat.st_mtime != timestamp: - return False - # check that the contents match - zip_contents = self.loader.get_data(zip_path) - with open(file_path, 'rb') as f: - file_contents = f.read() - return zip_contents == file_contents - - def _get_eager_resources(self): - if self.eagers is None: - eagers = [] - for name in ('native_libs.txt', 'eager_resources.txt'): - if self.has_metadata(name): - eagers.extend(self.get_metadata_lines(name)) - self.eagers = eagers - return self.eagers - - def _index(self): - try: - return self._dirindex - except AttributeError: - ind = {} - for path in self.zipinfo: - parts = path.split(os.sep) - while parts: - parent = os.sep.join(parts[:-1]) - if parent in ind: - ind[parent].append(parts[-1]) - break - else: - ind[parent] = [parts.pop()] - self._dirindex = ind - return ind - - def _has(self, fspath): - zip_path = self._zipinfo_name(fspath) - return zip_path in self.zipinfo or zip_path in self._index() - - def _isdir(self, fspath): - return self._zipinfo_name(fspath) in self._index() - - def _listdir(self, fspath): - return list(self._index().get(self._zipinfo_name(fspath), ())) - - def _eager_to_zip(self, resource_name): - return self._zipinfo_name(self._fn(self.egg_root, resource_name)) - - def _resource_to_zip(self, resource_name): - return self._zipinfo_name(self._fn(self.module_path, resource_name)) - - -register_loader_type(zipimport.zipimporter, ZipProvider) - - -class FileMetadata(EmptyProvider): - """Metadata handler for standalone PKG-INFO files - - Usage:: - - metadata = FileMetadata("/path/to/PKG-INFO") - - This provider rejects all data and metadata requests except for PKG-INFO, - which is treated as existing, and will be the contents of the file at - the provided location. - """ - - def __init__(self, path): - self.path = path - - def _get_metadata_path(self, name): - return self.path - - def has_metadata(self, name): - return name == 'PKG-INFO' and os.path.isfile(self.path) - - def get_metadata(self, name): - if name != 'PKG-INFO': - raise KeyError("No metadata except PKG-INFO is available") - - with io.open(self.path, encoding='utf-8', errors="replace") as f: - metadata = f.read() - self._warn_on_replacement(metadata) - return metadata - - def _warn_on_replacement(self, metadata): - replacement_char = '�' - if replacement_char in metadata: - tmpl = "{self.path} could not be properly decoded in UTF-8" - msg = tmpl.format(**locals()) - warnings.warn(msg) - - def get_metadata_lines(self, name): - return yield_lines(self.get_metadata(name)) - - -class PathMetadata(DefaultProvider): - """Metadata provider for egg directories - - Usage:: - - # Development eggs: - - egg_info = "/path/to/PackageName.egg-info" - base_dir = os.path.dirname(egg_info) - metadata = PathMetadata(base_dir, egg_info) - dist_name = os.path.splitext(os.path.basename(egg_info))[0] - dist = Distribution(basedir, project_name=dist_name, metadata=metadata) - - # Unpacked egg directories: - - egg_path = "/path/to/PackageName-ver-pyver-etc.egg" - metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO')) - dist = Distribution.from_filename(egg_path, metadata=metadata) - """ - - def __init__(self, path, egg_info): - self.module_path = path - self.egg_info = egg_info - - -class EggMetadata(ZipProvider): - """Metadata provider for .egg files""" - - def __init__(self, importer): - """Create a metadata provider from a zipimporter""" - - self.zip_pre = importer.archive + os.sep - self.loader = importer - if importer.prefix: - self.module_path = os.path.join(importer.archive, importer.prefix) - else: - self.module_path = importer.archive - self._setup_prefix() - - -_declare_state('dict', _distribution_finders={}) - - -def register_finder(importer_type, distribution_finder): - """Register `distribution_finder` to find distributions in sys.path items - - `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item - handler), and `distribution_finder` is a callable that, passed a path - item and the importer instance, yields ``Distribution`` instances found on - that path item. See ``pkg_resources.find_on_path`` for an example.""" - _distribution_finders[importer_type] = distribution_finder - - -def find_distributions(path_item, only=False): - """Yield distributions accessible via `path_item`""" - importer = get_importer(path_item) - finder = _find_adapter(_distribution_finders, importer) - return finder(importer, path_item, only) - - -def find_eggs_in_zip(importer, path_item, only=False): - """ - Find eggs in zip files; possibly multiple nested eggs. - """ - if importer.archive.endswith('.whl'): - # wheels are not supported with this finder - # they don't have PKG-INFO metadata, and won't ever contain eggs - return - metadata = EggMetadata(importer) - if metadata.has_metadata('PKG-INFO'): - yield Distribution.from_filename(path_item, metadata=metadata) - if only: - # don't yield nested distros - return - for subitem in metadata.resource_listdir(''): - if _is_egg_path(subitem): - subpath = os.path.join(path_item, subitem) - dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath) - for dist in dists: - yield dist - elif subitem.lower().endswith(('.dist-info', '.egg-info')): - subpath = os.path.join(path_item, subitem) - submeta = EggMetadata(zipimport.zipimporter(subpath)) - submeta.egg_info = subpath - yield Distribution.from_location(path_item, subitem, submeta) - - -register_finder(zipimport.zipimporter, find_eggs_in_zip) - - -def find_nothing(importer, path_item, only=False): - return () - - -register_finder(object, find_nothing) - - -def find_on_path(importer, path_item, only=False): - """Yield distributions accessible on a sys.path directory""" - path_item = _normalize_cached(path_item) - - if _is_unpacked_egg(path_item): - yield Distribution.from_filename( - path_item, - metadata=PathMetadata(path_item, os.path.join(path_item, 'EGG-INFO')), - ) - return - - entries = (os.path.join(path_item, child) for child in safe_listdir(path_item)) - - # scan for .egg and .egg-info in directory - for entry in sorted(entries): - fullpath = os.path.join(path_item, entry) - factory = dist_factory(path_item, entry, only) - for dist in factory(fullpath): - yield dist - - -def dist_factory(path_item, entry, only): - """Return a dist_factory for the given entry.""" - lower = entry.lower() - is_egg_info = lower.endswith('.egg-info') - is_dist_info = lower.endswith('.dist-info') and os.path.isdir( - os.path.join(path_item, entry) - ) - is_meta = is_egg_info or is_dist_info - return ( - distributions_from_metadata - if is_meta - else find_distributions - if not only and _is_egg_path(entry) - else resolve_egg_link - if not only and lower.endswith('.egg-link') - else NoDists() - ) - - -class NoDists: - """ - >>> bool(NoDists()) - False - - >>> list(NoDists()('anything')) - [] - """ - - def __bool__(self): - return False - - def __call__(self, fullpath): - return iter(()) - - -def safe_listdir(path): - """ - Attempt to list contents of path, but suppress some exceptions. - """ - try: - return os.listdir(path) - except (PermissionError, NotADirectoryError): - pass - except OSError as e: - # Ignore the directory if does not exist, not a directory or - # permission denied - if e.errno not in (errno.ENOTDIR, errno.EACCES, errno.ENOENT): - raise - return () - - -def distributions_from_metadata(path): - root = os.path.dirname(path) - if os.path.isdir(path): - if len(os.listdir(path)) == 0: - # empty metadata dir; skip - return - metadata = PathMetadata(root, path) - else: - metadata = FileMetadata(path) - entry = os.path.basename(path) - yield Distribution.from_location( - root, - entry, - metadata, - precedence=DEVELOP_DIST, - ) - - -def non_empty_lines(path): - """ - Yield non-empty lines from file at path - """ - with open(path) as f: - for line in f: - line = line.strip() - if line: - yield line - - -def resolve_egg_link(path): - """ - Given a path to an .egg-link, resolve distributions - present in the referenced path. - """ - referenced_paths = non_empty_lines(path) - resolved_paths = ( - os.path.join(os.path.dirname(path), ref) for ref in referenced_paths - ) - dist_groups = map(find_distributions, resolved_paths) - return next(dist_groups, ()) - - -if hasattr(pkgutil, 'ImpImporter'): - register_finder(pkgutil.ImpImporter, find_on_path) - -register_finder(importlib_machinery.FileFinder, find_on_path) - -_declare_state('dict', _namespace_handlers={}) -_declare_state('dict', _namespace_packages={}) - - -def register_namespace_handler(importer_type, namespace_handler): - """Register `namespace_handler` to declare namespace packages - - `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item - handler), and `namespace_handler` is a callable like this:: - - def namespace_handler(importer, path_entry, moduleName, module): - # return a path_entry to use for child packages - - Namespace handlers are only called if the importer object has already - agreed that it can handle the relevant path item, and they should only - return a subpath if the module __path__ does not already contain an - equivalent subpath. For an example namespace handler, see - ``pkg_resources.file_ns_handler``. - """ - _namespace_handlers[importer_type] = namespace_handler - - -def _handle_ns(packageName, path_item): - """Ensure that named package includes a subpath of path_item (if needed)""" - - importer = get_importer(path_item) - if importer is None: - return None - - # use find_spec (PEP 451) and fall-back to find_module (PEP 302) - try: - spec = importer.find_spec(packageName) - except AttributeError: - # capture warnings due to #1111 - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - loader = importer.find_module(packageName) - else: - loader = spec.loader if spec else None - - if loader is None: - return None - module = sys.modules.get(packageName) - if module is None: - module = sys.modules[packageName] = types.ModuleType(packageName) - module.__path__ = [] - _set_parent_ns(packageName) - elif not hasattr(module, '__path__'): - raise TypeError("Not a package:", packageName) - handler = _find_adapter(_namespace_handlers, importer) - subpath = handler(importer, path_item, packageName, module) - if subpath is not None: - path = module.__path__ - path.append(subpath) - importlib.import_module(packageName) - _rebuild_mod_path(path, packageName, module) - return subpath - - -def _rebuild_mod_path(orig_path, package_name, module): - """ - Rebuild module.__path__ ensuring that all entries are ordered - corresponding to their sys.path order - """ - sys_path = [_normalize_cached(p) for p in sys.path] - - def safe_sys_path_index(entry): - """ - Workaround for #520 and #513. - """ - try: - return sys_path.index(entry) - except ValueError: - return float('inf') - - def position_in_sys_path(path): - """ - Return the ordinal of the path based on its position in sys.path - """ - path_parts = path.split(os.sep) - module_parts = package_name.count('.') + 1 - parts = path_parts[:-module_parts] - return safe_sys_path_index(_normalize_cached(os.sep.join(parts))) - - new_path = sorted(orig_path, key=position_in_sys_path) - new_path = [_normalize_cached(p) for p in new_path] - - if isinstance(module.__path__, list): - module.__path__[:] = new_path - else: - module.__path__ = new_path - - -def declare_namespace(packageName): - """Declare that package 'packageName' is a namespace package""" - - msg = ( - f"Deprecated call to `pkg_resources.declare_namespace({packageName!r})`.\n" - "Implementing implicit namespace packages (as specified in PEP 420) " - "is preferred to `pkg_resources.declare_namespace`. " - "See https://setuptools.pypa.io/en/latest/references/" - "keywords.html#keyword-namespace-packages" - ) - warnings.warn(msg, DeprecationWarning, stacklevel=2) - - _imp.acquire_lock() - try: - if packageName in _namespace_packages: - return - - path = sys.path - parent, _, _ = packageName.rpartition('.') - - if parent: - declare_namespace(parent) - if parent not in _namespace_packages: - __import__(parent) - try: - path = sys.modules[parent].__path__ - except AttributeError as e: - raise TypeError("Not a package:", parent) from e - - # Track what packages are namespaces, so when new path items are added, - # they can be updated - _namespace_packages.setdefault(parent or None, []).append(packageName) - _namespace_packages.setdefault(packageName, []) - - for path_item in path: - # Ensure all the parent's path items are reflected in the child, - # if they apply - _handle_ns(packageName, path_item) - - finally: - _imp.release_lock() - - -def fixup_namespace_packages(path_item, parent=None): - """Ensure that previously-declared namespace packages include path_item""" - _imp.acquire_lock() - try: - for package in _namespace_packages.get(parent, ()): - subpath = _handle_ns(package, path_item) - if subpath: - fixup_namespace_packages(subpath, package) - finally: - _imp.release_lock() - - -def file_ns_handler(importer, path_item, packageName, module): - """Compute an ns-package subpath for a filesystem or zipfile importer""" - - subpath = os.path.join(path_item, packageName.split('.')[-1]) - normalized = _normalize_cached(subpath) - for item in module.__path__: - if _normalize_cached(item) == normalized: - break - else: - # Only return the path if it's not already there - return subpath - - -if hasattr(pkgutil, 'ImpImporter'): - register_namespace_handler(pkgutil.ImpImporter, file_ns_handler) - -register_namespace_handler(zipimport.zipimporter, file_ns_handler) -register_namespace_handler(importlib_machinery.FileFinder, file_ns_handler) - - -def null_ns_handler(importer, path_item, packageName, module): - return None - - -register_namespace_handler(object, null_ns_handler) - - -def normalize_path(filename): - """Normalize a file/dir name for comparison purposes""" - return os.path.normcase(os.path.realpath(os.path.normpath(_cygwin_patch(filename)))) - - -def _cygwin_patch(filename): # pragma: nocover - """ - Contrary to POSIX 2008, on Cygwin, getcwd (3) contains - symlink components. Using - os.path.abspath() works around this limitation. A fix in os.getcwd() - would probably better, in Cygwin even more so, except - that this seems to be by design... - """ - return os.path.abspath(filename) if sys.platform == 'cygwin' else filename - - -def _normalize_cached(filename, _cache={}): - try: - return _cache[filename] - except KeyError: - _cache[filename] = result = normalize_path(filename) - return result - - -def _is_egg_path(path): - """ - Determine if given path appears to be an egg. - """ - return _is_zip_egg(path) or _is_unpacked_egg(path) - - -def _is_zip_egg(path): - return ( - path.lower().endswith('.egg') - and os.path.isfile(path) - and zipfile.is_zipfile(path) - ) - - -def _is_unpacked_egg(path): - """ - Determine if given path appears to be an unpacked egg. - """ - return path.lower().endswith('.egg') and os.path.isfile( - os.path.join(path, 'EGG-INFO', 'PKG-INFO') - ) - - -def _set_parent_ns(packageName): - parts = packageName.split('.') - name = parts.pop() - if parts: - parent = '.'.join(parts) - setattr(sys.modules[parent], name, sys.modules[packageName]) - - -MODULE = re.compile(r"\w+(\.\w+)*$").match -EGG_NAME = re.compile( - r""" - (?P[^-]+) ( - -(?P[^-]+) ( - -py(?P[^-]+) ( - -(?P.+) - )? - )? - )? - """, - re.VERBOSE | re.IGNORECASE, -).match - - -class EntryPoint: - """Object representing an advertised importable object""" - - def __init__(self, name, module_name, attrs=(), extras=(), dist=None): - if not MODULE(module_name): - raise ValueError("Invalid module name", module_name) - self.name = name - self.module_name = module_name - self.attrs = tuple(attrs) - self.extras = tuple(extras) - self.dist = dist - - def __str__(self): - s = "%s = %s" % (self.name, self.module_name) - if self.attrs: - s += ':' + '.'.join(self.attrs) - if self.extras: - s += ' [%s]' % ','.join(self.extras) - return s - - def __repr__(self): - return "EntryPoint.parse(%r)" % str(self) - - def load(self, require=True, *args, **kwargs): - """ - Require packages for this EntryPoint, then resolve it. - """ - if not require or args or kwargs: - warnings.warn( - "Parameters to load are deprecated. Call .resolve and " - ".require separately.", - PkgResourcesDeprecationWarning, - stacklevel=2, - ) - if require: - self.require(*args, **kwargs) - return self.resolve() - - def resolve(self): - """ - Resolve the entry point from its module and attrs. - """ - module = __import__(self.module_name, fromlist=['__name__'], level=0) - try: - return functools.reduce(getattr, self.attrs, module) - except AttributeError as exc: - raise ImportError(str(exc)) from exc - - def require(self, env=None, installer=None): - if self.extras and not self.dist: - raise UnknownExtra("Can't require() without a distribution", self) - - # Get the requirements for this entry point with all its extras and - # then resolve them. We have to pass `extras` along when resolving so - # that the working set knows what extras we want. Otherwise, for - # dist-info distributions, the working set will assume that the - # requirements for that extra are purely optional and skip over them. - reqs = self.dist.requires(self.extras) - items = working_set.resolve(reqs, env, installer, extras=self.extras) - list(map(working_set.add, items)) - - pattern = re.compile( - r'\s*' - r'(?P.+?)\s*' - r'=\s*' - r'(?P[\w.]+)\s*' - r'(:\s*(?P[\w.]+))?\s*' - r'(?P\[.*\])?\s*$' - ) - - @classmethod - def parse(cls, src, dist=None): - """Parse a single entry point from string `src` - - Entry point syntax follows the form:: - - name = some.module:some.attr [extra1, extra2] - - The entry name and module name are required, but the ``:attrs`` and - ``[extras]`` parts are optional - """ - m = cls.pattern.match(src) - if not m: - msg = "EntryPoint must be in 'name=module:attrs [extras]' format" - raise ValueError(msg, src) - res = m.groupdict() - extras = cls._parse_extras(res['extras']) - attrs = res['attr'].split('.') if res['attr'] else () - return cls(res['name'], res['module'], attrs, extras, dist) - - @classmethod - def _parse_extras(cls, extras_spec): - if not extras_spec: - return () - req = Requirement.parse('x' + extras_spec) - if req.specs: - raise ValueError() - return req.extras - - @classmethod - def parse_group(cls, group, lines, dist=None): - """Parse an entry point group""" - if not MODULE(group): - raise ValueError("Invalid group name", group) - this = {} - for line in yield_lines(lines): - ep = cls.parse(line, dist) - if ep.name in this: - raise ValueError("Duplicate entry point", group, ep.name) - this[ep.name] = ep - return this - - @classmethod - def parse_map(cls, data, dist=None): - """Parse a map of entry point groups""" - if isinstance(data, dict): - data = data.items() - else: - data = split_sections(data) - maps = {} - for group, lines in data: - if group is None: - if not lines: - continue - raise ValueError("Entry points must be listed in groups") - group = group.strip() - if group in maps: - raise ValueError("Duplicate group name", group) - maps[group] = cls.parse_group(group, lines, dist) - return maps - - -def _version_from_file(lines): - """ - Given an iterable of lines from a Metadata file, return - the value of the Version field, if present, or None otherwise. - """ - - def is_version_line(line): - return line.lower().startswith('version:') - - version_lines = filter(is_version_line, lines) - line = next(iter(version_lines), '') - _, _, value = line.partition(':') - return safe_version(value.strip()) or None - - -class Distribution: - """Wrap an actual or potential sys.path entry w/metadata""" - - PKG_INFO = 'PKG-INFO' - - def __init__( - self, - location=None, - metadata=None, - project_name=None, - version=None, - py_version=PY_MAJOR, - platform=None, - precedence=EGG_DIST, - ): - self.project_name = safe_name(project_name or 'Unknown') - if version is not None: - self._version = safe_version(version) - self.py_version = py_version - self.platform = platform - self.location = location - self.precedence = precedence - self._provider = metadata or empty_provider - - @classmethod - def from_location(cls, location, basename, metadata=None, **kw): - project_name, version, py_version, platform = [None] * 4 - basename, ext = os.path.splitext(basename) - if ext.lower() in _distributionImpl: - cls = _distributionImpl[ext.lower()] - - match = EGG_NAME(basename) - if match: - project_name, version, py_version, platform = match.group( - 'name', 'ver', 'pyver', 'plat' - ) - return cls( - location, - metadata, - project_name=project_name, - version=version, - py_version=py_version, - platform=platform, - **kw, - )._reload_version() - - def _reload_version(self): - return self - - @property - def hashcmp(self): - return ( - self._forgiving_parsed_version, - self.precedence, - self.key, - self.location, - self.py_version or '', - self.platform or '', - ) - - def __hash__(self): - return hash(self.hashcmp) - - def __lt__(self, other): - return self.hashcmp < other.hashcmp - - def __le__(self, other): - return self.hashcmp <= other.hashcmp - - def __gt__(self, other): - return self.hashcmp > other.hashcmp - - def __ge__(self, other): - return self.hashcmp >= other.hashcmp - - def __eq__(self, other): - if not isinstance(other, self.__class__): - # It's not a Distribution, so they are not equal - return False - return self.hashcmp == other.hashcmp - - def __ne__(self, other): - return not self == other - - # These properties have to be lazy so that we don't have to load any - # metadata until/unless it's actually needed. (i.e., some distributions - # may not know their name or version without loading PKG-INFO) - - @property - def key(self): - try: - return self._key - except AttributeError: - self._key = key = self.project_name.lower() - return key - - @property - def parsed_version(self): - if not hasattr(self, "_parsed_version"): - try: - self._parsed_version = parse_version(self.version) - except packaging.version.InvalidVersion as ex: - info = f"(package: {self.project_name})" - if hasattr(ex, "add_note"): - ex.add_note(info) # PEP 678 - raise - raise packaging.version.InvalidVersion(f"{str(ex)} {info}") from None - - return self._parsed_version - - @property - def _forgiving_parsed_version(self): - try: - return self.parsed_version - except packaging.version.InvalidVersion as ex: - self._parsed_version = parse_version(_forgiving_version(self.version)) - - notes = "\n".join(getattr(ex, "__notes__", [])) # PEP 678 - msg = f"""!!\n\n - ************************************************************************* - {str(ex)}\n{notes} - - This is a long overdue deprecation. - For the time being, `pkg_resources` will use `{self._parsed_version}` - as a replacement to avoid breaking existing environments, - but no future compatibility is guaranteed. - - If you maintain package {self.project_name} you should implement - the relevant changes to adequate the project to PEP 440 immediately. - ************************************************************************* - \n\n!! - """ - warnings.warn(msg, DeprecationWarning) - - return self._parsed_version - - @property - def version(self): - try: - return self._version - except AttributeError as e: - version = self._get_version() - if version is None: - path = self._get_metadata_path_for_display(self.PKG_INFO) - msg = ("Missing 'Version:' header and/or {} file at path: {}").format( - self.PKG_INFO, path - ) - raise ValueError(msg, self) from e - - return version - - @property - def _dep_map(self): - """ - A map of extra to its list of (direct) requirements - for this distribution, including the null extra. - """ - try: - return self.__dep_map - except AttributeError: - self.__dep_map = self._filter_extras(self._build_dep_map()) - return self.__dep_map - - @staticmethod - def _filter_extras(dm): - """ - Given a mapping of extras to dependencies, strip off - environment markers and filter out any dependencies - not matching the markers. - """ - for extra in list(filter(None, dm)): - new_extra = extra - reqs = dm.pop(extra) - new_extra, _, marker = extra.partition(':') - fails_marker = marker and ( - invalid_marker(marker) or not evaluate_marker(marker) - ) - if fails_marker: - reqs = [] - new_extra = safe_extra(new_extra) or None - - dm.setdefault(new_extra, []).extend(reqs) - return dm - - def _build_dep_map(self): - dm = {} - for name in 'requires.txt', 'depends.txt': - for extra, reqs in split_sections(self._get_metadata(name)): - dm.setdefault(extra, []).extend(parse_requirements(reqs)) - return dm - - def requires(self, extras=()): - """List of Requirements needed for this distro if `extras` are used""" - dm = self._dep_map - deps = [] - deps.extend(dm.get(None, ())) - for ext in extras: - try: - deps.extend(dm[safe_extra(ext)]) - except KeyError as e: - raise UnknownExtra( - "%s has no such extra feature %r" % (self, ext) - ) from e - return deps - - def _get_metadata_path_for_display(self, name): - """ - Return the path to the given metadata file, if available. - """ - try: - # We need to access _get_metadata_path() on the provider object - # directly rather than through this class's __getattr__() - # since _get_metadata_path() is marked private. - path = self._provider._get_metadata_path(name) - - # Handle exceptions e.g. in case the distribution's metadata - # provider doesn't support _get_metadata_path(). - except Exception: - return '[could not detect]' - - return path - - def _get_metadata(self, name): - if self.has_metadata(name): - for line in self.get_metadata_lines(name): - yield line - - def _get_version(self): - lines = self._get_metadata(self.PKG_INFO) - version = _version_from_file(lines) - - return version - - def activate(self, path=None, replace=False): - """Ensure distribution is importable on `path` (default=sys.path)""" - if path is None: - path = sys.path - self.insert_on(path, replace=replace) - if path is sys.path: - fixup_namespace_packages(self.location) - for pkg in self._get_metadata('namespace_packages.txt'): - if pkg in sys.modules: - declare_namespace(pkg) - - def egg_name(self): - """Return what this distribution's standard .egg filename should be""" - filename = "%s-%s-py%s" % ( - to_filename(self.project_name), - to_filename(self.version), - self.py_version or PY_MAJOR, - ) - - if self.platform: - filename += '-' + self.platform - return filename - - def __repr__(self): - if self.location: - return "%s (%s)" % (self, self.location) - else: - return str(self) - - def __str__(self): - try: - version = getattr(self, 'version', None) - except ValueError: - version = None - version = version or "[unknown version]" - return "%s %s" % (self.project_name, version) - - def __getattr__(self, attr): - """Delegate all unrecognized public attributes to .metadata provider""" - if attr.startswith('_'): - raise AttributeError(attr) - return getattr(self._provider, attr) - - def __dir__(self): - return list( - set(super(Distribution, self).__dir__()) - | set(attr for attr in self._provider.__dir__() if not attr.startswith('_')) - ) - - @classmethod - def from_filename(cls, filename, metadata=None, **kw): - return cls.from_location( - _normalize_cached(filename), os.path.basename(filename), metadata, **kw - ) - - def as_requirement(self): - """Return a ``Requirement`` that matches this distribution exactly""" - if isinstance(self.parsed_version, packaging.version.Version): - spec = "%s==%s" % (self.project_name, self.parsed_version) - else: - spec = "%s===%s" % (self.project_name, self.parsed_version) - - return Requirement.parse(spec) - - def load_entry_point(self, group, name): - """Return the `name` entry point of `group` or raise ImportError""" - ep = self.get_entry_info(group, name) - if ep is None: - raise ImportError("Entry point %r not found" % ((group, name),)) - return ep.load() - - def get_entry_map(self, group=None): - """Return the entry point map for `group`, or the full entry map""" - try: - ep_map = self._ep_map - except AttributeError: - ep_map = self._ep_map = EntryPoint.parse_map( - self._get_metadata('entry_points.txt'), self - ) - if group is not None: - return ep_map.get(group, {}) - return ep_map - - def get_entry_info(self, group, name): - """Return the EntryPoint object for `group`+`name`, or ``None``""" - return self.get_entry_map(group).get(name) - - # FIXME: 'Distribution.insert_on' is too complex (13) - def insert_on(self, path, loc=None, replace=False): # noqa: C901 - """Ensure self.location is on path - - If replace=False (default): - - If location is already in path anywhere, do nothing. - - Else: - - If it's an egg and its parent directory is on path, - insert just ahead of the parent. - - Else: add to the end of path. - If replace=True: - - If location is already on path anywhere (not eggs) - or higher priority than its parent (eggs) - do nothing. - - Else: - - If it's an egg and its parent directory is on path, - insert just ahead of the parent, - removing any lower-priority entries. - - Else: add it to the front of path. - """ - - loc = loc or self.location - if not loc: - return - - nloc = _normalize_cached(loc) - bdir = os.path.dirname(nloc) - npath = [(p and _normalize_cached(p) or p) for p in path] - - for p, item in enumerate(npath): - if item == nloc: - if replace: - break - else: - # don't modify path (even removing duplicates) if - # found and not replace - return - elif item == bdir and self.precedence == EGG_DIST: - # if it's an .egg, give it precedence over its directory - # UNLESS it's already been added to sys.path and replace=False - if (not replace) and nloc in npath[p:]: - return - if path is sys.path: - self.check_version_conflict() - path.insert(p, loc) - npath.insert(p, nloc) - break - else: - if path is sys.path: - self.check_version_conflict() - if replace: - path.insert(0, loc) - else: - path.append(loc) - return - - # p is the spot where we found or inserted loc; now remove duplicates - while True: - try: - np = npath.index(nloc, p + 1) - except ValueError: - break - else: - del npath[np], path[np] - # ha! - p = np - - return - - def check_version_conflict(self): - if self.key == 'setuptools': - # ignore the inevitable setuptools self-conflicts :( - return - - nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt')) - loc = normalize_path(self.location) - for modname in self._get_metadata('top_level.txt'): - if ( - modname not in sys.modules - or modname in nsp - or modname in _namespace_packages - ): - continue - if modname in ('pkg_resources', 'setuptools', 'site'): - continue - fn = getattr(sys.modules[modname], '__file__', None) - if fn and ( - normalize_path(fn).startswith(loc) or fn.startswith(self.location) - ): - continue - issue_warning( - "Module %s was already imported from %s, but %s is being added" - " to sys.path" % (modname, fn, self.location), - ) - - def has_version(self): - try: - self.version - except ValueError: - issue_warning("Unbuilt egg for " + repr(self)) - return False - except SystemError: - # TODO: remove this except clause when python/cpython#103632 is fixed. - return False - return True - - def clone(self, **kw): - """Copy this distribution, substituting in any changed keyword args""" - names = 'project_name version py_version platform location precedence' - for attr in names.split(): - kw.setdefault(attr, getattr(self, attr, None)) - kw.setdefault('metadata', self._provider) - return self.__class__(**kw) - - @property - def extras(self): - return [dep for dep in self._dep_map if dep] - - -class EggInfoDistribution(Distribution): - def _reload_version(self): - """ - Packages installed by distutils (e.g. numpy or scipy), - which uses an old safe_version, and so - their version numbers can get mangled when - converted to filenames (e.g., 1.11.0.dev0+2329eae to - 1.11.0.dev0_2329eae). These distributions will not be - parsed properly - downstream by Distribution and safe_version, so - take an extra step and try to get the version number from - the metadata file itself instead of the filename. - """ - md_version = self._get_version() - if md_version: - self._version = md_version - return self - - -class DistInfoDistribution(Distribution): - """ - Wrap an actual or potential sys.path entry - w/metadata, .dist-info style. - """ - - PKG_INFO = 'METADATA' - EQEQ = re.compile(r"([\(,])\s*(\d.*?)\s*([,\)])") - - @property - def _parsed_pkg_info(self): - """Parse and cache metadata""" - try: - return self._pkg_info - except AttributeError: - metadata = self.get_metadata(self.PKG_INFO) - self._pkg_info = email.parser.Parser().parsestr(metadata) - return self._pkg_info - - @property - def _dep_map(self): - try: - return self.__dep_map - except AttributeError: - self.__dep_map = self._compute_dependencies() - return self.__dep_map - - def _compute_dependencies(self): - """Recompute this distribution's dependencies.""" - dm = self.__dep_map = {None: []} - - reqs = [] - # Including any condition expressions - for req in self._parsed_pkg_info.get_all('Requires-Dist') or []: - reqs.extend(parse_requirements(req)) - - def reqs_for_extra(extra): - for req in reqs: - if not req.marker or req.marker.evaluate({'extra': extra}): - yield req - - common = types.MappingProxyType(dict.fromkeys(reqs_for_extra(None))) - dm[None].extend(common) - - for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []: - s_extra = safe_extra(extra.strip()) - dm[s_extra] = [r for r in reqs_for_extra(extra) if r not in common] - - return dm - - -_distributionImpl = { - '.egg': Distribution, - '.egg-info': EggInfoDistribution, - '.dist-info': DistInfoDistribution, -} - - -def issue_warning(*args, **kw): - level = 1 - g = globals() - try: - # find the first stack frame that is *not* code in - # the pkg_resources module, to use for the warning - while sys._getframe(level).f_globals is g: - level += 1 - except ValueError: - pass - warnings.warn(stacklevel=level + 1, *args, **kw) - - -def parse_requirements(strs): - """ - Yield ``Requirement`` objects for each specification in `strs`. - - `strs` must be a string, or a (possibly-nested) iterable thereof. - """ - return map(Requirement, join_continuation(map(drop_comment, yield_lines(strs)))) - - -class RequirementParseError(packaging.requirements.InvalidRequirement): - "Compatibility wrapper for InvalidRequirement" - - -class Requirement(packaging.requirements.Requirement): - def __init__(self, requirement_string): - """DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!""" - super(Requirement, self).__init__(requirement_string) - self.unsafe_name = self.name - project_name = safe_name(self.name) - self.project_name, self.key = project_name, project_name.lower() - self.specs = [(spec.operator, spec.version) for spec in self.specifier] - self.extras = tuple(map(safe_extra, self.extras)) - self.hashCmp = ( - self.key, - self.url, - self.specifier, - frozenset(self.extras), - str(self.marker) if self.marker else None, - ) - self.__hash = hash(self.hashCmp) - - def __eq__(self, other): - return isinstance(other, Requirement) and self.hashCmp == other.hashCmp - - def __ne__(self, other): - return not self == other - - def __contains__(self, item): - if isinstance(item, Distribution): - if item.key != self.key: - return False - - item = item.version - - # Allow prereleases always in order to match the previous behavior of - # this method. In the future this should be smarter and follow PEP 440 - # more accurately. - return self.specifier.contains(item, prereleases=True) - - def __hash__(self): - return self.__hash - - def __repr__(self): - return "Requirement.parse(%r)" % str(self) - - @staticmethod - def parse(s): - (req,) = parse_requirements(s) - return req - - -def _always_object(classes): - """ - Ensure object appears in the mro even - for old-style classes. - """ - if object not in classes: - return classes + (object,) - return classes - - -def _find_adapter(registry, ob): - """Return an adapter factory for `ob` from `registry`""" - types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob)))) - for t in types: - if t in registry: - return registry[t] - - -def ensure_directory(path): - """Ensure that the parent directory of `path` exists""" - dirname = os.path.dirname(path) - os.makedirs(dirname, exist_ok=True) - - -def _bypass_ensure_directory(path): - """Sandbox-bypassing version of ensure_directory()""" - if not WRITE_SUPPORT: - raise IOError('"os.mkdir" not supported on this platform.') - dirname, filename = split(path) - if dirname and filename and not isdir(dirname): - _bypass_ensure_directory(dirname) - try: - mkdir(dirname, 0o755) - except FileExistsError: - pass - - -def split_sections(s): - """Split a string or iterable thereof into (section, content) pairs - - Each ``section`` is a stripped version of the section header ("[section]") - and each ``content`` is a list of stripped lines excluding blank lines and - comment-only lines. If there are any such lines before the first section - header, they're returned in a first ``section`` of ``None``. - """ - section = None - content = [] - for line in yield_lines(s): - if line.startswith("["): - if line.endswith("]"): - if section or content: - yield section, content - section = line[1:-1].strip() - content = [] - else: - raise ValueError("Invalid section heading", line) - else: - content.append(line) - - # wrap up last segment - yield section, content - - -def _mkstemp(*args, **kw): - old_open = os.open - try: - # temporarily bypass sandboxing - os.open = os_open - return tempfile.mkstemp(*args, **kw) - finally: - # and then put it back - os.open = old_open - - -# Silence the PEP440Warning by default, so that end users don't get hit by it -# randomly just because they use pkg_resources. We want to append the rule -# because we want earlier uses of filterwarnings to take precedence over this -# one. -warnings.filterwarnings("ignore", category=PEP440Warning, append=True) - - -# from jaraco.functools 1.3 -def _call_aside(f, *args, **kwargs): - f(*args, **kwargs) - return f - - -@_call_aside -def _initialize(g=globals()): - "Set up global resource manager (deliberately not state-saved)" - manager = ResourceManager() - g['_manager'] = manager - g.update( - (name, getattr(manager, name)) - for name in dir(manager) - if not name.startswith('_') - ) - - -class PkgResourcesDeprecationWarning(Warning): - """ - Base class for warning about deprecations in ``pkg_resources`` - - This class is not derived from ``DeprecationWarning``, and as such is - visible by default. - """ - - -@_call_aside -def _initialize_master_working_set(): - """ - Prepare the master working set and make the ``require()`` - API available. - - This function has explicit effects on the global state - of pkg_resources. It is intended to be invoked once at - the initialization of this module. - - Invocation by other packages is unsupported and done - at their own risk. - """ - working_set = WorkingSet._build_master() - _declare_state('object', working_set=working_set) - - require = working_set.require - iter_entry_points = working_set.iter_entry_points - add_activation_listener = working_set.subscribe - run_script = working_set.run_script - # backward compatibility - run_main = run_script - # Activate all distributions already on sys.path with replace=False and - # ensure that all distributions added to the working set in the future - # (e.g. by calling ``require()``) will get activated as well, - # with higher priority (replace=True). - tuple(dist.activate(replace=False) for dist in working_set) - add_activation_listener( - lambda dist: dist.activate(replace=True), - existing=False, - ) - working_set.entries = [] - # match order - list(map(working_set.add_entry, sys.path)) - globals().update(locals()) diff --git a/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/INSTALLER b/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a..0000000000 --- a/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/LICENSE b/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/LICENSE deleted file mode 100644 index d645695673..0000000000 --- a/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/METADATA b/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/METADATA deleted file mode 100644 index a9995f09a3..0000000000 --- a/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/METADATA +++ /dev/null @@ -1,104 +0,0 @@ -Metadata-Version: 2.1 -Name: importlib-resources -Version: 5.10.2 -Summary: Read resources from Python packages -Home-page: https://github.com/python/importlib_resources -Author: Barry Warsaw -Author-email: barry@python.org -Project-URL: Documentation, https://importlib-resources.readthedocs.io/ -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: Apache Software License -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3 :: Only -Requires-Python: >=3.7 -License-File: LICENSE -Requires-Dist: zipp (>=3.1.0) ; python_version < "3.10" -Provides-Extra: docs -Requires-Dist: sphinx (>=3.5) ; extra == 'docs' -Requires-Dist: jaraco.packaging (>=9) ; extra == 'docs' -Requires-Dist: rst.linker (>=1.9) ; extra == 'docs' -Requires-Dist: furo ; extra == 'docs' -Requires-Dist: sphinx-lint ; extra == 'docs' -Requires-Dist: jaraco.tidelift (>=1.4) ; extra == 'docs' -Provides-Extra: testing -Requires-Dist: pytest (>=6) ; extra == 'testing' -Requires-Dist: pytest-checkdocs (>=2.4) ; extra == 'testing' -Requires-Dist: flake8 (<5) ; extra == 'testing' -Requires-Dist: pytest-cov ; extra == 'testing' -Requires-Dist: pytest-enabler (>=1.3) ; extra == 'testing' -Requires-Dist: pytest-black (>=0.3.7) ; (platform_python_implementation != "PyPy") and extra == 'testing' -Requires-Dist: pytest-mypy (>=0.9.1) ; (platform_python_implementation != "PyPy") and extra == 'testing' -Requires-Dist: pytest-flake8 ; (python_version < "3.12") and extra == 'testing' - -.. image:: https://img.shields.io/pypi/v/importlib_resources.svg - :target: https://pypi.org/project/importlib_resources - -.. image:: https://img.shields.io/pypi/pyversions/importlib_resources.svg - -.. image:: https://github.com/python/importlib_resources/workflows/tests/badge.svg - :target: https://github.com/python/importlib_resources/actions?query=workflow%3A%22tests%22 - :alt: tests - -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black - :alt: Code style: Black - -.. image:: https://readthedocs.org/projects/importlib-resources/badge/?version=latest - :target: https://importlib-resources.readthedocs.io/en/latest/?badge=latest - -.. image:: https://img.shields.io/badge/skeleton-2022-informational - :target: https://blog.jaraco.com/skeleton - -.. image:: https://tidelift.com/badges/package/pypi/importlib-resources - :target: https://tidelift.com/subscription/pkg/pypi-importlib-resources?utm_source=pypi-importlib-resources&utm_medium=readme - -``importlib_resources`` is a backport of Python standard library -`importlib.resources -`_ -module for older Pythons. - -The key goal of this module is to replace parts of `pkg_resources -`_ with a -solution in Python's stdlib that relies on well-defined APIs. This makes -reading resources included in packages easier, with more stable and consistent -semantics. - -Compatibility -============= - -New features are introduced in this third-party library and later merged -into CPython. The following table indicates which versions of this library -were contributed to different versions in the standard library: - -.. list-table:: - :header-rows: 1 - - * - importlib_resources - - stdlib - * - 5.9 - - 3.12 - * - 5.7 - - 3.11 - * - 5.0 - - 3.10 - * - 1.3 - - 3.9 - * - 0.5 (?) - - 3.7 - -For Enterprise -============== - -Available as part of the Tidelift Subscription. - -This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. - -`Learn more `_. - -Security Contact -================ - -To report a security vulnerability, please use the -`Tidelift security contact `_. -Tidelift will coordinate the fix and disclosure. diff --git a/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/RECORD b/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/RECORD deleted file mode 100644 index 7d19852d4a..0000000000 --- a/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/RECORD +++ /dev/null @@ -1,77 +0,0 @@ -importlib_resources-5.10.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -importlib_resources-5.10.2.dist-info/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 -importlib_resources-5.10.2.dist-info/METADATA,sha256=Xo5ntATvDYUxdmW8tr8kxtfdiOC9889mOk-LE1LtZfI,4111 -importlib_resources-5.10.2.dist-info/RECORD,, -importlib_resources-5.10.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -importlib_resources-5.10.2.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92 -importlib_resources-5.10.2.dist-info/top_level.txt,sha256=fHIjHU1GZwAjvcydpmUnUrTnbvdiWjG4OEVZK8by0TQ,20 -importlib_resources/__init__.py,sha256=evPm12kLgYqTm-pbzm60bOuumumT8IpBNWFp0uMyrzE,506 -importlib_resources/__pycache__/__init__.cpython-311.pyc,, -importlib_resources/__pycache__/_adapters.cpython-311.pyc,, -importlib_resources/__pycache__/_common.cpython-311.pyc,, -importlib_resources/__pycache__/_compat.cpython-311.pyc,, -importlib_resources/__pycache__/_itertools.cpython-311.pyc,, -importlib_resources/__pycache__/_legacy.cpython-311.pyc,, -importlib_resources/__pycache__/abc.cpython-311.pyc,, -importlib_resources/__pycache__/readers.cpython-311.pyc,, -importlib_resources/__pycache__/simple.cpython-311.pyc,, -importlib_resources/_adapters.py,sha256=o51tP2hpVtohP33gSYyAkGNpLfYDBqxxYsadyiRZi1E,4504 -importlib_resources/_common.py,sha256=jSC4xfLdcMNbtbWHtpzbFkNa0W7kvf__nsYn14C_AEU,5457 -importlib_resources/_compat.py,sha256=dSadF6WPt8MwOqSm_NIOQPhw4x0iaMYTWxi-XS93p7M,2923 -importlib_resources/_itertools.py,sha256=WCdJ1Gs_kNFwKENyIG7TO0Y434IWCu0zjVVSsSbZwU8,884 -importlib_resources/_legacy.py,sha256=0TKdZixxLWA-xwtAZw4HcpqJmj4Xprx1Zkcty0gTRZY,3481 -importlib_resources/abc.py,sha256=Icr2IJ2QtH7vvAB9vC5WRJ9KBoaDyJa7KUs8McuROzo,5140 -importlib_resources/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -importlib_resources/readers.py,sha256=PZsi5qacr2Qn3KHw4qw3Gm1MzrBblPHoTdjqjH7EKWw,3581 -importlib_resources/simple.py,sha256=0__2TQBTQoqkajYmNPt1HxERcReAT6boVKJA328pr04,2576 -importlib_resources/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -importlib_resources/tests/__pycache__/__init__.cpython-311.pyc,, -importlib_resources/tests/__pycache__/_compat.cpython-311.pyc,, -importlib_resources/tests/__pycache__/_path.cpython-311.pyc,, -importlib_resources/tests/__pycache__/test_compatibilty_files.cpython-311.pyc,, -importlib_resources/tests/__pycache__/test_contents.cpython-311.pyc,, -importlib_resources/tests/__pycache__/test_files.cpython-311.pyc,, -importlib_resources/tests/__pycache__/test_open.cpython-311.pyc,, -importlib_resources/tests/__pycache__/test_path.cpython-311.pyc,, -importlib_resources/tests/__pycache__/test_read.cpython-311.pyc,, -importlib_resources/tests/__pycache__/test_reader.cpython-311.pyc,, -importlib_resources/tests/__pycache__/test_resource.cpython-311.pyc,, -importlib_resources/tests/__pycache__/update-zips.cpython-311.pyc,, -importlib_resources/tests/__pycache__/util.cpython-311.pyc,, -importlib_resources/tests/_compat.py,sha256=YTSB0U1R9oADnh6GrQcOCgojxcF_N6H1LklymEWf9SQ,708 -importlib_resources/tests/_path.py,sha256=yZyWsQzJZQ1Z8ARAxWkjAdaVVsjlzyqxO0qjBUofJ8M,1039 -importlib_resources/tests/data01/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -importlib_resources/tests/data01/__pycache__/__init__.cpython-311.pyc,, -importlib_resources/tests/data01/binary.file,sha256=BU7ewdAhH2JP7Qy8qdT5QAsOSRxDdCryxbCr6_DJkNg,4 -importlib_resources/tests/data01/subdirectory/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -importlib_resources/tests/data01/subdirectory/__pycache__/__init__.cpython-311.pyc,, -importlib_resources/tests/data01/subdirectory/binary.file,sha256=BU7ewdAhH2JP7Qy8qdT5QAsOSRxDdCryxbCr6_DJkNg,4 -importlib_resources/tests/data01/utf-16.file,sha256=t5q9qhxX0rYqItBOM8D3ylwG-RHrnOYteTLtQr6sF7g,44 -importlib_resources/tests/data01/utf-8.file,sha256=kwWgYG4yQ-ZF2X_WA66EjYPmxJRn-w8aSOiS9e8tKYY,20 -importlib_resources/tests/data02/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -importlib_resources/tests/data02/__pycache__/__init__.cpython-311.pyc,, -importlib_resources/tests/data02/one/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -importlib_resources/tests/data02/one/__pycache__/__init__.cpython-311.pyc,, -importlib_resources/tests/data02/one/resource1.txt,sha256=10flKac7c-XXFzJ3t-AB5MJjlBy__dSZvPE_dOm2q6U,13 -importlib_resources/tests/data02/two/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -importlib_resources/tests/data02/two/__pycache__/__init__.cpython-311.pyc,, -importlib_resources/tests/data02/two/resource2.txt,sha256=lt2jbN3TMn9QiFKM832X39bU_62UptDdUkoYzkvEbl0,13 -importlib_resources/tests/namespacedata01/binary.file,sha256=BU7ewdAhH2JP7Qy8qdT5QAsOSRxDdCryxbCr6_DJkNg,4 -importlib_resources/tests/namespacedata01/utf-16.file,sha256=t5q9qhxX0rYqItBOM8D3ylwG-RHrnOYteTLtQr6sF7g,44 -importlib_resources/tests/namespacedata01/utf-8.file,sha256=kwWgYG4yQ-ZF2X_WA66EjYPmxJRn-w8aSOiS9e8tKYY,20 -importlib_resources/tests/test_compatibilty_files.py,sha256=NWkbIsylI8Wz3Dwsxo1quT4ZI6ToXFA2mojCG6Dzuxw,3260 -importlib_resources/tests/test_contents.py,sha256=V1Xfk3lqTDdvUsZuV18Kndf0CT_tkM2oEIwk9Vv0rhg,968 -importlib_resources/tests/test_files.py,sha256=1Y8da-g0xOQLzuREDYUiRc_qhWlvFNeydW_mUH7l15w,3251 -importlib_resources/tests/test_open.py,sha256=pmEgdrSFdM83L6FxtR8U_RT9BfI3JZ4snGmM_ZZIegY,2565 -importlib_resources/tests/test_path.py,sha256=xvPteNA-UKavDhKgLgrQuXSxKWYH7Q4nSNDVfBX95Gs,2103 -importlib_resources/tests/test_read.py,sha256=EyYvpHJ_7F4LuX2EU_c5EerIBQfRhOFmiIR7LOc5Y5E,2408 -importlib_resources/tests/test_reader.py,sha256=nPhldbYPq3fXoQs0ZAub4atjhp2lgNyLNv2G1pg6Agw,4480 -importlib_resources/tests/test_resource.py,sha256=EMoarxTEHcrq8R41LQDsndIG8Idtm4I_LpN8DYpHtT0,8478 -importlib_resources/tests/update-zips.py,sha256=x-SrO5v87iLLUMXyefxDwAd3imAs_slI94sLWvJ6N40,1417 -importlib_resources/tests/util.py,sha256=ARAlxZ47wC-lgR7PGlmgBoi4HnhzcykD5Is2-TAwY0I,4873 -importlib_resources/tests/zipdata01/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -importlib_resources/tests/zipdata01/__pycache__/__init__.cpython-311.pyc,, -importlib_resources/tests/zipdata01/ziptestdata.zip,sha256=z5Of4dsv3T0t-46B0MsVhxlhsPGMz28aUhJDWpj3_oY,876 -importlib_resources/tests/zipdata02/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -importlib_resources/tests/zipdata02/__pycache__/__init__.cpython-311.pyc,, -importlib_resources/tests/zipdata02/ziptestdata.zip,sha256=ydI-_j-xgQ7tDxqBp9cjOqXBGxUp6ZBbwVJu6Xj-nrY,698 diff --git a/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/top_level.txt b/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/top_level.txt deleted file mode 100644 index 58ad1bd333..0000000000 --- a/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -importlib_resources diff --git a/pkg_resources/_vendor/importlib_resources/__init__.py b/pkg_resources/_vendor/importlib_resources/__init__.py deleted file mode 100644 index 34e3a9950c..0000000000 --- a/pkg_resources/_vendor/importlib_resources/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Read resources contained within a package.""" - -from ._common import ( - as_file, - files, - Package, -) - -from ._legacy import ( - contents, - open_binary, - read_binary, - open_text, - read_text, - is_resource, - path, - Resource, -) - -from .abc import ResourceReader - - -__all__ = [ - 'Package', - 'Resource', - 'ResourceReader', - 'as_file', - 'contents', - 'files', - 'is_resource', - 'open_binary', - 'open_text', - 'path', - 'read_binary', - 'read_text', -] diff --git a/pkg_resources/_vendor/importlib_resources/_adapters.py b/pkg_resources/_vendor/importlib_resources/_adapters.py deleted file mode 100644 index ea363d86a5..0000000000 --- a/pkg_resources/_vendor/importlib_resources/_adapters.py +++ /dev/null @@ -1,170 +0,0 @@ -from contextlib import suppress -from io import TextIOWrapper - -from . import abc - - -class SpecLoaderAdapter: - """ - Adapt a package spec to adapt the underlying loader. - """ - - def __init__(self, spec, adapter=lambda spec: spec.loader): - self.spec = spec - self.loader = adapter(spec) - - def __getattr__(self, name): - return getattr(self.spec, name) - - -class TraversableResourcesLoader: - """ - Adapt a loader to provide TraversableResources. - """ - - def __init__(self, spec): - self.spec = spec - - def get_resource_reader(self, name): - return CompatibilityFiles(self.spec)._native() - - -def _io_wrapper(file, mode='r', *args, **kwargs): - if mode == 'r': - return TextIOWrapper(file, *args, **kwargs) - elif mode == 'rb': - return file - raise ValueError( - "Invalid mode value '{}', only 'r' and 'rb' are supported".format(mode) - ) - - -class CompatibilityFiles: - """ - Adapter for an existing or non-existent resource reader - to provide a compatibility .files(). - """ - - class SpecPath(abc.Traversable): - """ - Path tied to a module spec. - Can be read and exposes the resource reader children. - """ - - def __init__(self, spec, reader): - self._spec = spec - self._reader = reader - - def iterdir(self): - if not self._reader: - return iter(()) - return iter( - CompatibilityFiles.ChildPath(self._reader, path) - for path in self._reader.contents() - ) - - def is_file(self): - return False - - is_dir = is_file - - def joinpath(self, other): - if not self._reader: - return CompatibilityFiles.OrphanPath(other) - return CompatibilityFiles.ChildPath(self._reader, other) - - @property - def name(self): - return self._spec.name - - def open(self, mode='r', *args, **kwargs): - return _io_wrapper(self._reader.open_resource(None), mode, *args, **kwargs) - - class ChildPath(abc.Traversable): - """ - Path tied to a resource reader child. - Can be read but doesn't expose any meaningful children. - """ - - def __init__(self, reader, name): - self._reader = reader - self._name = name - - def iterdir(self): - return iter(()) - - def is_file(self): - return self._reader.is_resource(self.name) - - def is_dir(self): - return not self.is_file() - - def joinpath(self, other): - return CompatibilityFiles.OrphanPath(self.name, other) - - @property - def name(self): - return self._name - - def open(self, mode='r', *args, **kwargs): - return _io_wrapper( - self._reader.open_resource(self.name), mode, *args, **kwargs - ) - - class OrphanPath(abc.Traversable): - """ - Orphan path, not tied to a module spec or resource reader. - Can't be read and doesn't expose any meaningful children. - """ - - def __init__(self, *path_parts): - if len(path_parts) < 1: - raise ValueError('Need at least one path part to construct a path') - self._path = path_parts - - def iterdir(self): - return iter(()) - - def is_file(self): - return False - - is_dir = is_file - - def joinpath(self, other): - return CompatibilityFiles.OrphanPath(*self._path, other) - - @property - def name(self): - return self._path[-1] - - def open(self, mode='r', *args, **kwargs): - raise FileNotFoundError("Can't open orphan path") - - def __init__(self, spec): - self.spec = spec - - @property - def _reader(self): - with suppress(AttributeError): - return self.spec.loader.get_resource_reader(self.spec.name) - - def _native(self): - """ - Return the native reader if it supports files(). - """ - reader = self._reader - return reader if hasattr(reader, 'files') else self - - def __getattr__(self, attr): - return getattr(self._reader, attr) - - def files(self): - return CompatibilityFiles.SpecPath(self.spec, self._reader) - - -def wrap_spec(package): - """ - Construct a package spec with traversable compatibility - on the spec/loader/reader. - """ - return SpecLoaderAdapter(package.__spec__, TraversableResourcesLoader) diff --git a/pkg_resources/_vendor/importlib_resources/_common.py b/pkg_resources/_vendor/importlib_resources/_common.py deleted file mode 100644 index 3c6de1cfb2..0000000000 --- a/pkg_resources/_vendor/importlib_resources/_common.py +++ /dev/null @@ -1,207 +0,0 @@ -import os -import pathlib -import tempfile -import functools -import contextlib -import types -import importlib -import inspect -import warnings -import itertools - -from typing import Union, Optional, cast -from .abc import ResourceReader, Traversable - -from ._compat import wrap_spec - -Package = Union[types.ModuleType, str] -Anchor = Package - - -def package_to_anchor(func): - """ - Replace 'package' parameter as 'anchor' and warn about the change. - - Other errors should fall through. - - >>> files('a', 'b') - Traceback (most recent call last): - TypeError: files() takes from 0 to 1 positional arguments but 2 were given - """ - undefined = object() - - @functools.wraps(func) - def wrapper(anchor=undefined, package=undefined): - if package is not undefined: - if anchor is not undefined: - return func(anchor, package) - warnings.warn( - "First parameter to files is renamed to 'anchor'", - DeprecationWarning, - stacklevel=2, - ) - return func(package) - elif anchor is undefined: - return func() - return func(anchor) - - return wrapper - - -@package_to_anchor -def files(anchor: Optional[Anchor] = None) -> Traversable: - """ - Get a Traversable resource for an anchor. - """ - return from_package(resolve(anchor)) - - -def get_resource_reader(package: types.ModuleType) -> Optional[ResourceReader]: - """ - Return the package's loader if it's a ResourceReader. - """ - # We can't use - # a issubclass() check here because apparently abc.'s __subclasscheck__() - # hook wants to create a weak reference to the object, but - # zipimport.zipimporter does not support weak references, resulting in a - # TypeError. That seems terrible. - spec = package.__spec__ - reader = getattr(spec.loader, 'get_resource_reader', None) # type: ignore - if reader is None: - return None - return reader(spec.name) # type: ignore - - -@functools.singledispatch -def resolve(cand: Optional[Anchor]) -> types.ModuleType: - return cast(types.ModuleType, cand) - - -@resolve.register -def _(cand: str) -> types.ModuleType: - return importlib.import_module(cand) - - -@resolve.register -def _(cand: None) -> types.ModuleType: - return resolve(_infer_caller().f_globals['__name__']) - - -def _infer_caller(): - """ - Walk the stack and find the frame of the first caller not in this module. - """ - - def is_this_file(frame_info): - return frame_info.filename == __file__ - - def is_wrapper(frame_info): - return frame_info.function == 'wrapper' - - not_this_file = itertools.filterfalse(is_this_file, inspect.stack()) - # also exclude 'wrapper' due to singledispatch in the call stack - callers = itertools.filterfalse(is_wrapper, not_this_file) - return next(callers).frame - - -def from_package(package: types.ModuleType): - """ - Return a Traversable object for the given package. - - """ - spec = wrap_spec(package) - reader = spec.loader.get_resource_reader(spec.name) - return reader.files() - - -@contextlib.contextmanager -def _tempfile( - reader, - suffix='', - # gh-93353: Keep a reference to call os.remove() in late Python - # finalization. - *, - _os_remove=os.remove, -): - # Not using tempfile.NamedTemporaryFile as it leads to deeper 'try' - # blocks due to the need to close the temporary file to work on Windows - # properly. - fd, raw_path = tempfile.mkstemp(suffix=suffix) - try: - try: - os.write(fd, reader()) - finally: - os.close(fd) - del reader - yield pathlib.Path(raw_path) - finally: - try: - _os_remove(raw_path) - except FileNotFoundError: - pass - - -def _temp_file(path): - return _tempfile(path.read_bytes, suffix=path.name) - - -def _is_present_dir(path: Traversable) -> bool: - """ - Some Traversables implement ``is_dir()`` to raise an - exception (i.e. ``FileNotFoundError``) when the - directory doesn't exist. This function wraps that call - to always return a boolean and only return True - if there's a dir and it exists. - """ - with contextlib.suppress(FileNotFoundError): - return path.is_dir() - return False - - -@functools.singledispatch -def as_file(path): - """ - Given a Traversable object, return that object as a - path on the local file system in a context manager. - """ - return _temp_dir(path) if _is_present_dir(path) else _temp_file(path) - - -@as_file.register(pathlib.Path) -@contextlib.contextmanager -def _(path): - """ - Degenerate behavior for pathlib.Path objects. - """ - yield path - - -@contextlib.contextmanager -def _temp_path(dir: tempfile.TemporaryDirectory): - """ - Wrap tempfile.TemporyDirectory to return a pathlib object. - """ - with dir as result: - yield pathlib.Path(result) - - -@contextlib.contextmanager -def _temp_dir(path): - """ - Given a traversable dir, recursively replicate the whole tree - to the file system in a context manager. - """ - assert path.is_dir() - with _temp_path(tempfile.TemporaryDirectory()) as temp_dir: - yield _write_contents(temp_dir, path) - - -def _write_contents(target, source): - child = target.joinpath(source.name) - if source.is_dir(): - child.mkdir() - for item in source.iterdir(): - _write_contents(child, item) - else: - child.write_bytes(source.read_bytes()) - return child diff --git a/pkg_resources/_vendor/importlib_resources/_compat.py b/pkg_resources/_vendor/importlib_resources/_compat.py deleted file mode 100644 index 8b5b1d280f..0000000000 --- a/pkg_resources/_vendor/importlib_resources/_compat.py +++ /dev/null @@ -1,108 +0,0 @@ -# flake8: noqa - -import abc -import os -import sys -import pathlib -from contextlib import suppress -from typing import Union - - -if sys.version_info >= (3, 10): - from zipfile import Path as ZipPath # type: ignore -else: - from ..zipp import Path as ZipPath # type: ignore - - -try: - from typing import runtime_checkable # type: ignore -except ImportError: - - def runtime_checkable(cls): # type: ignore - return cls - - -try: - from typing import Protocol # type: ignore -except ImportError: - Protocol = abc.ABC # type: ignore - - -class TraversableResourcesLoader: - """ - Adapt loaders to provide TraversableResources and other - compatibility. - - Used primarily for Python 3.9 and earlier where the native - loaders do not yet implement TraversableResources. - """ - - def __init__(self, spec): - self.spec = spec - - @property - def path(self): - return self.spec.origin - - def get_resource_reader(self, name): - from . import readers, _adapters - - def _zip_reader(spec): - with suppress(AttributeError): - return readers.ZipReader(spec.loader, spec.name) - - def _namespace_reader(spec): - with suppress(AttributeError, ValueError): - return readers.NamespaceReader(spec.submodule_search_locations) - - def _available_reader(spec): - with suppress(AttributeError): - return spec.loader.get_resource_reader(spec.name) - - def _native_reader(spec): - reader = _available_reader(spec) - return reader if hasattr(reader, 'files') else None - - def _file_reader(spec): - try: - path = pathlib.Path(self.path) - except TypeError: - return None - if path.exists(): - return readers.FileReader(self) - - return ( - # native reader if it supplies 'files' - _native_reader(self.spec) - or - # local ZipReader if a zip module - _zip_reader(self.spec) - or - # local NamespaceReader if a namespace module - _namespace_reader(self.spec) - or - # local FileReader - _file_reader(self.spec) - # fallback - adapt the spec ResourceReader to TraversableReader - or _adapters.CompatibilityFiles(self.spec) - ) - - -def wrap_spec(package): - """ - Construct a package spec with traversable compatibility - on the spec/loader/reader. - - Supersedes _adapters.wrap_spec to use TraversableResourcesLoader - from above for older Python compatibility (<3.10). - """ - from . import _adapters - - return _adapters.SpecLoaderAdapter(package.__spec__, TraversableResourcesLoader) - - -if sys.version_info >= (3, 9): - StrPath = Union[str, os.PathLike[str]] -else: - # PathLike is only subscriptable at runtime in 3.9+ - StrPath = Union[str, "os.PathLike[str]"] diff --git a/pkg_resources/_vendor/importlib_resources/_itertools.py b/pkg_resources/_vendor/importlib_resources/_itertools.py deleted file mode 100644 index cce05582ff..0000000000 --- a/pkg_resources/_vendor/importlib_resources/_itertools.py +++ /dev/null @@ -1,35 +0,0 @@ -from itertools import filterfalse - -from typing import ( - Callable, - Iterable, - Iterator, - Optional, - Set, - TypeVar, - Union, -) - -# Type and type variable definitions -_T = TypeVar('_T') -_U = TypeVar('_U') - - -def unique_everseen( - iterable: Iterable[_T], key: Optional[Callable[[_T], _U]] = None -) -> Iterator[_T]: - "List unique elements, preserving order. Remember all elements ever seen." - # unique_everseen('AAAABBBCCDAABBB') --> A B C D - # unique_everseen('ABBCcAD', str.lower) --> A B C D - seen: Set[Union[_T, _U]] = set() - seen_add = seen.add - if key is None: - for element in filterfalse(seen.__contains__, iterable): - seen_add(element) - yield element - else: - for element in iterable: - k = key(element) - if k not in seen: - seen_add(k) - yield element diff --git a/pkg_resources/_vendor/importlib_resources/_legacy.py b/pkg_resources/_vendor/importlib_resources/_legacy.py deleted file mode 100644 index b1ea8105da..0000000000 --- a/pkg_resources/_vendor/importlib_resources/_legacy.py +++ /dev/null @@ -1,120 +0,0 @@ -import functools -import os -import pathlib -import types -import warnings - -from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any - -from . import _common - -Package = Union[types.ModuleType, str] -Resource = str - - -def deprecated(func): - @functools.wraps(func) - def wrapper(*args, **kwargs): - warnings.warn( - f"{func.__name__} is deprecated. Use files() instead. " - "Refer to https://importlib-resources.readthedocs.io" - "/en/latest/using.html#migrating-from-legacy for migration advice.", - DeprecationWarning, - stacklevel=2, - ) - return func(*args, **kwargs) - - return wrapper - - -def normalize_path(path: Any) -> str: - """Normalize a path by ensuring it is a string. - - If the resulting string contains path separators, an exception is raised. - """ - str_path = str(path) - parent, file_name = os.path.split(str_path) - if parent: - raise ValueError(f'{path!r} must be only a file name') - return file_name - - -@deprecated -def open_binary(package: Package, resource: Resource) -> BinaryIO: - """Return a file-like object opened for binary reading of the resource.""" - return (_common.files(package) / normalize_path(resource)).open('rb') - - -@deprecated -def read_binary(package: Package, resource: Resource) -> bytes: - """Return the binary contents of the resource.""" - return (_common.files(package) / normalize_path(resource)).read_bytes() - - -@deprecated -def open_text( - package: Package, - resource: Resource, - encoding: str = 'utf-8', - errors: str = 'strict', -) -> TextIO: - """Return a file-like object opened for text reading of the resource.""" - return (_common.files(package) / normalize_path(resource)).open( - 'r', encoding=encoding, errors=errors - ) - - -@deprecated -def read_text( - package: Package, - resource: Resource, - encoding: str = 'utf-8', - errors: str = 'strict', -) -> str: - """Return the decoded string of the resource. - - The decoding-related arguments have the same semantics as those of - bytes.decode(). - """ - with open_text(package, resource, encoding, errors) as fp: - return fp.read() - - -@deprecated -def contents(package: Package) -> Iterable[str]: - """Return an iterable of entries in `package`. - - Note that not all entries are resources. Specifically, directories are - not considered resources. Use `is_resource()` on each entry returned here - to check if it is a resource or not. - """ - return [path.name for path in _common.files(package).iterdir()] - - -@deprecated -def is_resource(package: Package, name: str) -> bool: - """True if `name` is a resource inside `package`. - - Directories are *not* resources. - """ - resource = normalize_path(name) - return any( - traversable.name == resource and traversable.is_file() - for traversable in _common.files(package).iterdir() - ) - - -@deprecated -def path( - package: Package, - resource: Resource, -) -> ContextManager[pathlib.Path]: - """A context manager providing a file path object to the resource. - - If the resource does not already exist on its own on the file system, - a temporary file will be created. If the file was created, the file - will be deleted upon exiting the context manager (no exception is - raised if the file was deleted prior to the context manager - exiting). - """ - return _common.as_file(_common.files(package) / normalize_path(resource)) diff --git a/pkg_resources/_vendor/importlib_resources/abc.py b/pkg_resources/_vendor/importlib_resources/abc.py deleted file mode 100644 index 23b6aeafe4..0000000000 --- a/pkg_resources/_vendor/importlib_resources/abc.py +++ /dev/null @@ -1,170 +0,0 @@ -import abc -import io -import itertools -import pathlib -from typing import Any, BinaryIO, Iterable, Iterator, NoReturn, Text, Optional - -from ._compat import runtime_checkable, Protocol, StrPath - - -__all__ = ["ResourceReader", "Traversable", "TraversableResources"] - - -class ResourceReader(metaclass=abc.ABCMeta): - """Abstract base class for loaders to provide resource reading support.""" - - @abc.abstractmethod - def open_resource(self, resource: Text) -> BinaryIO: - """Return an opened, file-like object for binary reading. - - The 'resource' argument is expected to represent only a file name. - If the resource cannot be found, FileNotFoundError is raised. - """ - # This deliberately raises FileNotFoundError instead of - # NotImplementedError so that if this method is accidentally called, - # it'll still do the right thing. - raise FileNotFoundError - - @abc.abstractmethod - def resource_path(self, resource: Text) -> Text: - """Return the file system path to the specified resource. - - The 'resource' argument is expected to represent only a file name. - If the resource does not exist on the file system, raise - FileNotFoundError. - """ - # This deliberately raises FileNotFoundError instead of - # NotImplementedError so that if this method is accidentally called, - # it'll still do the right thing. - raise FileNotFoundError - - @abc.abstractmethod - def is_resource(self, path: Text) -> bool: - """Return True if the named 'path' is a resource. - - Files are resources, directories are not. - """ - raise FileNotFoundError - - @abc.abstractmethod - def contents(self) -> Iterable[str]: - """Return an iterable of entries in `package`.""" - raise FileNotFoundError - - -class TraversalError(Exception): - pass - - -@runtime_checkable -class Traversable(Protocol): - """ - An object with a subset of pathlib.Path methods suitable for - traversing directories and opening files. - - Any exceptions that occur when accessing the backing resource - may propagate unaltered. - """ - - @abc.abstractmethod - def iterdir(self) -> Iterator["Traversable"]: - """ - Yield Traversable objects in self - """ - - def read_bytes(self) -> bytes: - """ - Read contents of self as bytes - """ - with self.open('rb') as strm: - return strm.read() - - def read_text(self, encoding: Optional[str] = None) -> str: - """ - Read contents of self as text - """ - with self.open(encoding=encoding) as strm: - return strm.read() - - @abc.abstractmethod - def is_dir(self) -> bool: - """ - Return True if self is a directory - """ - - @abc.abstractmethod - def is_file(self) -> bool: - """ - Return True if self is a file - """ - - def joinpath(self, *descendants: StrPath) -> "Traversable": - """ - Return Traversable resolved with any descendants applied. - - Each descendant should be a path segment relative to self - and each may contain multiple levels separated by - ``posixpath.sep`` (``/``). - """ - if not descendants: - return self - names = itertools.chain.from_iterable( - path.parts for path in map(pathlib.PurePosixPath, descendants) - ) - target = next(names) - matches = ( - traversable for traversable in self.iterdir() if traversable.name == target - ) - try: - match = next(matches) - except StopIteration: - raise TraversalError( - "Target not found during traversal.", target, list(names) - ) - return match.joinpath(*names) - - def __truediv__(self, child: StrPath) -> "Traversable": - """ - Return Traversable child in self - """ - return self.joinpath(child) - - @abc.abstractmethod - def open(self, mode='r', *args, **kwargs): - """ - mode may be 'r' or 'rb' to open as text or binary. Return a handle - suitable for reading (same as pathlib.Path.open). - - When opening as text, accepts encoding parameters such as those - accepted by io.TextIOWrapper. - """ - - @property - @abc.abstractmethod - def name(self) -> str: - """ - The base name of this object without any parent references. - """ - - -class TraversableResources(ResourceReader): - """ - The required interface for providing traversable - resources. - """ - - @abc.abstractmethod - def files(self) -> "Traversable": - """Return a Traversable object for the loaded package.""" - - def open_resource(self, resource: StrPath) -> io.BufferedReader: - return self.files().joinpath(resource).open('rb') - - def resource_path(self, resource: Any) -> NoReturn: - raise FileNotFoundError(resource) - - def is_resource(self, path: StrPath) -> bool: - return self.files().joinpath(path).is_file() - - def contents(self) -> Iterator[str]: - return (item.name for item in self.files().iterdir()) diff --git a/pkg_resources/_vendor/importlib_resources/readers.py b/pkg_resources/_vendor/importlib_resources/readers.py deleted file mode 100644 index ab34db7409..0000000000 --- a/pkg_resources/_vendor/importlib_resources/readers.py +++ /dev/null @@ -1,120 +0,0 @@ -import collections -import pathlib -import operator - -from . import abc - -from ._itertools import unique_everseen -from ._compat import ZipPath - - -def remove_duplicates(items): - return iter(collections.OrderedDict.fromkeys(items)) - - -class FileReader(abc.TraversableResources): - def __init__(self, loader): - self.path = pathlib.Path(loader.path).parent - - def resource_path(self, resource): - """ - Return the file system path to prevent - `resources.path()` from creating a temporary - copy. - """ - return str(self.path.joinpath(resource)) - - def files(self): - return self.path - - -class ZipReader(abc.TraversableResources): - def __init__(self, loader, module): - _, _, name = module.rpartition('.') - self.prefix = loader.prefix.replace('\\', '/') + name + '/' - self.archive = loader.archive - - def open_resource(self, resource): - try: - return super().open_resource(resource) - except KeyError as exc: - raise FileNotFoundError(exc.args[0]) - - def is_resource(self, path): - # workaround for `zipfile.Path.is_file` returning true - # for non-existent paths. - target = self.files().joinpath(path) - return target.is_file() and target.exists() - - def files(self): - return ZipPath(self.archive, self.prefix) - - -class MultiplexedPath(abc.Traversable): - """ - Given a series of Traversable objects, implement a merged - version of the interface across all objects. Useful for - namespace packages which may be multihomed at a single - name. - """ - - def __init__(self, *paths): - self._paths = list(map(pathlib.Path, remove_duplicates(paths))) - if not self._paths: - message = 'MultiplexedPath must contain at least one path' - raise FileNotFoundError(message) - if not all(path.is_dir() for path in self._paths): - raise NotADirectoryError('MultiplexedPath only supports directories') - - def iterdir(self): - files = (file for path in self._paths for file in path.iterdir()) - return unique_everseen(files, key=operator.attrgetter('name')) - - def read_bytes(self): - raise FileNotFoundError(f'{self} is not a file') - - def read_text(self, *args, **kwargs): - raise FileNotFoundError(f'{self} is not a file') - - def is_dir(self): - return True - - def is_file(self): - return False - - def joinpath(self, *descendants): - try: - return super().joinpath(*descendants) - except abc.TraversalError: - # One of the paths did not resolve (a directory does not exist). - # Just return something that will not exist. - return self._paths[0].joinpath(*descendants) - - def open(self, *args, **kwargs): - raise FileNotFoundError(f'{self} is not a file') - - @property - def name(self): - return self._paths[0].name - - def __repr__(self): - paths = ', '.join(f"'{path}'" for path in self._paths) - return f'MultiplexedPath({paths})' - - -class NamespaceReader(abc.TraversableResources): - def __init__(self, namespace_path): - if 'NamespacePath' not in str(namespace_path): - raise ValueError('Invalid path') - self.path = MultiplexedPath(*list(namespace_path)) - - def resource_path(self, resource): - """ - Return the file system path to prevent - `resources.path()` from creating a temporary - copy. - """ - return str(self.path.joinpath(resource)) - - def files(self): - return self.path diff --git a/pkg_resources/_vendor/importlib_resources/simple.py b/pkg_resources/_vendor/importlib_resources/simple.py deleted file mode 100644 index 7770c922c8..0000000000 --- a/pkg_resources/_vendor/importlib_resources/simple.py +++ /dev/null @@ -1,106 +0,0 @@ -""" -Interface adapters for low-level readers. -""" - -import abc -import io -import itertools -from typing import BinaryIO, List - -from .abc import Traversable, TraversableResources - - -class SimpleReader(abc.ABC): - """ - The minimum, low-level interface required from a resource - provider. - """ - - @property - @abc.abstractmethod - def package(self) -> str: - """ - The name of the package for which this reader loads resources. - """ - - @abc.abstractmethod - def children(self) -> List['SimpleReader']: - """ - Obtain an iterable of SimpleReader for available - child containers (e.g. directories). - """ - - @abc.abstractmethod - def resources(self) -> List[str]: - """ - Obtain available named resources for this virtual package. - """ - - @abc.abstractmethod - def open_binary(self, resource: str) -> BinaryIO: - """ - Obtain a File-like for a named resource. - """ - - @property - def name(self): - return self.package.split('.')[-1] - - -class ResourceContainer(Traversable): - """ - Traversable container for a package's resources via its reader. - """ - - def __init__(self, reader: SimpleReader): - self.reader = reader - - def is_dir(self): - return True - - def is_file(self): - return False - - def iterdir(self): - files = (ResourceHandle(self, name) for name in self.reader.resources) - dirs = map(ResourceContainer, self.reader.children()) - return itertools.chain(files, dirs) - - def open(self, *args, **kwargs): - raise IsADirectoryError() - - -class ResourceHandle(Traversable): - """ - Handle to a named resource in a ResourceReader. - """ - - def __init__(self, parent: ResourceContainer, name: str): - self.parent = parent - self.name = name # type: ignore - - def is_file(self): - return True - - def is_dir(self): - return False - - def open(self, mode='r', *args, **kwargs): - stream = self.parent.reader.open_binary(self.name) - if 'b' not in mode: - stream = io.TextIOWrapper(*args, **kwargs) - return stream - - def joinpath(self, name): - raise RuntimeError("Cannot traverse into a resource") - - -class TraversableReader(TraversableResources, SimpleReader): - """ - A TraversableResources based on SimpleReader. Resource providers - may derive from this class to provide the TraversableResources - interface by supplying the SimpleReader interface. - """ - - def files(self): - return ResourceContainer(self) diff --git a/pkg_resources/_vendor/importlib_resources/tests/_compat.py b/pkg_resources/_vendor/importlib_resources/tests/_compat.py deleted file mode 100644 index e7bf06dd4e..0000000000 --- a/pkg_resources/_vendor/importlib_resources/tests/_compat.py +++ /dev/null @@ -1,32 +0,0 @@ -import os - - -try: - from test.support import import_helper # type: ignore -except ImportError: - # Python 3.9 and earlier - class import_helper: # type: ignore - from test.support import ( - modules_setup, - modules_cleanup, - DirsOnSysPath, - CleanImport, - ) - - -try: - from test.support import os_helper # type: ignore -except ImportError: - # Python 3.9 compat - class os_helper: # type:ignore - from test.support import temp_dir - - -try: - # Python 3.10 - from test.support.os_helper import unlink -except ImportError: - from test.support import unlink as _unlink - - def unlink(target): - return _unlink(os.fspath(target)) diff --git a/pkg_resources/_vendor/importlib_resources/tests/_path.py b/pkg_resources/_vendor/importlib_resources/tests/_path.py deleted file mode 100644 index c630e4d3d3..0000000000 --- a/pkg_resources/_vendor/importlib_resources/tests/_path.py +++ /dev/null @@ -1,50 +0,0 @@ -import pathlib -import functools - - -#### -# from jaraco.path 3.4 - - -def build(spec, prefix=pathlib.Path()): - """ - Build a set of files/directories, as described by the spec. - - Each key represents a pathname, and the value represents - the content. Content may be a nested directory. - - >>> spec = { - ... 'README.txt': "A README file", - ... "foo": { - ... "__init__.py": "", - ... "bar": { - ... "__init__.py": "", - ... }, - ... "baz.py": "# Some code", - ... } - ... } - >>> tmpdir = getfixture('tmpdir') - >>> build(spec, tmpdir) - """ - for name, contents in spec.items(): - create(contents, pathlib.Path(prefix) / name) - - -@functools.singledispatch -def create(content, path): - path.mkdir(exist_ok=True) - build(content, prefix=path) # type: ignore - - -@create.register -def _(content: bytes, path): - path.write_bytes(content) - - -@create.register -def _(content: str, path): - path.write_text(content) - - -# end from jaraco.path -#### diff --git a/pkg_resources/_vendor/importlib_resources/tests/data01/binary.file b/pkg_resources/_vendor/importlib_resources/tests/data01/binary.file deleted file mode 100644 index eaf36c1dac..0000000000 Binary files a/pkg_resources/_vendor/importlib_resources/tests/data01/binary.file and /dev/null differ diff --git a/pkg_resources/_vendor/importlib_resources/tests/data01/subdirectory/binary.file b/pkg_resources/_vendor/importlib_resources/tests/data01/subdirectory/binary.file deleted file mode 100644 index eaf36c1dac..0000000000 Binary files a/pkg_resources/_vendor/importlib_resources/tests/data01/subdirectory/binary.file and /dev/null differ diff --git a/pkg_resources/_vendor/importlib_resources/tests/data01/utf-16.file b/pkg_resources/_vendor/importlib_resources/tests/data01/utf-16.file deleted file mode 100644 index 2cb772295e..0000000000 Binary files a/pkg_resources/_vendor/importlib_resources/tests/data01/utf-16.file and /dev/null differ diff --git a/pkg_resources/_vendor/importlib_resources/tests/data01/utf-8.file b/pkg_resources/_vendor/importlib_resources/tests/data01/utf-8.file deleted file mode 100644 index 1c0132ad90..0000000000 --- a/pkg_resources/_vendor/importlib_resources/tests/data01/utf-8.file +++ /dev/null @@ -1 +0,0 @@ -Hello, UTF-8 world! diff --git a/pkg_resources/_vendor/importlib_resources/tests/data02/one/resource1.txt b/pkg_resources/_vendor/importlib_resources/tests/data02/one/resource1.txt deleted file mode 100644 index 61a813e401..0000000000 --- a/pkg_resources/_vendor/importlib_resources/tests/data02/one/resource1.txt +++ /dev/null @@ -1 +0,0 @@ -one resource diff --git a/pkg_resources/_vendor/importlib_resources/tests/data02/two/__init__.py b/pkg_resources/_vendor/importlib_resources/tests/data02/two/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/pkg_resources/_vendor/importlib_resources/tests/data02/two/resource2.txt b/pkg_resources/_vendor/importlib_resources/tests/data02/two/resource2.txt deleted file mode 100644 index a80ce46ea3..0000000000 --- a/pkg_resources/_vendor/importlib_resources/tests/data02/two/resource2.txt +++ /dev/null @@ -1 +0,0 @@ -two resource diff --git a/pkg_resources/_vendor/importlib_resources/tests/namespacedata01/binary.file b/pkg_resources/_vendor/importlib_resources/tests/namespacedata01/binary.file deleted file mode 100644 index eaf36c1dac..0000000000 Binary files a/pkg_resources/_vendor/importlib_resources/tests/namespacedata01/binary.file and /dev/null differ diff --git a/pkg_resources/_vendor/importlib_resources/tests/namespacedata01/utf-16.file b/pkg_resources/_vendor/importlib_resources/tests/namespacedata01/utf-16.file deleted file mode 100644 index 2cb772295e..0000000000 Binary files a/pkg_resources/_vendor/importlib_resources/tests/namespacedata01/utf-16.file and /dev/null differ diff --git a/pkg_resources/_vendor/importlib_resources/tests/namespacedata01/utf-8.file b/pkg_resources/_vendor/importlib_resources/tests/namespacedata01/utf-8.file deleted file mode 100644 index 1c0132ad90..0000000000 --- a/pkg_resources/_vendor/importlib_resources/tests/namespacedata01/utf-8.file +++ /dev/null @@ -1 +0,0 @@ -Hello, UTF-8 world! diff --git a/pkg_resources/_vendor/importlib_resources/tests/test_compatibilty_files.py b/pkg_resources/_vendor/importlib_resources/tests/test_compatibilty_files.py deleted file mode 100644 index d92c7c56c9..0000000000 --- a/pkg_resources/_vendor/importlib_resources/tests/test_compatibilty_files.py +++ /dev/null @@ -1,102 +0,0 @@ -import io -import unittest - -import importlib_resources as resources - -from importlib_resources._adapters import ( - CompatibilityFiles, - wrap_spec, -) - -from . import util - - -class CompatibilityFilesTests(unittest.TestCase): - @property - def package(self): - bytes_data = io.BytesIO(b'Hello, world!') - return util.create_package( - file=bytes_data, - path='some_path', - contents=('a', 'b', 'c'), - ) - - @property - def files(self): - return resources.files(self.package) - - def test_spec_path_iter(self): - self.assertEqual( - sorted(path.name for path in self.files.iterdir()), - ['a', 'b', 'c'], - ) - - def test_child_path_iter(self): - self.assertEqual(list((self.files / 'a').iterdir()), []) - - def test_orphan_path_iter(self): - self.assertEqual(list((self.files / 'a' / 'a').iterdir()), []) - self.assertEqual(list((self.files / 'a' / 'a' / 'a').iterdir()), []) - - def test_spec_path_is(self): - self.assertFalse(self.files.is_file()) - self.assertFalse(self.files.is_dir()) - - def test_child_path_is(self): - self.assertTrue((self.files / 'a').is_file()) - self.assertFalse((self.files / 'a').is_dir()) - - def test_orphan_path_is(self): - self.assertFalse((self.files / 'a' / 'a').is_file()) - self.assertFalse((self.files / 'a' / 'a').is_dir()) - self.assertFalse((self.files / 'a' / 'a' / 'a').is_file()) - self.assertFalse((self.files / 'a' / 'a' / 'a').is_dir()) - - def test_spec_path_name(self): - self.assertEqual(self.files.name, 'testingpackage') - - def test_child_path_name(self): - self.assertEqual((self.files / 'a').name, 'a') - - def test_orphan_path_name(self): - self.assertEqual((self.files / 'a' / 'b').name, 'b') - self.assertEqual((self.files / 'a' / 'b' / 'c').name, 'c') - - def test_spec_path_open(self): - self.assertEqual(self.files.read_bytes(), b'Hello, world!') - self.assertEqual(self.files.read_text(), 'Hello, world!') - - def test_child_path_open(self): - self.assertEqual((self.files / 'a').read_bytes(), b'Hello, world!') - self.assertEqual((self.files / 'a').read_text(), 'Hello, world!') - - def test_orphan_path_open(self): - with self.assertRaises(FileNotFoundError): - (self.files / 'a' / 'b').read_bytes() - with self.assertRaises(FileNotFoundError): - (self.files / 'a' / 'b' / 'c').read_bytes() - - def test_open_invalid_mode(self): - with self.assertRaises(ValueError): - self.files.open('0') - - def test_orphan_path_invalid(self): - with self.assertRaises(ValueError): - CompatibilityFiles.OrphanPath() - - def test_wrap_spec(self): - spec = wrap_spec(self.package) - self.assertIsInstance(spec.loader.get_resource_reader(None), CompatibilityFiles) - - -class CompatibilityFilesNoReaderTests(unittest.TestCase): - @property - def package(self): - return util.create_package_from_loader(None) - - @property - def files(self): - return resources.files(self.package) - - def test_spec_path_joinpath(self): - self.assertIsInstance(self.files / 'a', CompatibilityFiles.OrphanPath) diff --git a/pkg_resources/_vendor/importlib_resources/tests/test_contents.py b/pkg_resources/_vendor/importlib_resources/tests/test_contents.py deleted file mode 100644 index 525568e8c9..0000000000 --- a/pkg_resources/_vendor/importlib_resources/tests/test_contents.py +++ /dev/null @@ -1,43 +0,0 @@ -import unittest -import importlib_resources as resources - -from . import data01 -from . import util - - -class ContentsTests: - expected = { - '__init__.py', - 'binary.file', - 'subdirectory', - 'utf-16.file', - 'utf-8.file', - } - - def test_contents(self): - contents = {path.name for path in resources.files(self.data).iterdir()} - assert self.expected <= contents - - -class ContentsDiskTests(ContentsTests, unittest.TestCase): - def setUp(self): - self.data = data01 - - -class ContentsZipTests(ContentsTests, util.ZipSetup, unittest.TestCase): - pass - - -class ContentsNamespaceTests(ContentsTests, unittest.TestCase): - expected = { - # no __init__ because of namespace design - # no subdirectory as incidental difference in fixture - 'binary.file', - 'utf-16.file', - 'utf-8.file', - } - - def setUp(self): - from . import namespacedata01 - - self.data = namespacedata01 diff --git a/pkg_resources/_vendor/importlib_resources/tests/test_files.py b/pkg_resources/_vendor/importlib_resources/tests/test_files.py deleted file mode 100644 index d258fb5f0f..0000000000 --- a/pkg_resources/_vendor/importlib_resources/tests/test_files.py +++ /dev/null @@ -1,112 +0,0 @@ -import typing -import textwrap -import unittest -import warnings -import importlib -import contextlib - -import importlib_resources as resources -from ..abc import Traversable -from . import data01 -from . import util -from . import _path -from ._compat import os_helper, import_helper - - -@contextlib.contextmanager -def suppress_known_deprecation(): - with warnings.catch_warnings(record=True) as ctx: - warnings.simplefilter('default', category=DeprecationWarning) - yield ctx - - -class FilesTests: - def test_read_bytes(self): - files = resources.files(self.data) - actual = files.joinpath('utf-8.file').read_bytes() - assert actual == b'Hello, UTF-8 world!\n' - - def test_read_text(self): - files = resources.files(self.data) - actual = files.joinpath('utf-8.file').read_text(encoding='utf-8') - assert actual == 'Hello, UTF-8 world!\n' - - @unittest.skipUnless( - hasattr(typing, 'runtime_checkable'), - "Only suitable when typing supports runtime_checkable", - ) - def test_traversable(self): - assert isinstance(resources.files(self.data), Traversable) - - def test_old_parameter(self): - """ - Files used to take a 'package' parameter. Make sure anyone - passing by name is still supported. - """ - with suppress_known_deprecation(): - resources.files(package=self.data) - - -class OpenDiskTests(FilesTests, unittest.TestCase): - def setUp(self): - self.data = data01 - - -class OpenZipTests(FilesTests, util.ZipSetup, unittest.TestCase): - pass - - -class OpenNamespaceTests(FilesTests, unittest.TestCase): - def setUp(self): - from . import namespacedata01 - - self.data = namespacedata01 - - -class SiteDir: - def setUp(self): - self.fixtures = contextlib.ExitStack() - self.addCleanup(self.fixtures.close) - self.site_dir = self.fixtures.enter_context(os_helper.temp_dir()) - self.fixtures.enter_context(import_helper.DirsOnSysPath(self.site_dir)) - self.fixtures.enter_context(import_helper.CleanImport()) - - -class ModulesFilesTests(SiteDir, unittest.TestCase): - def test_module_resources(self): - """ - A module can have resources found adjacent to the module. - """ - spec = { - 'mod.py': '', - 'res.txt': 'resources are the best', - } - _path.build(spec, self.site_dir) - import mod - - actual = resources.files(mod).joinpath('res.txt').read_text() - assert actual == spec['res.txt'] - - -class ImplicitContextFilesTests(SiteDir, unittest.TestCase): - def test_implicit_files(self): - """ - Without any parameter, files() will infer the location as the caller. - """ - spec = { - 'somepkg': { - '__init__.py': textwrap.dedent( - """ - import importlib_resources as res - val = res.files().joinpath('res.txt').read_text() - """ - ), - 'res.txt': 'resources are the best', - }, - } - _path.build(spec, self.site_dir) - assert importlib.import_module('somepkg').val == 'resources are the best' - - -if __name__ == '__main__': - unittest.main() diff --git a/pkg_resources/_vendor/importlib_resources/tests/test_open.py b/pkg_resources/_vendor/importlib_resources/tests/test_open.py deleted file mode 100644 index 87b42c3d39..0000000000 --- a/pkg_resources/_vendor/importlib_resources/tests/test_open.py +++ /dev/null @@ -1,81 +0,0 @@ -import unittest - -import importlib_resources as resources -from . import data01 -from . import util - - -class CommonBinaryTests(util.CommonTests, unittest.TestCase): - def execute(self, package, path): - target = resources.files(package).joinpath(path) - with target.open('rb'): - pass - - -class CommonTextTests(util.CommonTests, unittest.TestCase): - def execute(self, package, path): - target = resources.files(package).joinpath(path) - with target.open(): - pass - - -class OpenTests: - def test_open_binary(self): - target = resources.files(self.data) / 'binary.file' - with target.open('rb') as fp: - result = fp.read() - self.assertEqual(result, b'\x00\x01\x02\x03') - - def test_open_text_default_encoding(self): - target = resources.files(self.data) / 'utf-8.file' - with target.open() as fp: - result = fp.read() - self.assertEqual(result, 'Hello, UTF-8 world!\n') - - def test_open_text_given_encoding(self): - target = resources.files(self.data) / 'utf-16.file' - with target.open(encoding='utf-16', errors='strict') as fp: - result = fp.read() - self.assertEqual(result, 'Hello, UTF-16 world!\n') - - def test_open_text_with_errors(self): - # Raises UnicodeError without the 'errors' argument. - target = resources.files(self.data) / 'utf-16.file' - with target.open(encoding='utf-8', errors='strict') as fp: - self.assertRaises(UnicodeError, fp.read) - with target.open(encoding='utf-8', errors='ignore') as fp: - result = fp.read() - self.assertEqual( - result, - 'H\x00e\x00l\x00l\x00o\x00,\x00 ' - '\x00U\x00T\x00F\x00-\x001\x006\x00 ' - '\x00w\x00o\x00r\x00l\x00d\x00!\x00\n\x00', - ) - - def test_open_binary_FileNotFoundError(self): - target = resources.files(self.data) / 'does-not-exist' - self.assertRaises(FileNotFoundError, target.open, 'rb') - - def test_open_text_FileNotFoundError(self): - target = resources.files(self.data) / 'does-not-exist' - self.assertRaises(FileNotFoundError, target.open) - - -class OpenDiskTests(OpenTests, unittest.TestCase): - def setUp(self): - self.data = data01 - - -class OpenDiskNamespaceTests(OpenTests, unittest.TestCase): - def setUp(self): - from . import namespacedata01 - - self.data = namespacedata01 - - -class OpenZipTests(OpenTests, util.ZipSetup, unittest.TestCase): - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/pkg_resources/_vendor/importlib_resources/tests/test_path.py b/pkg_resources/_vendor/importlib_resources/tests/test_path.py deleted file mode 100644 index 4f4d3943bb..0000000000 --- a/pkg_resources/_vendor/importlib_resources/tests/test_path.py +++ /dev/null @@ -1,64 +0,0 @@ -import io -import unittest - -import importlib_resources as resources -from . import data01 -from . import util - - -class CommonTests(util.CommonTests, unittest.TestCase): - def execute(self, package, path): - with resources.as_file(resources.files(package).joinpath(path)): - pass - - -class PathTests: - def test_reading(self): - # Path should be readable. - # Test also implicitly verifies the returned object is a pathlib.Path - # instance. - target = resources.files(self.data) / 'utf-8.file' - with resources.as_file(target) as path: - self.assertTrue(path.name.endswith("utf-8.file"), repr(path)) - # pathlib.Path.read_text() was introduced in Python 3.5. - with path.open('r', encoding='utf-8') as file: - text = file.read() - self.assertEqual('Hello, UTF-8 world!\n', text) - - -class PathDiskTests(PathTests, unittest.TestCase): - data = data01 - - def test_natural_path(self): - """ - Guarantee the internal implementation detail that - file-system-backed resources do not get the tempdir - treatment. - """ - target = resources.files(self.data) / 'utf-8.file' - with resources.as_file(target) as path: - assert 'data' in str(path) - - -class PathMemoryTests(PathTests, unittest.TestCase): - def setUp(self): - file = io.BytesIO(b'Hello, UTF-8 world!\n') - self.addCleanup(file.close) - self.data = util.create_package( - file=file, path=FileNotFoundError("package exists only in memory") - ) - self.data.__spec__.origin = None - self.data.__spec__.has_location = False - - -class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase): - def test_remove_in_context_manager(self): - # It is not an error if the file that was temporarily stashed on the - # file system is removed inside the `with` stanza. - target = resources.files(self.data) / 'utf-8.file' - with resources.as_file(target) as path: - path.unlink() - - -if __name__ == '__main__': - unittest.main() diff --git a/pkg_resources/_vendor/importlib_resources/tests/test_read.py b/pkg_resources/_vendor/importlib_resources/tests/test_read.py deleted file mode 100644 index 41dd6db5f3..0000000000 --- a/pkg_resources/_vendor/importlib_resources/tests/test_read.py +++ /dev/null @@ -1,76 +0,0 @@ -import unittest -import importlib_resources as resources - -from . import data01 -from . import util -from importlib import import_module - - -class CommonBinaryTests(util.CommonTests, unittest.TestCase): - def execute(self, package, path): - resources.files(package).joinpath(path).read_bytes() - - -class CommonTextTests(util.CommonTests, unittest.TestCase): - def execute(self, package, path): - resources.files(package).joinpath(path).read_text() - - -class ReadTests: - def test_read_bytes(self): - result = resources.files(self.data).joinpath('binary.file').read_bytes() - self.assertEqual(result, b'\0\1\2\3') - - def test_read_text_default_encoding(self): - result = resources.files(self.data).joinpath('utf-8.file').read_text() - self.assertEqual(result, 'Hello, UTF-8 world!\n') - - def test_read_text_given_encoding(self): - result = ( - resources.files(self.data) - .joinpath('utf-16.file') - .read_text(encoding='utf-16') - ) - self.assertEqual(result, 'Hello, UTF-16 world!\n') - - def test_read_text_with_errors(self): - # Raises UnicodeError without the 'errors' argument. - target = resources.files(self.data) / 'utf-16.file' - self.assertRaises(UnicodeError, target.read_text, encoding='utf-8') - result = target.read_text(encoding='utf-8', errors='ignore') - self.assertEqual( - result, - 'H\x00e\x00l\x00l\x00o\x00,\x00 ' - '\x00U\x00T\x00F\x00-\x001\x006\x00 ' - '\x00w\x00o\x00r\x00l\x00d\x00!\x00\n\x00', - ) - - -class ReadDiskTests(ReadTests, unittest.TestCase): - data = data01 - - -class ReadZipTests(ReadTests, util.ZipSetup, unittest.TestCase): - def test_read_submodule_resource(self): - submodule = import_module('ziptestdata.subdirectory') - result = resources.files(submodule).joinpath('binary.file').read_bytes() - self.assertEqual(result, b'\0\1\2\3') - - def test_read_submodule_resource_by_name(self): - result = ( - resources.files('ziptestdata.subdirectory') - .joinpath('binary.file') - .read_bytes() - ) - self.assertEqual(result, b'\0\1\2\3') - - -class ReadNamespaceTests(ReadTests, unittest.TestCase): - def setUp(self): - from . import namespacedata01 - - self.data = namespacedata01 - - -if __name__ == '__main__': - unittest.main() diff --git a/pkg_resources/_vendor/importlib_resources/tests/test_reader.py b/pkg_resources/_vendor/importlib_resources/tests/test_reader.py deleted file mode 100644 index 1c8ebeeb13..0000000000 --- a/pkg_resources/_vendor/importlib_resources/tests/test_reader.py +++ /dev/null @@ -1,133 +0,0 @@ -import os.path -import sys -import pathlib -import unittest - -from importlib import import_module -from importlib_resources.readers import MultiplexedPath, NamespaceReader - - -class MultiplexedPathTest(unittest.TestCase): - @classmethod - def setUpClass(cls): - path = pathlib.Path(__file__).parent / 'namespacedata01' - cls.folder = str(path) - - def test_init_no_paths(self): - with self.assertRaises(FileNotFoundError): - MultiplexedPath() - - def test_init_file(self): - with self.assertRaises(NotADirectoryError): - MultiplexedPath(os.path.join(self.folder, 'binary.file')) - - def test_iterdir(self): - contents = {path.name for path in MultiplexedPath(self.folder).iterdir()} - try: - contents.remove('__pycache__') - except (KeyError, ValueError): - pass - self.assertEqual(contents, {'binary.file', 'utf-16.file', 'utf-8.file'}) - - def test_iterdir_duplicate(self): - data01 = os.path.abspath(os.path.join(__file__, '..', 'data01')) - contents = { - path.name for path in MultiplexedPath(self.folder, data01).iterdir() - } - for remove in ('__pycache__', '__init__.pyc'): - try: - contents.remove(remove) - except (KeyError, ValueError): - pass - self.assertEqual( - contents, - {'__init__.py', 'binary.file', 'subdirectory', 'utf-16.file', 'utf-8.file'}, - ) - - def test_is_dir(self): - self.assertEqual(MultiplexedPath(self.folder).is_dir(), True) - - def test_is_file(self): - self.assertEqual(MultiplexedPath(self.folder).is_file(), False) - - def test_open_file(self): - path = MultiplexedPath(self.folder) - with self.assertRaises(FileNotFoundError): - path.read_bytes() - with self.assertRaises(FileNotFoundError): - path.read_text() - with self.assertRaises(FileNotFoundError): - path.open() - - def test_join_path(self): - prefix = os.path.abspath(os.path.join(__file__, '..')) - data01 = os.path.join(prefix, 'data01') - path = MultiplexedPath(self.folder, data01) - self.assertEqual( - str(path.joinpath('binary.file'))[len(prefix) + 1 :], - os.path.join('namespacedata01', 'binary.file'), - ) - self.assertEqual( - str(path.joinpath('subdirectory'))[len(prefix) + 1 :], - os.path.join('data01', 'subdirectory'), - ) - self.assertEqual( - str(path.joinpath('imaginary'))[len(prefix) + 1 :], - os.path.join('namespacedata01', 'imaginary'), - ) - self.assertEqual(path.joinpath(), path) - - def test_join_path_compound(self): - path = MultiplexedPath(self.folder) - assert not path.joinpath('imaginary/foo.py').exists() - - def test_repr(self): - self.assertEqual( - repr(MultiplexedPath(self.folder)), - f"MultiplexedPath('{self.folder}')", - ) - - def test_name(self): - self.assertEqual( - MultiplexedPath(self.folder).name, - os.path.basename(self.folder), - ) - - -class NamespaceReaderTest(unittest.TestCase): - site_dir = str(pathlib.Path(__file__).parent) - - @classmethod - def setUpClass(cls): - sys.path.append(cls.site_dir) - - @classmethod - def tearDownClass(cls): - sys.path.remove(cls.site_dir) - - def test_init_error(self): - with self.assertRaises(ValueError): - NamespaceReader(['path1', 'path2']) - - def test_resource_path(self): - namespacedata01 = import_module('namespacedata01') - reader = NamespaceReader(namespacedata01.__spec__.submodule_search_locations) - - root = os.path.abspath(os.path.join(__file__, '..', 'namespacedata01')) - self.assertEqual( - reader.resource_path('binary.file'), os.path.join(root, 'binary.file') - ) - self.assertEqual( - reader.resource_path('imaginary'), os.path.join(root, 'imaginary') - ) - - def test_files(self): - namespacedata01 = import_module('namespacedata01') - reader = NamespaceReader(namespacedata01.__spec__.submodule_search_locations) - root = os.path.abspath(os.path.join(__file__, '..', 'namespacedata01')) - self.assertIsInstance(reader.files(), MultiplexedPath) - self.assertEqual(repr(reader.files()), f"MultiplexedPath('{root}')") - - -if __name__ == '__main__': - unittest.main() diff --git a/pkg_resources/_vendor/importlib_resources/tests/test_resource.py b/pkg_resources/_vendor/importlib_resources/tests/test_resource.py deleted file mode 100644 index 8239027167..0000000000 --- a/pkg_resources/_vendor/importlib_resources/tests/test_resource.py +++ /dev/null @@ -1,260 +0,0 @@ -import sys -import unittest -import importlib_resources as resources -import uuid -import pathlib - -from . import data01 -from . import zipdata01, zipdata02 -from . import util -from importlib import import_module -from ._compat import import_helper, unlink - - -class ResourceTests: - # Subclasses are expected to set the `data` attribute. - - def test_is_file_exists(self): - target = resources.files(self.data) / 'binary.file' - self.assertTrue(target.is_file()) - - def test_is_file_missing(self): - target = resources.files(self.data) / 'not-a-file' - self.assertFalse(target.is_file()) - - def test_is_dir(self): - target = resources.files(self.data) / 'subdirectory' - self.assertFalse(target.is_file()) - self.assertTrue(target.is_dir()) - - -class ResourceDiskTests(ResourceTests, unittest.TestCase): - def setUp(self): - self.data = data01 - - -class ResourceZipTests(ResourceTests, util.ZipSetup, unittest.TestCase): - pass - - -def names(traversable): - return {item.name for item in traversable.iterdir()} - - -class ResourceLoaderTests(unittest.TestCase): - def test_resource_contents(self): - package = util.create_package( - file=data01, path=data01.__file__, contents=['A', 'B', 'C'] - ) - self.assertEqual(names(resources.files(package)), {'A', 'B', 'C'}) - - def test_is_file(self): - package = util.create_package( - file=data01, path=data01.__file__, contents=['A', 'B', 'C', 'D/E', 'D/F'] - ) - self.assertTrue(resources.files(package).joinpath('B').is_file()) - - def test_is_dir(self): - package = util.create_package( - file=data01, path=data01.__file__, contents=['A', 'B', 'C', 'D/E', 'D/F'] - ) - self.assertTrue(resources.files(package).joinpath('D').is_dir()) - - def test_resource_missing(self): - package = util.create_package( - file=data01, path=data01.__file__, contents=['A', 'B', 'C', 'D/E', 'D/F'] - ) - self.assertFalse(resources.files(package).joinpath('Z').is_file()) - - -class ResourceCornerCaseTests(unittest.TestCase): - def test_package_has_no_reader_fallback(self): - # Test odd ball packages which: - # 1. Do not have a ResourceReader as a loader - # 2. Are not on the file system - # 3. Are not in a zip file - module = util.create_package( - file=data01, path=data01.__file__, contents=['A', 'B', 'C'] - ) - # Give the module a dummy loader. - module.__loader__ = object() - # Give the module a dummy origin. - module.__file__ = '/path/which/shall/not/be/named' - module.__spec__.loader = module.__loader__ - module.__spec__.origin = module.__file__ - self.assertFalse(resources.files(module).joinpath('A').is_file()) - - -class ResourceFromZipsTest01(util.ZipSetupBase, unittest.TestCase): - ZIP_MODULE = zipdata01 # type: ignore - - def test_is_submodule_resource(self): - submodule = import_module('ziptestdata.subdirectory') - self.assertTrue(resources.files(submodule).joinpath('binary.file').is_file()) - - def test_read_submodule_resource_by_name(self): - self.assertTrue( - resources.files('ziptestdata.subdirectory') - .joinpath('binary.file') - .is_file() - ) - - def test_submodule_contents(self): - submodule = import_module('ziptestdata.subdirectory') - self.assertEqual( - names(resources.files(submodule)), {'__init__.py', 'binary.file'} - ) - - def test_submodule_contents_by_name(self): - self.assertEqual( - names(resources.files('ziptestdata.subdirectory')), - {'__init__.py', 'binary.file'}, - ) - - def test_as_file_directory(self): - with resources.as_file(resources.files('ziptestdata')) as data: - assert data.name == 'ziptestdata' - assert data.is_dir() - assert data.joinpath('subdirectory').is_dir() - assert len(list(data.iterdir())) - assert not data.parent.exists() - - -class ResourceFromZipsTest02(util.ZipSetupBase, unittest.TestCase): - ZIP_MODULE = zipdata02 # type: ignore - - def test_unrelated_contents(self): - """ - Test thata zip with two unrelated subpackages return - distinct resources. Ref python/importlib_resources#44. - """ - self.assertEqual( - names(resources.files('ziptestdata.one')), - {'__init__.py', 'resource1.txt'}, - ) - self.assertEqual( - names(resources.files('ziptestdata.two')), - {'__init__.py', 'resource2.txt'}, - ) - - -class DeletingZipsTest(unittest.TestCase): - """Having accessed resources in a zip file should not keep an open - reference to the zip. - """ - - ZIP_MODULE = zipdata01 - - def setUp(self): - modules = import_helper.modules_setup() - self.addCleanup(import_helper.modules_cleanup, *modules) - - data_path = pathlib.Path(self.ZIP_MODULE.__file__) - data_dir = data_path.parent - self.source_zip_path = data_dir / 'ziptestdata.zip' - self.zip_path = pathlib.Path(f'{uuid.uuid4()}.zip').absolute() - self.zip_path.write_bytes(self.source_zip_path.read_bytes()) - sys.path.append(str(self.zip_path)) - self.data = import_module('ziptestdata') - - def tearDown(self): - try: - sys.path.remove(str(self.zip_path)) - except ValueError: - pass - - try: - del sys.path_importer_cache[str(self.zip_path)] - del sys.modules[self.data.__name__] - except KeyError: - pass - - try: - unlink(self.zip_path) - except OSError: - # If the test fails, this will probably fail too - pass - - def test_iterdir_does_not_keep_open(self): - c = [item.name for item in resources.files('ziptestdata').iterdir()] - self.zip_path.unlink() - del c - - def test_is_file_does_not_keep_open(self): - c = resources.files('ziptestdata').joinpath('binary.file').is_file() - self.zip_path.unlink() - del c - - def test_is_file_failure_does_not_keep_open(self): - c = resources.files('ziptestdata').joinpath('not-present').is_file() - self.zip_path.unlink() - del c - - @unittest.skip("Desired but not supported.") - def test_as_file_does_not_keep_open(self): # pragma: no cover - c = resources.as_file(resources.files('ziptestdata') / 'binary.file') - self.zip_path.unlink() - del c - - def test_entered_path_does_not_keep_open(self): - # This is what certifi does on import to make its bundle - # available for the process duration. - c = resources.as_file( - resources.files('ziptestdata') / 'binary.file' - ).__enter__() - self.zip_path.unlink() - del c - - def test_read_binary_does_not_keep_open(self): - c = resources.files('ziptestdata').joinpath('binary.file').read_bytes() - self.zip_path.unlink() - del c - - def test_read_text_does_not_keep_open(self): - c = resources.files('ziptestdata').joinpath('utf-8.file').read_text() - self.zip_path.unlink() - del c - - -class ResourceFromNamespaceTest01(unittest.TestCase): - site_dir = str(pathlib.Path(__file__).parent) - - @classmethod - def setUpClass(cls): - sys.path.append(cls.site_dir) - - @classmethod - def tearDownClass(cls): - sys.path.remove(cls.site_dir) - - def test_is_submodule_resource(self): - self.assertTrue( - resources.files(import_module('namespacedata01')) - .joinpath('binary.file') - .is_file() - ) - - def test_read_submodule_resource_by_name(self): - self.assertTrue( - resources.files('namespacedata01').joinpath('binary.file').is_file() - ) - - def test_submodule_contents(self): - contents = names(resources.files(import_module('namespacedata01'))) - try: - contents.remove('__pycache__') - except KeyError: - pass - self.assertEqual(contents, {'binary.file', 'utf-8.file', 'utf-16.file'}) - - def test_submodule_contents_by_name(self): - contents = names(resources.files('namespacedata01')) - try: - contents.remove('__pycache__') - except KeyError: - pass - self.assertEqual(contents, {'binary.file', 'utf-8.file', 'utf-16.file'}) - - -if __name__ == '__main__': - unittest.main() diff --git a/pkg_resources/_vendor/importlib_resources/tests/update-zips.py b/pkg_resources/_vendor/importlib_resources/tests/update-zips.py deleted file mode 100644 index 231334aa7e..0000000000 --- a/pkg_resources/_vendor/importlib_resources/tests/update-zips.py +++ /dev/null @@ -1,53 +0,0 @@ -""" -Generate the zip test data files. - -Run to build the tests/zipdataNN/ziptestdata.zip files from -files in tests/dataNN. - -Replaces the file with the working copy, but does commit anything -to the source repo. -""" - -import contextlib -import os -import pathlib -import zipfile - - -def main(): - """ - >>> from unittest import mock - >>> monkeypatch = getfixture('monkeypatch') - >>> monkeypatch.setattr(zipfile, 'ZipFile', mock.MagicMock()) - >>> print(); main() # print workaround for bpo-32509 - - ...data01... -> ziptestdata/... - ... - ...data02... -> ziptestdata/... - ... - """ - suffixes = '01', '02' - tuple(map(generate, suffixes)) - - -def generate(suffix): - root = pathlib.Path(__file__).parent.relative_to(os.getcwd()) - zfpath = root / f'zipdata{suffix}/ziptestdata.zip' - with zipfile.ZipFile(zfpath, 'w') as zf: - for src, rel in walk(root / f'data{suffix}'): - dst = 'ziptestdata' / pathlib.PurePosixPath(rel.as_posix()) - print(src, '->', dst) - zf.write(src, dst) - - -def walk(datapath): - for dirpath, dirnames, filenames in os.walk(datapath): - with contextlib.suppress(ValueError): - dirnames.remove('__pycache__') - for filename in filenames: - res = pathlib.Path(dirpath) / filename - rel = res.relative_to(datapath) - yield res, rel - - -__name__ == '__main__' and main() diff --git a/pkg_resources/_vendor/importlib_resources/tests/util.py b/pkg_resources/_vendor/importlib_resources/tests/util.py deleted file mode 100644 index b596c0ce4f..0000000000 --- a/pkg_resources/_vendor/importlib_resources/tests/util.py +++ /dev/null @@ -1,167 +0,0 @@ -import abc -import importlib -import io -import sys -import types -import pathlib - -from . import data01 -from . import zipdata01 -from ..abc import ResourceReader -from ._compat import import_helper - - -from importlib.machinery import ModuleSpec - - -class Reader(ResourceReader): - def __init__(self, **kwargs): - vars(self).update(kwargs) - - def get_resource_reader(self, package): - return self - - def open_resource(self, path): - self._path = path - if isinstance(self.file, Exception): - raise self.file - return self.file - - def resource_path(self, path_): - self._path = path_ - if isinstance(self.path, Exception): - raise self.path - return self.path - - def is_resource(self, path_): - self._path = path_ - if isinstance(self.path, Exception): - raise self.path - - def part(entry): - return entry.split('/') - - return any( - len(parts) == 1 and parts[0] == path_ for parts in map(part, self._contents) - ) - - def contents(self): - if isinstance(self.path, Exception): - raise self.path - yield from self._contents - - -def create_package_from_loader(loader, is_package=True): - name = 'testingpackage' - module = types.ModuleType(name) - spec = ModuleSpec(name, loader, origin='does-not-exist', is_package=is_package) - module.__spec__ = spec - module.__loader__ = loader - return module - - -def create_package(file=None, path=None, is_package=True, contents=()): - return create_package_from_loader( - Reader(file=file, path=path, _contents=contents), - is_package, - ) - - -class CommonTests(metaclass=abc.ABCMeta): - """ - Tests shared by test_open, test_path, and test_read. - """ - - @abc.abstractmethod - def execute(self, package, path): - """ - Call the pertinent legacy API function (e.g. open_text, path) - on package and path. - """ - - def test_package_name(self): - # Passing in the package name should succeed. - self.execute(data01.__name__, 'utf-8.file') - - def test_package_object(self): - # Passing in the package itself should succeed. - self.execute(data01, 'utf-8.file') - - def test_string_path(self): - # Passing in a string for the path should succeed. - path = 'utf-8.file' - self.execute(data01, path) - - def test_pathlib_path(self): - # Passing in a pathlib.PurePath object for the path should succeed. - path = pathlib.PurePath('utf-8.file') - self.execute(data01, path) - - def test_importing_module_as_side_effect(self): - # The anchor package can already be imported. - del sys.modules[data01.__name__] - self.execute(data01.__name__, 'utf-8.file') - - def test_missing_path(self): - # Attempting to open or read or request the path for a - # non-existent path should succeed if open_resource - # can return a viable data stream. - bytes_data = io.BytesIO(b'Hello, world!') - package = create_package(file=bytes_data, path=FileNotFoundError()) - self.execute(package, 'utf-8.file') - self.assertEqual(package.__loader__._path, 'utf-8.file') - - def test_extant_path(self): - # Attempting to open or read or request the path when the - # path does exist should still succeed. Does not assert - # anything about the result. - bytes_data = io.BytesIO(b'Hello, world!') - # any path that exists - path = __file__ - package = create_package(file=bytes_data, path=path) - self.execute(package, 'utf-8.file') - self.assertEqual(package.__loader__._path, 'utf-8.file') - - def test_useless_loader(self): - package = create_package(file=FileNotFoundError(), path=FileNotFoundError()) - with self.assertRaises(FileNotFoundError): - self.execute(package, 'utf-8.file') - - -class ZipSetupBase: - ZIP_MODULE = None - - @classmethod - def setUpClass(cls): - data_path = pathlib.Path(cls.ZIP_MODULE.__file__) - data_dir = data_path.parent - cls._zip_path = str(data_dir / 'ziptestdata.zip') - sys.path.append(cls._zip_path) - cls.data = importlib.import_module('ziptestdata') - - @classmethod - def tearDownClass(cls): - try: - sys.path.remove(cls._zip_path) - except ValueError: - pass - - try: - del sys.path_importer_cache[cls._zip_path] - del sys.modules[cls.data.__name__] - except KeyError: - pass - - try: - del cls.data - del cls._zip_path - except AttributeError: - pass - - def setUp(self): - modules = import_helper.modules_setup() - self.addCleanup(import_helper.modules_cleanup, *modules) - - -class ZipSetup(ZipSetupBase): - ZIP_MODULE = zipdata01 # type: ignore diff --git a/pkg_resources/_vendor/importlib_resources/tests/zipdata01/__init__.py b/pkg_resources/_vendor/importlib_resources/tests/zipdata01/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/pkg_resources/_vendor/importlib_resources/tests/zipdata01/ziptestdata.zip b/pkg_resources/_vendor/importlib_resources/tests/zipdata01/ziptestdata.zip deleted file mode 100644 index 9a3bb0739f..0000000000 Binary files a/pkg_resources/_vendor/importlib_resources/tests/zipdata01/ziptestdata.zip and /dev/null differ diff --git a/pkg_resources/_vendor/importlib_resources/tests/zipdata02/__init__.py b/pkg_resources/_vendor/importlib_resources/tests/zipdata02/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/pkg_resources/_vendor/importlib_resources/tests/zipdata02/ziptestdata.zip b/pkg_resources/_vendor/importlib_resources/tests/zipdata02/ziptestdata.zip deleted file mode 100644 index d63ff512d2..0000000000 Binary files a/pkg_resources/_vendor/importlib_resources/tests/zipdata02/ziptestdata.zip and /dev/null differ diff --git a/pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/INSTALLER b/pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a..0000000000 --- a/pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/LICENSE b/pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/LICENSE deleted file mode 100644 index 353924be0e..0000000000 --- a/pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright Jason R. Coombs - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/METADATA b/pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/METADATA deleted file mode 100644 index 281137a035..0000000000 --- a/pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/METADATA +++ /dev/null @@ -1,68 +0,0 @@ -Metadata-Version: 2.1 -Name: jaraco.context -Version: 4.3.0 -Summary: Context managers by jaraco -Home-page: https://github.com/jaraco/jaraco.context -Author: Jason R. Coombs -Author-email: jaraco@jaraco.com -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: MIT License -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3 :: Only -Requires-Python: >=3.7 -License-File: LICENSE -Provides-Extra: docs -Requires-Dist: sphinx (>=3.5) ; extra == 'docs' -Requires-Dist: jaraco.packaging (>=9) ; extra == 'docs' -Requires-Dist: rst.linker (>=1.9) ; extra == 'docs' -Requires-Dist: furo ; extra == 'docs' -Requires-Dist: sphinx-lint ; extra == 'docs' -Requires-Dist: jaraco.tidelift (>=1.4) ; extra == 'docs' -Provides-Extra: testing -Requires-Dist: pytest (>=6) ; extra == 'testing' -Requires-Dist: pytest-checkdocs (>=2.4) ; extra == 'testing' -Requires-Dist: flake8 (<5) ; extra == 'testing' -Requires-Dist: pytest-cov ; extra == 'testing' -Requires-Dist: pytest-enabler (>=1.3) ; extra == 'testing' -Requires-Dist: pytest-black (>=0.3.7) ; (platform_python_implementation != "PyPy") and extra == 'testing' -Requires-Dist: pytest-mypy (>=0.9.1) ; (platform_python_implementation != "PyPy") and extra == 'testing' -Requires-Dist: pytest-flake8 ; (python_version < "3.12") and extra == 'testing' - -.. image:: https://img.shields.io/pypi/v/jaraco.context.svg - :target: https://pypi.org/project/jaraco.context - -.. image:: https://img.shields.io/pypi/pyversions/jaraco.context.svg - -.. image:: https://github.com/jaraco/jaraco.context/workflows/tests/badge.svg - :target: https://github.com/jaraco/jaraco.context/actions?query=workflow%3A%22tests%22 - :alt: tests - -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black - :alt: Code style: Black - -.. image:: https://readthedocs.org/projects/jaracocontext/badge/?version=latest - :target: https://jaracocontext.readthedocs.io/en/latest/?badge=latest - -.. image:: https://img.shields.io/badge/skeleton-2023-informational - :target: https://blog.jaraco.com/skeleton - -.. image:: https://tidelift.com/badges/package/pypi/jaraco.context - :target: https://tidelift.com/subscription/pkg/pypi-jaraco.context?utm_source=pypi-jaraco.context&utm_medium=readme - -For Enterprise -============== - -Available as part of the Tidelift Subscription. - -This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. - -`Learn more `_. - -Security Contact -================ - -To report a security vulnerability, please use the -`Tidelift security contact `_. -Tidelift will coordinate the fix and disclosure. diff --git a/pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/RECORD b/pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/RECORD deleted file mode 100644 index 03122364a2..0000000000 --- a/pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/RECORD +++ /dev/null @@ -1,8 +0,0 @@ -jaraco.context-4.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -jaraco.context-4.3.0.dist-info/LICENSE,sha256=2z8CRrH5J48VhFuZ_sR4uLUG63ZIeZNyL4xuJUKF-vg,1050 -jaraco.context-4.3.0.dist-info/METADATA,sha256=GqMykAm33E7Tt_t_MHc5O7GJN62Qwp6MEHX9WD-LPow,2958 -jaraco.context-4.3.0.dist-info/RECORD,, -jaraco.context-4.3.0.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92 -jaraco.context-4.3.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 -jaraco/__pycache__/context.cpython-311.pyc,, -jaraco/context.py,sha256=vlyDzb_PvZ9H7R9bbTr_CMRnveW5Dc56eC7eyd_GfoA,7460 diff --git a/pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/INSTALLER b/pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a..0000000000 --- a/pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/METADATA b/pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/METADATA deleted file mode 100644 index 23c6f5ef2b..0000000000 --- a/pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/METADATA +++ /dev/null @@ -1,72 +0,0 @@ -Metadata-Version: 2.1 -Name: jaraco.functools -Version: 3.6.0 -Summary: Functools like those found in stdlib -Home-page: https://github.com/jaraco/jaraco.functools -Author: Jason R. Coombs -Author-email: jaraco@jaraco.com -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: MIT License -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3 :: Only -Requires-Python: >=3.7 -License-File: LICENSE -Requires-Dist: more-itertools -Provides-Extra: docs -Requires-Dist: sphinx (>=3.5) ; extra == 'docs' -Requires-Dist: jaraco.packaging (>=9) ; extra == 'docs' -Requires-Dist: rst.linker (>=1.9) ; extra == 'docs' -Requires-Dist: furo ; extra == 'docs' -Requires-Dist: sphinx-lint ; extra == 'docs' -Requires-Dist: jaraco.tidelift (>=1.4) ; extra == 'docs' -Provides-Extra: testing -Requires-Dist: pytest (>=6) ; extra == 'testing' -Requires-Dist: pytest-checkdocs (>=2.4) ; extra == 'testing' -Requires-Dist: flake8 (<5) ; extra == 'testing' -Requires-Dist: pytest-cov ; extra == 'testing' -Requires-Dist: pytest-enabler (>=1.3) ; extra == 'testing' -Requires-Dist: jaraco.classes ; extra == 'testing' -Requires-Dist: pytest-black (>=0.3.7) ; (platform_python_implementation != "PyPy") and extra == 'testing' -Requires-Dist: pytest-mypy (>=0.9.1) ; (platform_python_implementation != "PyPy") and extra == 'testing' -Requires-Dist: pytest-flake8 ; (python_version < "3.12") and extra == 'testing' - -.. image:: https://img.shields.io/pypi/v/jaraco.functools.svg - :target: https://pypi.org/project/jaraco.functools - -.. image:: https://img.shields.io/pypi/pyversions/jaraco.functools.svg - -.. image:: https://github.com/jaraco/jaraco.functools/workflows/tests/badge.svg - :target: https://github.com/jaraco/jaraco.functools/actions?query=workflow%3A%22tests%22 - :alt: tests - -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black - :alt: Code style: Black - -.. image:: https://readthedocs.org/projects/jaracofunctools/badge/?version=latest - :target: https://jaracofunctools.readthedocs.io/en/latest/?badge=latest - -.. image:: https://img.shields.io/badge/skeleton-2023-informational - :target: https://blog.jaraco.com/skeleton - -.. image:: https://tidelift.com/badges/package/pypi/jaraco.functools - :target: https://tidelift.com/subscription/pkg/pypi-jaraco.functools?utm_source=pypi-jaraco.functools&utm_medium=readme - -Additional functools in the spirit of stdlib's functools. - -For Enterprise -============== - -Available as part of the Tidelift Subscription. - -This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. - -`Learn more `_. - -Security Contact -================ - -To report a security vulnerability, please use the -`Tidelift security contact `_. -Tidelift will coordinate the fix and disclosure. diff --git a/pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/RECORD b/pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/RECORD deleted file mode 100644 index 70a3521307..0000000000 --- a/pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/RECORD +++ /dev/null @@ -1,8 +0,0 @@ -jaraco.functools-3.6.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -jaraco.functools-3.6.0.dist-info/LICENSE,sha256=2z8CRrH5J48VhFuZ_sR4uLUG63ZIeZNyL4xuJUKF-vg,1050 -jaraco.functools-3.6.0.dist-info/METADATA,sha256=ImGoa1WEbhsibIb288yWqkDAvqLwlPzayjravRvW_Bs,3136 -jaraco.functools-3.6.0.dist-info/RECORD,, -jaraco.functools-3.6.0.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92 -jaraco.functools-3.6.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 -jaraco/__pycache__/functools.cpython-311.pyc,, -jaraco/functools.py,sha256=GhSJGMVMcb0U4-axXaY_au30hT-ceW-HM1EbV1_9NzI,15035 diff --git a/pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/INSTALLER b/pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a..0000000000 --- a/pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/LICENSE b/pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/LICENSE deleted file mode 100644 index 353924be0e..0000000000 --- a/pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright Jason R. Coombs - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/METADATA b/pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/METADATA deleted file mode 100644 index 615a50a4ae..0000000000 --- a/pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/METADATA +++ /dev/null @@ -1,55 +0,0 @@ -Metadata-Version: 2.1 -Name: jaraco.text -Version: 3.7.0 -Summary: Module for text manipulation -Home-page: https://github.com/jaraco/jaraco.text -Author: Jason R. Coombs -Author-email: jaraco@jaraco.com -License: UNKNOWN -Platform: UNKNOWN -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: MIT License -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3 :: Only -Requires-Python: >=3.6 -License-File: LICENSE -Requires-Dist: jaraco.functools -Requires-Dist: jaraco.context (>=4.1) -Requires-Dist: importlib-resources ; python_version < "3.9" -Provides-Extra: docs -Requires-Dist: sphinx ; extra == 'docs' -Requires-Dist: jaraco.packaging (>=8.2) ; extra == 'docs' -Requires-Dist: rst.linker (>=1.9) ; extra == 'docs' -Provides-Extra: testing -Requires-Dist: pytest (>=6) ; extra == 'testing' -Requires-Dist: pytest-checkdocs (>=2.4) ; extra == 'testing' -Requires-Dist: pytest-flake8 ; extra == 'testing' -Requires-Dist: pytest-cov ; extra == 'testing' -Requires-Dist: pytest-enabler (>=1.0.1) ; extra == 'testing' -Requires-Dist: pytest-black (>=0.3.7) ; (platform_python_implementation != "PyPy") and extra == 'testing' -Requires-Dist: pytest-mypy ; (platform_python_implementation != "PyPy") and extra == 'testing' - -.. image:: https://img.shields.io/pypi/v/jaraco.text.svg - :target: `PyPI link`_ - -.. image:: https://img.shields.io/pypi/pyversions/jaraco.text.svg - :target: `PyPI link`_ - -.. _PyPI link: https://pypi.org/project/jaraco.text - -.. image:: https://github.com/jaraco/jaraco.text/workflows/tests/badge.svg - :target: https://github.com/jaraco/jaraco.text/actions?query=workflow%3A%22tests%22 - :alt: tests - -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black - :alt: Code style: Black - -.. image:: https://readthedocs.org/projects/jaracotext/badge/?version=latest - :target: https://jaracotext.readthedocs.io/en/latest/?badge=latest - -.. image:: https://img.shields.io/badge/skeleton-2021-informational - :target: https://blog.jaraco.com/skeleton - - diff --git a/pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/RECORD b/pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/RECORD deleted file mode 100644 index dd471b0708..0000000000 --- a/pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/RECORD +++ /dev/null @@ -1,10 +0,0 @@ -jaraco.text-3.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -jaraco.text-3.7.0.dist-info/LICENSE,sha256=2z8CRrH5J48VhFuZ_sR4uLUG63ZIeZNyL4xuJUKF-vg,1050 -jaraco.text-3.7.0.dist-info/METADATA,sha256=5mcR1dY0cJNrM-VIkAFkpjOgvgzmq6nM1GfD0gwTIhs,2136 -jaraco.text-3.7.0.dist-info/RECORD,, -jaraco.text-3.7.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -jaraco.text-3.7.0.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92 -jaraco.text-3.7.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 -jaraco/text/Lorem ipsum.txt,sha256=N_7c_79zxOufBY9HZ3yzMgOkNv-TkOTTio4BydrSjgs,1335 -jaraco/text/__init__.py,sha256=I56MW2ZFwPrYXIxzqxMBe2A1t-T4uZBgEgAKe9-JoqM,15538 -jaraco/text/__pycache__/__init__.cpython-311.pyc,, diff --git a/pkg_resources/_vendor/jaraco/__init__.py b/pkg_resources/_vendor/jaraco/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/pkg_resources/_vendor/jaraco/text/Lorem ipsum.txt b/pkg_resources/_vendor/jaraco/text/Lorem ipsum.txt deleted file mode 100644 index 986f944b60..0000000000 --- a/pkg_resources/_vendor/jaraco/text/Lorem ipsum.txt +++ /dev/null @@ -1,2 +0,0 @@ -Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. -Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. Integer in mauris eu nibh euismod gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue, eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis, neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, molestie eu, feugiat in, orci. In hac habitasse platea dictumst. diff --git a/pkg_resources/_vendor/jaraco/text/__init__.py b/pkg_resources/_vendor/jaraco/text/__init__.py deleted file mode 100644 index c466378ceb..0000000000 --- a/pkg_resources/_vendor/jaraco/text/__init__.py +++ /dev/null @@ -1,599 +0,0 @@ -import re -import itertools -import textwrap -import functools - -try: - from importlib.resources import files # type: ignore -except ImportError: # pragma: nocover - from pkg_resources.extern.importlib_resources import files # type: ignore - -from pkg_resources.extern.jaraco.functools import compose, method_cache -from pkg_resources.extern.jaraco.context import ExceptionTrap - - -def substitution(old, new): - """ - Return a function that will perform a substitution on a string - """ - return lambda s: s.replace(old, new) - - -def multi_substitution(*substitutions): - """ - Take a sequence of pairs specifying substitutions, and create - a function that performs those substitutions. - - >>> multi_substitution(('foo', 'bar'), ('bar', 'baz'))('foo') - 'baz' - """ - substitutions = itertools.starmap(substitution, substitutions) - # compose function applies last function first, so reverse the - # substitutions to get the expected order. - substitutions = reversed(tuple(substitutions)) - return compose(*substitutions) - - -class FoldedCase(str): - """ - A case insensitive string class; behaves just like str - except compares equal when the only variation is case. - - >>> s = FoldedCase('hello world') - - >>> s == 'Hello World' - True - - >>> 'Hello World' == s - True - - >>> s != 'Hello World' - False - - >>> s.index('O') - 4 - - >>> s.split('O') - ['hell', ' w', 'rld'] - - >>> sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta'])) - ['alpha', 'Beta', 'GAMMA'] - - Sequence membership is straightforward. - - >>> "Hello World" in [s] - True - >>> s in ["Hello World"] - True - - You may test for set inclusion, but candidate and elements - must both be folded. - - >>> FoldedCase("Hello World") in {s} - True - >>> s in {FoldedCase("Hello World")} - True - - String inclusion works as long as the FoldedCase object - is on the right. - - >>> "hello" in FoldedCase("Hello World") - True - - But not if the FoldedCase object is on the left: - - >>> FoldedCase('hello') in 'Hello World' - False - - In that case, use ``in_``: - - >>> FoldedCase('hello').in_('Hello World') - True - - >>> FoldedCase('hello') > FoldedCase('Hello') - False - """ - - def __lt__(self, other): - return self.lower() < other.lower() - - def __gt__(self, other): - return self.lower() > other.lower() - - def __eq__(self, other): - return self.lower() == other.lower() - - def __ne__(self, other): - return self.lower() != other.lower() - - def __hash__(self): - return hash(self.lower()) - - def __contains__(self, other): - return super().lower().__contains__(other.lower()) - - def in_(self, other): - "Does self appear in other?" - return self in FoldedCase(other) - - # cache lower since it's likely to be called frequently. - @method_cache - def lower(self): - return super().lower() - - def index(self, sub): - return self.lower().index(sub.lower()) - - def split(self, splitter=' ', maxsplit=0): - pattern = re.compile(re.escape(splitter), re.I) - return pattern.split(self, maxsplit) - - -# Python 3.8 compatibility -_unicode_trap = ExceptionTrap(UnicodeDecodeError) - - -@_unicode_trap.passes -def is_decodable(value): - r""" - Return True if the supplied value is decodable (using the default - encoding). - - >>> is_decodable(b'\xff') - False - >>> is_decodable(b'\x32') - True - """ - value.decode() - - -def is_binary(value): - r""" - Return True if the value appears to be binary (that is, it's a byte - string and isn't decodable). - - >>> is_binary(b'\xff') - True - >>> is_binary('\xff') - False - """ - return isinstance(value, bytes) and not is_decodable(value) - - -def trim(s): - r""" - Trim something like a docstring to remove the whitespace that - is common due to indentation and formatting. - - >>> trim("\n\tfoo = bar\n\t\tbar = baz\n") - 'foo = bar\n\tbar = baz' - """ - return textwrap.dedent(s).strip() - - -def wrap(s): - """ - Wrap lines of text, retaining existing newlines as - paragraph markers. - - >>> print(wrap(lorem_ipsum)) - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do - eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad - minim veniam, quis nostrud exercitation ullamco laboris nisi ut - aliquip ex ea commodo consequat. Duis aute irure dolor in - reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla - pariatur. Excepteur sint occaecat cupidatat non proident, sunt in - culpa qui officia deserunt mollit anim id est laborum. - - Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam - varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus - magna felis sollicitudin mauris. Integer in mauris eu nibh euismod - gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis - risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue, - eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas - fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla - a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis, - neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing - sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque - nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus - quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, - molestie eu, feugiat in, orci. In hac habitasse platea dictumst. - """ - paragraphs = s.splitlines() - wrapped = ('\n'.join(textwrap.wrap(para)) for para in paragraphs) - return '\n\n'.join(wrapped) - - -def unwrap(s): - r""" - Given a multi-line string, return an unwrapped version. - - >>> wrapped = wrap(lorem_ipsum) - >>> wrapped.count('\n') - 20 - >>> unwrapped = unwrap(wrapped) - >>> unwrapped.count('\n') - 1 - >>> print(unwrapped) - Lorem ipsum dolor sit amet, consectetur adipiscing ... - Curabitur pretium tincidunt lacus. Nulla gravida orci ... - - """ - paragraphs = re.split(r'\n\n+', s) - cleaned = (para.replace('\n', ' ') for para in paragraphs) - return '\n'.join(cleaned) - - - - -class Splitter(object): - """object that will split a string with the given arguments for each call - - >>> s = Splitter(',') - >>> s('hello, world, this is your, master calling') - ['hello', ' world', ' this is your', ' master calling'] - """ - - def __init__(self, *args): - self.args = args - - def __call__(self, s): - return s.split(*self.args) - - -def indent(string, prefix=' ' * 4): - """ - >>> indent('foo') - ' foo' - """ - return prefix + string - - -class WordSet(tuple): - """ - Given an identifier, return the words that identifier represents, - whether in camel case, underscore-separated, etc. - - >>> WordSet.parse("camelCase") - ('camel', 'Case') - - >>> WordSet.parse("under_sep") - ('under', 'sep') - - Acronyms should be retained - - >>> WordSet.parse("firstSNL") - ('first', 'SNL') - - >>> WordSet.parse("you_and_I") - ('you', 'and', 'I') - - >>> WordSet.parse("A simple test") - ('A', 'simple', 'test') - - Multiple caps should not interfere with the first cap of another word. - - >>> WordSet.parse("myABCClass") - ('my', 'ABC', 'Class') - - The result is a WordSet, so you can get the form you need. - - >>> WordSet.parse("myABCClass").underscore_separated() - 'my_ABC_Class' - - >>> WordSet.parse('a-command').camel_case() - 'ACommand' - - >>> WordSet.parse('someIdentifier').lowered().space_separated() - 'some identifier' - - Slices of the result should return another WordSet. - - >>> WordSet.parse('taken-out-of-context')[1:].underscore_separated() - 'out_of_context' - - >>> WordSet.from_class_name(WordSet()).lowered().space_separated() - 'word set' - - >>> example = WordSet.parse('figured it out') - >>> example.headless_camel_case() - 'figuredItOut' - >>> example.dash_separated() - 'figured-it-out' - - """ - - _pattern = re.compile('([A-Z]?[a-z]+)|([A-Z]+(?![a-z]))') - - def capitalized(self): - return WordSet(word.capitalize() for word in self) - - def lowered(self): - return WordSet(word.lower() for word in self) - - def camel_case(self): - return ''.join(self.capitalized()) - - def headless_camel_case(self): - words = iter(self) - first = next(words).lower() - new_words = itertools.chain((first,), WordSet(words).camel_case()) - return ''.join(new_words) - - def underscore_separated(self): - return '_'.join(self) - - def dash_separated(self): - return '-'.join(self) - - def space_separated(self): - return ' '.join(self) - - def trim_right(self, item): - """ - Remove the item from the end of the set. - - >>> WordSet.parse('foo bar').trim_right('foo') - ('foo', 'bar') - >>> WordSet.parse('foo bar').trim_right('bar') - ('foo',) - >>> WordSet.parse('').trim_right('bar') - () - """ - return self[:-1] if self and self[-1] == item else self - - def trim_left(self, item): - """ - Remove the item from the beginning of the set. - - >>> WordSet.parse('foo bar').trim_left('foo') - ('bar',) - >>> WordSet.parse('foo bar').trim_left('bar') - ('foo', 'bar') - >>> WordSet.parse('').trim_left('bar') - () - """ - return self[1:] if self and self[0] == item else self - - def trim(self, item): - """ - >>> WordSet.parse('foo bar').trim('foo') - ('bar',) - """ - return self.trim_left(item).trim_right(item) - - def __getitem__(self, item): - result = super(WordSet, self).__getitem__(item) - if isinstance(item, slice): - result = WordSet(result) - return result - - @classmethod - def parse(cls, identifier): - matches = cls._pattern.finditer(identifier) - return WordSet(match.group(0) for match in matches) - - @classmethod - def from_class_name(cls, subject): - return cls.parse(subject.__class__.__name__) - - -# for backward compatibility -words = WordSet.parse - - -def simple_html_strip(s): - r""" - Remove HTML from the string `s`. - - >>> str(simple_html_strip('')) - '' - - >>> print(simple_html_strip('A stormy day in paradise')) - A stormy day in paradise - - >>> print(simple_html_strip('Somebody tell the truth.')) - Somebody tell the truth. - - >>> print(simple_html_strip('What about
\nmultiple lines?')) - What about - multiple lines? - """ - html_stripper = re.compile('()|(<[^>]*>)|([^<]+)', re.DOTALL) - texts = (match.group(3) or '' for match in html_stripper.finditer(s)) - return ''.join(texts) - - -class SeparatedValues(str): - """ - A string separated by a separator. Overrides __iter__ for getting - the values. - - >>> list(SeparatedValues('a,b,c')) - ['a', 'b', 'c'] - - Whitespace is stripped and empty values are discarded. - - >>> list(SeparatedValues(' a, b , c, ')) - ['a', 'b', 'c'] - """ - - separator = ',' - - def __iter__(self): - parts = self.split(self.separator) - return filter(None, (part.strip() for part in parts)) - - -class Stripper: - r""" - Given a series of lines, find the common prefix and strip it from them. - - >>> lines = [ - ... 'abcdefg\n', - ... 'abc\n', - ... 'abcde\n', - ... ] - >>> res = Stripper.strip_prefix(lines) - >>> res.prefix - 'abc' - >>> list(res.lines) - ['defg\n', '\n', 'de\n'] - - If no prefix is common, nothing should be stripped. - - >>> lines = [ - ... 'abcd\n', - ... '1234\n', - ... ] - >>> res = Stripper.strip_prefix(lines) - >>> res.prefix = '' - >>> list(res.lines) - ['abcd\n', '1234\n'] - """ - - def __init__(self, prefix, lines): - self.prefix = prefix - self.lines = map(self, lines) - - @classmethod - def strip_prefix(cls, lines): - prefix_lines, lines = itertools.tee(lines) - prefix = functools.reduce(cls.common_prefix, prefix_lines) - return cls(prefix, lines) - - def __call__(self, line): - if not self.prefix: - return line - null, prefix, rest = line.partition(self.prefix) - return rest - - @staticmethod - def common_prefix(s1, s2): - """ - Return the common prefix of two lines. - """ - index = min(len(s1), len(s2)) - while s1[:index] != s2[:index]: - index -= 1 - return s1[:index] - - -def remove_prefix(text, prefix): - """ - Remove the prefix from the text if it exists. - - >>> remove_prefix('underwhelming performance', 'underwhelming ') - 'performance' - - >>> remove_prefix('something special', 'sample') - 'something special' - """ - null, prefix, rest = text.rpartition(prefix) - return rest - - -def remove_suffix(text, suffix): - """ - Remove the suffix from the text if it exists. - - >>> remove_suffix('name.git', '.git') - 'name' - - >>> remove_suffix('something special', 'sample') - 'something special' - """ - rest, suffix, null = text.partition(suffix) - return rest - - -def normalize_newlines(text): - r""" - Replace alternate newlines with the canonical newline. - - >>> normalize_newlines('Lorem Ipsum\u2029') - 'Lorem Ipsum\n' - >>> normalize_newlines('Lorem Ipsum\r\n') - 'Lorem Ipsum\n' - >>> normalize_newlines('Lorem Ipsum\x85') - 'Lorem Ipsum\n' - """ - newlines = ['\r\n', '\r', '\n', '\u0085', '\u2028', '\u2029'] - pattern = '|'.join(newlines) - return re.sub(pattern, '\n', text) - - -def _nonblank(str): - return str and not str.startswith('#') - - -@functools.singledispatch -def yield_lines(iterable): - r""" - Yield valid lines of a string or iterable. - - >>> list(yield_lines('')) - [] - >>> list(yield_lines(['foo', 'bar'])) - ['foo', 'bar'] - >>> list(yield_lines('foo\nbar')) - ['foo', 'bar'] - >>> list(yield_lines('\nfoo\n#bar\nbaz #comment')) - ['foo', 'baz #comment'] - >>> list(yield_lines(['foo\nbar', 'baz', 'bing\n\n\n'])) - ['foo', 'bar', 'baz', 'bing'] - """ - return itertools.chain.from_iterable(map(yield_lines, iterable)) - - -@yield_lines.register(str) -def _(text): - return filter(_nonblank, map(str.strip, text.splitlines())) - - -def drop_comment(line): - """ - Drop comments. - - >>> drop_comment('foo # bar') - 'foo' - - A hash without a space may be in a URL. - - >>> drop_comment('http://example.com/foo#bar') - 'http://example.com/foo#bar' - """ - return line.partition(' #')[0] - - -def join_continuation(lines): - r""" - Join lines continued by a trailing backslash. - - >>> list(join_continuation(['foo \\', 'bar', 'baz'])) - ['foobar', 'baz'] - >>> list(join_continuation(['foo \\', 'bar', 'baz'])) - ['foobar', 'baz'] - >>> list(join_continuation(['foo \\', 'bar \\', 'baz'])) - ['foobarbaz'] - - Not sure why, but... - The character preceeding the backslash is also elided. - - >>> list(join_continuation(['goo\\', 'dly'])) - ['godly'] - - A terrible idea, but... - If no line is available to continue, suppress the lines. - - >>> list(join_continuation(['foo', 'bar\\', 'baz\\'])) - ['foo'] - """ - lines = iter(lines) - for item in lines: - while item.endswith('\\'): - try: - item = item[:-2].strip() + next(lines) - except StopIteration: - return - yield item diff --git a/pkg_resources/_vendor/more_itertools-9.1.0.dist-info/INSTALLER b/pkg_resources/_vendor/more_itertools-9.1.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a..0000000000 --- a/pkg_resources/_vendor/more_itertools-9.1.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/pkg_resources/_vendor/more_itertools-9.1.0.dist-info/RECORD b/pkg_resources/_vendor/more_itertools-9.1.0.dist-info/RECORD deleted file mode 100644 index c2fd4da0ac..0000000000 --- a/pkg_resources/_vendor/more_itertools-9.1.0.dist-info/RECORD +++ /dev/null @@ -1,15 +0,0 @@ -more_itertools-9.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -more_itertools-9.1.0.dist-info/LICENSE,sha256=CfHIyelBrz5YTVlkHqm4fYPAyw_QB-te85Gn4mQ8GkY,1053 -more_itertools-9.1.0.dist-info/METADATA,sha256=qP4FQl-r_CTDFj9wwQAf_KrRs4u_HZBIeyc2WCLW69c,32271 -more_itertools-9.1.0.dist-info/RECORD,, -more_itertools-9.1.0.dist-info/WHEEL,sha256=rSgq_JpHF9fHR1lx53qwg_1-2LypZE_qmcuXbVUq948,81 -more_itertools/__init__.py,sha256=mTzXsWGDHiVW5x8zHzcRu1imUMzrEtJnUhfsN-dBrV4,148 -more_itertools/__init__.pyi,sha256=5B3eTzON1BBuOLob1vCflyEb2lSd6usXQQ-Cv-hXkeA,43 -more_itertools/__pycache__/__init__.cpython-311.pyc,, -more_itertools/__pycache__/more.cpython-311.pyc,, -more_itertools/__pycache__/recipes.cpython-311.pyc,, -more_itertools/more.py,sha256=YlrEMtcLMdcmcwL-T9YIQvMKjrAomEDbvQxQd4i5LnA,134968 -more_itertools/more.pyi,sha256=tZNfrCeIQLfOYhRyp0Wq7no_ryJ5h3FDskNNUBD-zmU,20105 -more_itertools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -more_itertools/recipes.py,sha256=lgw5bP3UoNfvUPhRaz1VIAfRFkF9pKWN-8UB6H0W5Eo,25416 -more_itertools/recipes.pyi,sha256=Um3BGANEFi4papnQfKBJnlEEuSpXS8-nbxro8OyuOt8,4056 diff --git a/pkg_resources/_vendor/more_itertools/__init__.py b/pkg_resources/_vendor/more_itertools/__init__.py deleted file mode 100644 index 66443971df..0000000000 --- a/pkg_resources/_vendor/more_itertools/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -"""More routines for operating on iterables, beyond itertools""" - -from .more import * # noqa -from .recipes import * # noqa - -__version__ = '9.1.0' diff --git a/pkg_resources/_vendor/more_itertools/__init__.pyi b/pkg_resources/_vendor/more_itertools/__init__.pyi deleted file mode 100644 index 96f6e36c7f..0000000000 --- a/pkg_resources/_vendor/more_itertools/__init__.pyi +++ /dev/null @@ -1,2 +0,0 @@ -from .more import * -from .recipes import * diff --git a/pkg_resources/_vendor/more_itertools/more.py b/pkg_resources/_vendor/more_itertools/more.py deleted file mode 100755 index e0e2d3de92..0000000000 --- a/pkg_resources/_vendor/more_itertools/more.py +++ /dev/null @@ -1,4391 +0,0 @@ -import warnings - -from collections import Counter, defaultdict, deque, abc -from collections.abc import Sequence -from functools import partial, reduce, wraps -from heapq import heapify, heapreplace, heappop -from itertools import ( - chain, - compress, - count, - cycle, - dropwhile, - groupby, - islice, - repeat, - starmap, - takewhile, - tee, - zip_longest, -) -from math import exp, factorial, floor, log -from queue import Empty, Queue -from random import random, randrange, uniform -from operator import itemgetter, mul, sub, gt, lt, ge, le -from sys import hexversion, maxsize -from time import monotonic - -from .recipes import ( - _marker, - _zip_equal, - UnequalIterablesError, - consume, - flatten, - pairwise, - powerset, - take, - unique_everseen, - all_equal, -) - -__all__ = [ - 'AbortThread', - 'SequenceView', - 'UnequalIterablesError', - 'adjacent', - 'all_unique', - 'always_iterable', - 'always_reversible', - 'bucket', - 'callback_iter', - 'chunked', - 'chunked_even', - 'circular_shifts', - 'collapse', - 'combination_index', - 'consecutive_groups', - 'constrained_batches', - 'consumer', - 'count_cycle', - 'countable', - 'difference', - 'distinct_combinations', - 'distinct_permutations', - 'distribute', - 'divide', - 'duplicates_everseen', - 'duplicates_justseen', - 'exactly_n', - 'filter_except', - 'first', - 'gray_product', - 'groupby_transform', - 'ichunked', - 'iequals', - 'ilen', - 'interleave', - 'interleave_evenly', - 'interleave_longest', - 'intersperse', - 'is_sorted', - 'islice_extended', - 'iterate', - 'last', - 'locate', - 'longest_common_prefix', - 'lstrip', - 'make_decorator', - 'map_except', - 'map_if', - 'map_reduce', - 'mark_ends', - 'minmax', - 'nth_or_last', - 'nth_permutation', - 'nth_product', - 'numeric_range', - 'one', - 'only', - 'padded', - 'partitions', - 'peekable', - 'permutation_index', - 'product_index', - 'raise_', - 'repeat_each', - 'repeat_last', - 'replace', - 'rlocate', - 'rstrip', - 'run_length', - 'sample', - 'seekable', - 'set_partitions', - 'side_effect', - 'sliced', - 'sort_together', - 'split_after', - 'split_at', - 'split_before', - 'split_into', - 'split_when', - 'spy', - 'stagger', - 'strip', - 'strictly_n', - 'substrings', - 'substrings_indexes', - 'time_limited', - 'unique_in_window', - 'unique_to_each', - 'unzip', - 'value_chain', - 'windowed', - 'windowed_complete', - 'with_iter', - 'zip_broadcast', - 'zip_equal', - 'zip_offset', -] - - -def chunked(iterable, n, strict=False): - """Break *iterable* into lists of length *n*: - - >>> list(chunked([1, 2, 3, 4, 5, 6], 3)) - [[1, 2, 3], [4, 5, 6]] - - By the default, the last yielded list will have fewer than *n* elements - if the length of *iterable* is not divisible by *n*: - - >>> list(chunked([1, 2, 3, 4, 5, 6, 7, 8], 3)) - [[1, 2, 3], [4, 5, 6], [7, 8]] - - To use a fill-in value instead, see the :func:`grouper` recipe. - - If the length of *iterable* is not divisible by *n* and *strict* is - ``True``, then ``ValueError`` will be raised before the last - list is yielded. - - """ - iterator = iter(partial(take, n, iter(iterable)), []) - if strict: - if n is None: - raise ValueError('n must not be None when using strict mode.') - - def ret(): - for chunk in iterator: - if len(chunk) != n: - raise ValueError('iterable is not divisible by n.') - yield chunk - - return iter(ret()) - else: - return iterator - - -def first(iterable, default=_marker): - """Return the first item of *iterable*, or *default* if *iterable* is - empty. - - >>> first([0, 1, 2, 3]) - 0 - >>> first([], 'some default') - 'some default' - - If *default* is not provided and there are no items in the iterable, - raise ``ValueError``. - - :func:`first` is useful when you have a generator of expensive-to-retrieve - values and want any arbitrary one. It is marginally shorter than - ``next(iter(iterable), default)``. - - """ - try: - return next(iter(iterable)) - except StopIteration as e: - if default is _marker: - raise ValueError( - 'first() was called on an empty iterable, and no ' - 'default value was provided.' - ) from e - return default - - -def last(iterable, default=_marker): - """Return the last item of *iterable*, or *default* if *iterable* is - empty. - - >>> last([0, 1, 2, 3]) - 3 - >>> last([], 'some default') - 'some default' - - If *default* is not provided and there are no items in the iterable, - raise ``ValueError``. - """ - try: - if isinstance(iterable, Sequence): - return iterable[-1] - # Work around https://bugs.python.org/issue38525 - elif hasattr(iterable, '__reversed__') and (hexversion != 0x030800F0): - return next(reversed(iterable)) - else: - return deque(iterable, maxlen=1)[-1] - except (IndexError, TypeError, StopIteration): - if default is _marker: - raise ValueError( - 'last() was called on an empty iterable, and no default was ' - 'provided.' - ) - return default - - -def nth_or_last(iterable, n, default=_marker): - """Return the nth or the last item of *iterable*, - or *default* if *iterable* is empty. - - >>> nth_or_last([0, 1, 2, 3], 2) - 2 - >>> nth_or_last([0, 1], 2) - 1 - >>> nth_or_last([], 0, 'some default') - 'some default' - - If *default* is not provided and there are no items in the iterable, - raise ``ValueError``. - """ - return last(islice(iterable, n + 1), default=default) - - -class peekable: - """Wrap an iterator to allow lookahead and prepending elements. - - Call :meth:`peek` on the result to get the value that will be returned - by :func:`next`. This won't advance the iterator: - - >>> p = peekable(['a', 'b']) - >>> p.peek() - 'a' - >>> next(p) - 'a' - - Pass :meth:`peek` a default value to return that instead of raising - ``StopIteration`` when the iterator is exhausted. - - >>> p = peekable([]) - >>> p.peek('hi') - 'hi' - - peekables also offer a :meth:`prepend` method, which "inserts" items - at the head of the iterable: - - >>> p = peekable([1, 2, 3]) - >>> p.prepend(10, 11, 12) - >>> next(p) - 10 - >>> p.peek() - 11 - >>> list(p) - [11, 12, 1, 2, 3] - - peekables can be indexed. Index 0 is the item that will be returned by - :func:`next`, index 1 is the item after that, and so on: - The values up to the given index will be cached. - - >>> p = peekable(['a', 'b', 'c', 'd']) - >>> p[0] - 'a' - >>> p[1] - 'b' - >>> next(p) - 'a' - - Negative indexes are supported, but be aware that they will cache the - remaining items in the source iterator, which may require significant - storage. - - To check whether a peekable is exhausted, check its truth value: - - >>> p = peekable(['a', 'b']) - >>> if p: # peekable has items - ... list(p) - ['a', 'b'] - >>> if not p: # peekable is exhausted - ... list(p) - [] - - """ - - def __init__(self, iterable): - self._it = iter(iterable) - self._cache = deque() - - def __iter__(self): - return self - - def __bool__(self): - try: - self.peek() - except StopIteration: - return False - return True - - def peek(self, default=_marker): - """Return the item that will be next returned from ``next()``. - - Return ``default`` if there are no items left. If ``default`` is not - provided, raise ``StopIteration``. - - """ - if not self._cache: - try: - self._cache.append(next(self._it)) - except StopIteration: - if default is _marker: - raise - return default - return self._cache[0] - - def prepend(self, *items): - """Stack up items to be the next ones returned from ``next()`` or - ``self.peek()``. The items will be returned in - first in, first out order:: - - >>> p = peekable([1, 2, 3]) - >>> p.prepend(10, 11, 12) - >>> next(p) - 10 - >>> list(p) - [11, 12, 1, 2, 3] - - It is possible, by prepending items, to "resurrect" a peekable that - previously raised ``StopIteration``. - - >>> p = peekable([]) - >>> next(p) - Traceback (most recent call last): - ... - StopIteration - >>> p.prepend(1) - >>> next(p) - 1 - >>> next(p) - Traceback (most recent call last): - ... - StopIteration - - """ - self._cache.extendleft(reversed(items)) - - def __next__(self): - if self._cache: - return self._cache.popleft() - - return next(self._it) - - def _get_slice(self, index): - # Normalize the slice's arguments - step = 1 if (index.step is None) else index.step - if step > 0: - start = 0 if (index.start is None) else index.start - stop = maxsize if (index.stop is None) else index.stop - elif step < 0: - start = -1 if (index.start is None) else index.start - stop = (-maxsize - 1) if (index.stop is None) else index.stop - else: - raise ValueError('slice step cannot be zero') - - # If either the start or stop index is negative, we'll need to cache - # the rest of the iterable in order to slice from the right side. - if (start < 0) or (stop < 0): - self._cache.extend(self._it) - # Otherwise we'll need to find the rightmost index and cache to that - # point. - else: - n = min(max(start, stop) + 1, maxsize) - cache_len = len(self._cache) - if n >= cache_len: - self._cache.extend(islice(self._it, n - cache_len)) - - return list(self._cache)[index] - - def __getitem__(self, index): - if isinstance(index, slice): - return self._get_slice(index) - - cache_len = len(self._cache) - if index < 0: - self._cache.extend(self._it) - elif index >= cache_len: - self._cache.extend(islice(self._it, index + 1 - cache_len)) - - return self._cache[index] - - -def consumer(func): - """Decorator that automatically advances a PEP-342-style "reverse iterator" - to its first yield point so you don't have to call ``next()`` on it - manually. - - >>> @consumer - ... def tally(): - ... i = 0 - ... while True: - ... print('Thing number %s is %s.' % (i, (yield))) - ... i += 1 - ... - >>> t = tally() - >>> t.send('red') - Thing number 0 is red. - >>> t.send('fish') - Thing number 1 is fish. - - Without the decorator, you would have to call ``next(t)`` before - ``t.send()`` could be used. - - """ - - @wraps(func) - def wrapper(*args, **kwargs): - gen = func(*args, **kwargs) - next(gen) - return gen - - return wrapper - - -def ilen(iterable): - """Return the number of items in *iterable*. - - >>> ilen(x for x in range(1000000) if x % 3 == 0) - 333334 - - This consumes the iterable, so handle with care. - - """ - # This approach was selected because benchmarks showed it's likely the - # fastest of the known implementations at the time of writing. - # See GitHub tracker: #236, #230. - counter = count() - deque(zip(iterable, counter), maxlen=0) - return next(counter) - - -def iterate(func, start): - """Return ``start``, ``func(start)``, ``func(func(start))``, ... - - >>> from itertools import islice - >>> list(islice(iterate(lambda x: 2*x, 1), 10)) - [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] - - """ - while True: - yield start - start = func(start) - - -def with_iter(context_manager): - """Wrap an iterable in a ``with`` statement, so it closes once exhausted. - - For example, this will close the file when the iterator is exhausted:: - - upper_lines = (line.upper() for line in with_iter(open('foo'))) - - Any context manager which returns an iterable is a candidate for - ``with_iter``. - - """ - with context_manager as iterable: - yield from iterable - - -def one(iterable, too_short=None, too_long=None): - """Return the first item from *iterable*, which is expected to contain only - that item. Raise an exception if *iterable* is empty or has more than one - item. - - :func:`one` is useful for ensuring that an iterable contains only one item. - For example, it can be used to retrieve the result of a database query - that is expected to return a single row. - - If *iterable* is empty, ``ValueError`` will be raised. You may specify a - different exception with the *too_short* keyword: - - >>> it = [] - >>> one(it) # doctest: +IGNORE_EXCEPTION_DETAIL - Traceback (most recent call last): - ... - ValueError: too many items in iterable (expected 1)' - >>> too_short = IndexError('too few items') - >>> one(it, too_short=too_short) # doctest: +IGNORE_EXCEPTION_DETAIL - Traceback (most recent call last): - ... - IndexError: too few items - - Similarly, if *iterable* contains more than one item, ``ValueError`` will - be raised. You may specify a different exception with the *too_long* - keyword: - - >>> it = ['too', 'many'] - >>> one(it) # doctest: +IGNORE_EXCEPTION_DETAIL - Traceback (most recent call last): - ... - ValueError: Expected exactly one item in iterable, but got 'too', - 'many', and perhaps more. - >>> too_long = RuntimeError - >>> one(it, too_long=too_long) # doctest: +IGNORE_EXCEPTION_DETAIL - Traceback (most recent call last): - ... - RuntimeError - - Note that :func:`one` attempts to advance *iterable* twice to ensure there - is only one item. See :func:`spy` or :func:`peekable` to check iterable - contents less destructively. - - """ - it = iter(iterable) - - try: - first_value = next(it) - except StopIteration as e: - raise ( - too_short or ValueError('too few items in iterable (expected 1)') - ) from e - - try: - second_value = next(it) - except StopIteration: - pass - else: - msg = ( - 'Expected exactly one item in iterable, but got {!r}, {!r}, ' - 'and perhaps more.'.format(first_value, second_value) - ) - raise too_long or ValueError(msg) - - return first_value - - -def raise_(exception, *args): - raise exception(*args) - - -def strictly_n(iterable, n, too_short=None, too_long=None): - """Validate that *iterable* has exactly *n* items and return them if - it does. If it has fewer than *n* items, call function *too_short* - with those items. If it has more than *n* items, call function - *too_long* with the first ``n + 1`` items. - - >>> iterable = ['a', 'b', 'c', 'd'] - >>> n = 4 - >>> list(strictly_n(iterable, n)) - ['a', 'b', 'c', 'd'] - - By default, *too_short* and *too_long* are functions that raise - ``ValueError``. - - >>> list(strictly_n('ab', 3)) # doctest: +IGNORE_EXCEPTION_DETAIL - Traceback (most recent call last): - ... - ValueError: too few items in iterable (got 2) - - >>> list(strictly_n('abc', 2)) # doctest: +IGNORE_EXCEPTION_DETAIL - Traceback (most recent call last): - ... - ValueError: too many items in iterable (got at least 3) - - You can instead supply functions that do something else. - *too_short* will be called with the number of items in *iterable*. - *too_long* will be called with `n + 1`. - - >>> def too_short(item_count): - ... raise RuntimeError - >>> it = strictly_n('abcd', 6, too_short=too_short) - >>> list(it) # doctest: +IGNORE_EXCEPTION_DETAIL - Traceback (most recent call last): - ... - RuntimeError - - >>> def too_long(item_count): - ... print('The boss is going to hear about this') - >>> it = strictly_n('abcdef', 4, too_long=too_long) - >>> list(it) - The boss is going to hear about this - ['a', 'b', 'c', 'd'] - - """ - if too_short is None: - too_short = lambda item_count: raise_( - ValueError, - 'Too few items in iterable (got {})'.format(item_count), - ) - - if too_long is None: - too_long = lambda item_count: raise_( - ValueError, - 'Too many items in iterable (got at least {})'.format(item_count), - ) - - it = iter(iterable) - for i in range(n): - try: - item = next(it) - except StopIteration: - too_short(i) - return - else: - yield item - - try: - next(it) - except StopIteration: - pass - else: - too_long(n + 1) - - -def distinct_permutations(iterable, r=None): - """Yield successive distinct permutations of the elements in *iterable*. - - >>> sorted(distinct_permutations([1, 0, 1])) - [(0, 1, 1), (1, 0, 1), (1, 1, 0)] - - Equivalent to ``set(permutations(iterable))``, except duplicates are not - generated and thrown away. For larger input sequences this is much more - efficient. - - Duplicate permutations arise when there are duplicated elements in the - input iterable. The number of items returned is - `n! / (x_1! * x_2! * ... * x_n!)`, where `n` is the total number of - items input, and each `x_i` is the count of a distinct item in the input - sequence. - - If *r* is given, only the *r*-length permutations are yielded. - - >>> sorted(distinct_permutations([1, 0, 1], r=2)) - [(0, 1), (1, 0), (1, 1)] - >>> sorted(distinct_permutations(range(3), r=2)) - [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] - - """ - - # Algorithm: https://w.wiki/Qai - def _full(A): - while True: - # Yield the permutation we have - yield tuple(A) - - # Find the largest index i such that A[i] < A[i + 1] - for i in range(size - 2, -1, -1): - if A[i] < A[i + 1]: - break - # If no such index exists, this permutation is the last one - else: - return - - # Find the largest index j greater than j such that A[i] < A[j] - for j in range(size - 1, i, -1): - if A[i] < A[j]: - break - - # Swap the value of A[i] with that of A[j], then reverse the - # sequence from A[i + 1] to form the new permutation - A[i], A[j] = A[j], A[i] - A[i + 1 :] = A[: i - size : -1] # A[i + 1:][::-1] - - # Algorithm: modified from the above - def _partial(A, r): - # Split A into the first r items and the last r items - head, tail = A[:r], A[r:] - right_head_indexes = range(r - 1, -1, -1) - left_tail_indexes = range(len(tail)) - - while True: - # Yield the permutation we have - yield tuple(head) - - # Starting from the right, find the first index of the head with - # value smaller than the maximum value of the tail - call it i. - pivot = tail[-1] - for i in right_head_indexes: - if head[i] < pivot: - break - pivot = head[i] - else: - return - - # Starting from the left, find the first value of the tail - # with a value greater than head[i] and swap. - for j in left_tail_indexes: - if tail[j] > head[i]: - head[i], tail[j] = tail[j], head[i] - break - # If we didn't find one, start from the right and find the first - # index of the head with a value greater than head[i] and swap. - else: - for j in right_head_indexes: - if head[j] > head[i]: - head[i], head[j] = head[j], head[i] - break - - # Reverse head[i + 1:] and swap it with tail[:r - (i + 1)] - tail += head[: i - r : -1] # head[i + 1:][::-1] - i += 1 - head[i:], tail[:] = tail[: r - i], tail[r - i :] - - items = sorted(iterable) - - size = len(items) - if r is None: - r = size - - if 0 < r <= size: - return _full(items) if (r == size) else _partial(items, r) - - return iter(() if r else ((),)) - - -def intersperse(e, iterable, n=1): - """Intersperse filler element *e* among the items in *iterable*, leaving - *n* items between each filler element. - - >>> list(intersperse('!', [1, 2, 3, 4, 5])) - [1, '!', 2, '!', 3, '!', 4, '!', 5] - - >>> list(intersperse(None, [1, 2, 3, 4, 5], n=2)) - [1, 2, None, 3, 4, None, 5] - - """ - if n == 0: - raise ValueError('n must be > 0') - elif n == 1: - # interleave(repeat(e), iterable) -> e, x_0, e, x_1, e, x_2... - # islice(..., 1, None) -> x_0, e, x_1, e, x_2... - return islice(interleave(repeat(e), iterable), 1, None) - else: - # interleave(filler, chunks) -> [e], [x_0, x_1], [e], [x_2, x_3]... - # islice(..., 1, None) -> [x_0, x_1], [e], [x_2, x_3]... - # flatten(...) -> x_0, x_1, e, x_2, x_3... - filler = repeat([e]) - chunks = chunked(iterable, n) - return flatten(islice(interleave(filler, chunks), 1, None)) - - -def unique_to_each(*iterables): - """Return the elements from each of the input iterables that aren't in the - other input iterables. - - For example, suppose you have a set of packages, each with a set of - dependencies:: - - {'pkg_1': {'A', 'B'}, 'pkg_2': {'B', 'C'}, 'pkg_3': {'B', 'D'}} - - If you remove one package, which dependencies can also be removed? - - If ``pkg_1`` is removed, then ``A`` is no longer necessary - it is not - associated with ``pkg_2`` or ``pkg_3``. Similarly, ``C`` is only needed for - ``pkg_2``, and ``D`` is only needed for ``pkg_3``:: - - >>> unique_to_each({'A', 'B'}, {'B', 'C'}, {'B', 'D'}) - [['A'], ['C'], ['D']] - - If there are duplicates in one input iterable that aren't in the others - they will be duplicated in the output. Input order is preserved:: - - >>> unique_to_each("mississippi", "missouri") - [['p', 'p'], ['o', 'u', 'r']] - - It is assumed that the elements of each iterable are hashable. - - """ - pool = [list(it) for it in iterables] - counts = Counter(chain.from_iterable(map(set, pool))) - uniques = {element for element in counts if counts[element] == 1} - return [list(filter(uniques.__contains__, it)) for it in pool] - - -def windowed(seq, n, fillvalue=None, step=1): - """Return a sliding window of width *n* over the given iterable. - - >>> all_windows = windowed([1, 2, 3, 4, 5], 3) - >>> list(all_windows) - [(1, 2, 3), (2, 3, 4), (3, 4, 5)] - - When the window is larger than the iterable, *fillvalue* is used in place - of missing values: - - >>> list(windowed([1, 2, 3], 4)) - [(1, 2, 3, None)] - - Each window will advance in increments of *step*: - - >>> list(windowed([1, 2, 3, 4, 5, 6], 3, fillvalue='!', step=2)) - [(1, 2, 3), (3, 4, 5), (5, 6, '!')] - - To slide into the iterable's items, use :func:`chain` to add filler items - to the left: - - >>> iterable = [1, 2, 3, 4] - >>> n = 3 - >>> padding = [None] * (n - 1) - >>> list(windowed(chain(padding, iterable), 3)) - [(None, None, 1), (None, 1, 2), (1, 2, 3), (2, 3, 4)] - """ - if n < 0: - raise ValueError('n must be >= 0') - if n == 0: - yield tuple() - return - if step < 1: - raise ValueError('step must be >= 1') - - window = deque(maxlen=n) - i = n - for _ in map(window.append, seq): - i -= 1 - if not i: - i = step - yield tuple(window) - - size = len(window) - if size == 0: - return - elif size < n: - yield tuple(chain(window, repeat(fillvalue, n - size))) - elif 0 < i < min(step, n): - window += (fillvalue,) * i - yield tuple(window) - - -def substrings(iterable): - """Yield all of the substrings of *iterable*. - - >>> [''.join(s) for s in substrings('more')] - ['m', 'o', 'r', 'e', 'mo', 'or', 're', 'mor', 'ore', 'more'] - - Note that non-string iterables can also be subdivided. - - >>> list(substrings([0, 1, 2])) - [(0,), (1,), (2,), (0, 1), (1, 2), (0, 1, 2)] - - """ - # The length-1 substrings - seq = [] - for item in iter(iterable): - seq.append(item) - yield (item,) - seq = tuple(seq) - item_count = len(seq) - - # And the rest - for n in range(2, item_count + 1): - for i in range(item_count - n + 1): - yield seq[i : i + n] - - -def substrings_indexes(seq, reverse=False): - """Yield all substrings and their positions in *seq* - - The items yielded will be a tuple of the form ``(substr, i, j)``, where - ``substr == seq[i:j]``. - - This function only works for iterables that support slicing, such as - ``str`` objects. - - >>> for item in substrings_indexes('more'): - ... print(item) - ('m', 0, 1) - ('o', 1, 2) - ('r', 2, 3) - ('e', 3, 4) - ('mo', 0, 2) - ('or', 1, 3) - ('re', 2, 4) - ('mor', 0, 3) - ('ore', 1, 4) - ('more', 0, 4) - - Set *reverse* to ``True`` to yield the same items in the opposite order. - - - """ - r = range(1, len(seq) + 1) - if reverse: - r = reversed(r) - return ( - (seq[i : i + L], i, i + L) for L in r for i in range(len(seq) - L + 1) - ) - - -class bucket: - """Wrap *iterable* and return an object that buckets it iterable into - child iterables based on a *key* function. - - >>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3'] - >>> s = bucket(iterable, key=lambda x: x[0]) # Bucket by 1st character - >>> sorted(list(s)) # Get the keys - ['a', 'b', 'c'] - >>> a_iterable = s['a'] - >>> next(a_iterable) - 'a1' - >>> next(a_iterable) - 'a2' - >>> list(s['b']) - ['b1', 'b2', 'b3'] - - The original iterable will be advanced and its items will be cached until - they are used by the child iterables. This may require significant storage. - - By default, attempting to select a bucket to which no items belong will - exhaust the iterable and cache all values. - If you specify a *validator* function, selected buckets will instead be - checked against it. - - >>> from itertools import count - >>> it = count(1, 2) # Infinite sequence of odd numbers - >>> key = lambda x: x % 10 # Bucket by last digit - >>> validator = lambda x: x in {1, 3, 5, 7, 9} # Odd digits only - >>> s = bucket(it, key=key, validator=validator) - >>> 2 in s - False - >>> list(s[2]) - [] - - """ - - def __init__(self, iterable, key, validator=None): - self._it = iter(iterable) - self._key = key - self._cache = defaultdict(deque) - self._validator = validator or (lambda x: True) - - def __contains__(self, value): - if not self._validator(value): - return False - - try: - item = next(self[value]) - except StopIteration: - return False - else: - self._cache[value].appendleft(item) - - return True - - def _get_values(self, value): - """ - Helper to yield items from the parent iterator that match *value*. - Items that don't match are stored in the local cache as they - are encountered. - """ - while True: - # If we've cached some items that match the target value, emit - # the first one and evict it from the cache. - if self._cache[value]: - yield self._cache[value].popleft() - # Otherwise we need to advance the parent iterator to search for - # a matching item, caching the rest. - else: - while True: - try: - item = next(self._it) - except StopIteration: - return - item_value = self._key(item) - if item_value == value: - yield item - break - elif self._validator(item_value): - self._cache[item_value].append(item) - - def __iter__(self): - for item in self._it: - item_value = self._key(item) - if self._validator(item_value): - self._cache[item_value].append(item) - - yield from self._cache.keys() - - def __getitem__(self, value): - if not self._validator(value): - return iter(()) - - return self._get_values(value) - - -def spy(iterable, n=1): - """Return a 2-tuple with a list containing the first *n* elements of - *iterable*, and an iterator with the same items as *iterable*. - This allows you to "look ahead" at the items in the iterable without - advancing it. - - There is one item in the list by default: - - >>> iterable = 'abcdefg' - >>> head, iterable = spy(iterable) - >>> head - ['a'] - >>> list(iterable) - ['a', 'b', 'c', 'd', 'e', 'f', 'g'] - - You may use unpacking to retrieve items instead of lists: - - >>> (head,), iterable = spy('abcdefg') - >>> head - 'a' - >>> (first, second), iterable = spy('abcdefg', 2) - >>> first - 'a' - >>> second - 'b' - - The number of items requested can be larger than the number of items in - the iterable: - - >>> iterable = [1, 2, 3, 4, 5] - >>> head, iterable = spy(iterable, 10) - >>> head - [1, 2, 3, 4, 5] - >>> list(iterable) - [1, 2, 3, 4, 5] - - """ - it = iter(iterable) - head = take(n, it) - - return head.copy(), chain(head, it) - - -def interleave(*iterables): - """Return a new iterable yielding from each iterable in turn, - until the shortest is exhausted. - - >>> list(interleave([1, 2, 3], [4, 5], [6, 7, 8])) - [1, 4, 6, 2, 5, 7] - - For a version that doesn't terminate after the shortest iterable is - exhausted, see :func:`interleave_longest`. - - """ - return chain.from_iterable(zip(*iterables)) - - -def interleave_longest(*iterables): - """Return a new iterable yielding from each iterable in turn, - skipping any that are exhausted. - - >>> list(interleave_longest([1, 2, 3], [4, 5], [6, 7, 8])) - [1, 4, 6, 2, 5, 7, 3, 8] - - This function produces the same output as :func:`roundrobin`, but may - perform better for some inputs (in particular when the number of iterables - is large). - - """ - i = chain.from_iterable(zip_longest(*iterables, fillvalue=_marker)) - return (x for x in i if x is not _marker) - - -def interleave_evenly(iterables, lengths=None): - """ - Interleave multiple iterables so that their elements are evenly distributed - throughout the output sequence. - - >>> iterables = [1, 2, 3, 4, 5], ['a', 'b'] - >>> list(interleave_evenly(iterables)) - [1, 2, 'a', 3, 4, 'b', 5] - - >>> iterables = [[1, 2, 3], [4, 5], [6, 7, 8]] - >>> list(interleave_evenly(iterables)) - [1, 6, 4, 2, 7, 3, 8, 5] - - This function requires iterables of known length. Iterables without - ``__len__()`` can be used by manually specifying lengths with *lengths*: - - >>> from itertools import combinations, repeat - >>> iterables = [combinations(range(4), 2), ['a', 'b', 'c']] - >>> lengths = [4 * (4 - 1) // 2, 3] - >>> list(interleave_evenly(iterables, lengths=lengths)) - [(0, 1), (0, 2), 'a', (0, 3), (1, 2), 'b', (1, 3), (2, 3), 'c'] - - Based on Bresenham's algorithm. - """ - if lengths is None: - try: - lengths = [len(it) for it in iterables] - except TypeError: - raise ValueError( - 'Iterable lengths could not be determined automatically. ' - 'Specify them with the lengths keyword.' - ) - elif len(iterables) != len(lengths): - raise ValueError('Mismatching number of iterables and lengths.') - - dims = len(lengths) - - # sort iterables by length, descending - lengths_permute = sorted( - range(dims), key=lambda i: lengths[i], reverse=True - ) - lengths_desc = [lengths[i] for i in lengths_permute] - iters_desc = [iter(iterables[i]) for i in lengths_permute] - - # the longest iterable is the primary one (Bresenham: the longest - # distance along an axis) - delta_primary, deltas_secondary = lengths_desc[0], lengths_desc[1:] - iter_primary, iters_secondary = iters_desc[0], iters_desc[1:] - errors = [delta_primary // dims] * len(deltas_secondary) - - to_yield = sum(lengths) - while to_yield: - yield next(iter_primary) - to_yield -= 1 - # update errors for each secondary iterable - errors = [e - delta for e, delta in zip(errors, deltas_secondary)] - - # those iterables for which the error is negative are yielded - # ("diagonal step" in Bresenham) - for i, e in enumerate(errors): - if e < 0: - yield next(iters_secondary[i]) - to_yield -= 1 - errors[i] += delta_primary - - -def collapse(iterable, base_type=None, levels=None): - """Flatten an iterable with multiple levels of nesting (e.g., a list of - lists of tuples) into non-iterable types. - - >>> iterable = [(1, 2), ([3, 4], [[5], [6]])] - >>> list(collapse(iterable)) - [1, 2, 3, 4, 5, 6] - - Binary and text strings are not considered iterable and - will not be collapsed. - - To avoid collapsing other types, specify *base_type*: - - >>> iterable = ['ab', ('cd', 'ef'), ['gh', 'ij']] - >>> list(collapse(iterable, base_type=tuple)) - ['ab', ('cd', 'ef'), 'gh', 'ij'] - - Specify *levels* to stop flattening after a certain level: - - >>> iterable = [('a', ['b']), ('c', ['d'])] - >>> list(collapse(iterable)) # Fully flattened - ['a', 'b', 'c', 'd'] - >>> list(collapse(iterable, levels=1)) # Only one level flattened - ['a', ['b'], 'c', ['d']] - - """ - - def walk(node, level): - if ( - ((levels is not None) and (level > levels)) - or isinstance(node, (str, bytes)) - or ((base_type is not None) and isinstance(node, base_type)) - ): - yield node - return - - try: - tree = iter(node) - except TypeError: - yield node - return - else: - for child in tree: - yield from walk(child, level + 1) - - yield from walk(iterable, 0) - - -def side_effect(func, iterable, chunk_size=None, before=None, after=None): - """Invoke *func* on each item in *iterable* (or on each *chunk_size* group - of items) before yielding the item. - - `func` must be a function that takes a single argument. Its return value - will be discarded. - - *before* and *after* are optional functions that take no arguments. They - will be executed before iteration starts and after it ends, respectively. - - `side_effect` can be used for logging, updating progress bars, or anything - that is not functionally "pure." - - Emitting a status message: - - >>> from more_itertools import consume - >>> func = lambda item: print('Received {}'.format(item)) - >>> consume(side_effect(func, range(2))) - Received 0 - Received 1 - - Operating on chunks of items: - - >>> pair_sums = [] - >>> func = lambda chunk: pair_sums.append(sum(chunk)) - >>> list(side_effect(func, [0, 1, 2, 3, 4, 5], 2)) - [0, 1, 2, 3, 4, 5] - >>> list(pair_sums) - [1, 5, 9] - - Writing to a file-like object: - - >>> from io import StringIO - >>> from more_itertools import consume - >>> f = StringIO() - >>> func = lambda x: print(x, file=f) - >>> before = lambda: print(u'HEADER', file=f) - >>> after = f.close - >>> it = [u'a', u'b', u'c'] - >>> consume(side_effect(func, it, before=before, after=after)) - >>> f.closed - True - - """ - try: - if before is not None: - before() - - if chunk_size is None: - for item in iterable: - func(item) - yield item - else: - for chunk in chunked(iterable, chunk_size): - func(chunk) - yield from chunk - finally: - if after is not None: - after() - - -def sliced(seq, n, strict=False): - """Yield slices of length *n* from the sequence *seq*. - - >>> list(sliced((1, 2, 3, 4, 5, 6), 3)) - [(1, 2, 3), (4, 5, 6)] - - By the default, the last yielded slice will have fewer than *n* elements - if the length of *seq* is not divisible by *n*: - - >>> list(sliced((1, 2, 3, 4, 5, 6, 7, 8), 3)) - [(1, 2, 3), (4, 5, 6), (7, 8)] - - If the length of *seq* is not divisible by *n* and *strict* is - ``True``, then ``ValueError`` will be raised before the last - slice is yielded. - - This function will only work for iterables that support slicing. - For non-sliceable iterables, see :func:`chunked`. - - """ - iterator = takewhile(len, (seq[i : i + n] for i in count(0, n))) - if strict: - - def ret(): - for _slice in iterator: - if len(_slice) != n: - raise ValueError("seq is not divisible by n.") - yield _slice - - return iter(ret()) - else: - return iterator - - -def split_at(iterable, pred, maxsplit=-1, keep_separator=False): - """Yield lists of items from *iterable*, where each list is delimited by - an item where callable *pred* returns ``True``. - - >>> list(split_at('abcdcba', lambda x: x == 'b')) - [['a'], ['c', 'd', 'c'], ['a']] - - >>> list(split_at(range(10), lambda n: n % 2 == 1)) - [[0], [2], [4], [6], [8], []] - - At most *maxsplit* splits are done. If *maxsplit* is not specified or -1, - then there is no limit on the number of splits: - - >>> list(split_at(range(10), lambda n: n % 2 == 1, maxsplit=2)) - [[0], [2], [4, 5, 6, 7, 8, 9]] - - By default, the delimiting items are not included in the output. - To include them, set *keep_separator* to ``True``. - - >>> list(split_at('abcdcba', lambda x: x == 'b', keep_separator=True)) - [['a'], ['b'], ['c', 'd', 'c'], ['b'], ['a']] - - """ - if maxsplit == 0: - yield list(iterable) - return - - buf = [] - it = iter(iterable) - for item in it: - if pred(item): - yield buf - if keep_separator: - yield [item] - if maxsplit == 1: - yield list(it) - return - buf = [] - maxsplit -= 1 - else: - buf.append(item) - yield buf - - -def split_before(iterable, pred, maxsplit=-1): - """Yield lists of items from *iterable*, where each list ends just before - an item for which callable *pred* returns ``True``: - - >>> list(split_before('OneTwo', lambda s: s.isupper())) - [['O', 'n', 'e'], ['T', 'w', 'o']] - - >>> list(split_before(range(10), lambda n: n % 3 == 0)) - [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] - - At most *maxsplit* splits are done. If *maxsplit* is not specified or -1, - then there is no limit on the number of splits: - - >>> list(split_before(range(10), lambda n: n % 3 == 0, maxsplit=2)) - [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]] - """ - if maxsplit == 0: - yield list(iterable) - return - - buf = [] - it = iter(iterable) - for item in it: - if pred(item) and buf: - yield buf - if maxsplit == 1: - yield [item] + list(it) - return - buf = [] - maxsplit -= 1 - buf.append(item) - if buf: - yield buf - - -def split_after(iterable, pred, maxsplit=-1): - """Yield lists of items from *iterable*, where each list ends with an - item where callable *pred* returns ``True``: - - >>> list(split_after('one1two2', lambda s: s.isdigit())) - [['o', 'n', 'e', '1'], ['t', 'w', 'o', '2']] - - >>> list(split_after(range(10), lambda n: n % 3 == 0)) - [[0], [1, 2, 3], [4, 5, 6], [7, 8, 9]] - - At most *maxsplit* splits are done. If *maxsplit* is not specified or -1, - then there is no limit on the number of splits: - - >>> list(split_after(range(10), lambda n: n % 3 == 0, maxsplit=2)) - [[0], [1, 2, 3], [4, 5, 6, 7, 8, 9]] - - """ - if maxsplit == 0: - yield list(iterable) - return - - buf = [] - it = iter(iterable) - for item in it: - buf.append(item) - if pred(item) and buf: - yield buf - if maxsplit == 1: - buf = list(it) - if buf: - yield buf - return - buf = [] - maxsplit -= 1 - if buf: - yield buf - - -def split_when(iterable, pred, maxsplit=-1): - """Split *iterable* into pieces based on the output of *pred*. - *pred* should be a function that takes successive pairs of items and - returns ``True`` if the iterable should be split in between them. - - For example, to find runs of increasing numbers, split the iterable when - element ``i`` is larger than element ``i + 1``: - - >>> list(split_when([1, 2, 3, 3, 2, 5, 2, 4, 2], lambda x, y: x > y)) - [[1, 2, 3, 3], [2, 5], [2, 4], [2]] - - At most *maxsplit* splits are done. If *maxsplit* is not specified or -1, - then there is no limit on the number of splits: - - >>> list(split_when([1, 2, 3, 3, 2, 5, 2, 4, 2], - ... lambda x, y: x > y, maxsplit=2)) - [[1, 2, 3, 3], [2, 5], [2, 4, 2]] - - """ - if maxsplit == 0: - yield list(iterable) - return - - it = iter(iterable) - try: - cur_item = next(it) - except StopIteration: - return - - buf = [cur_item] - for next_item in it: - if pred(cur_item, next_item): - yield buf - if maxsplit == 1: - yield [next_item] + list(it) - return - buf = [] - maxsplit -= 1 - - buf.append(next_item) - cur_item = next_item - - yield buf - - -def split_into(iterable, sizes): - """Yield a list of sequential items from *iterable* of length 'n' for each - integer 'n' in *sizes*. - - >>> list(split_into([1,2,3,4,5,6], [1,2,3])) - [[1], [2, 3], [4, 5, 6]] - - If the sum of *sizes* is smaller than the length of *iterable*, then the - remaining items of *iterable* will not be returned. - - >>> list(split_into([1,2,3,4,5,6], [2,3])) - [[1, 2], [3, 4, 5]] - - If the sum of *sizes* is larger than the length of *iterable*, fewer items - will be returned in the iteration that overruns *iterable* and further - lists will be empty: - - >>> list(split_into([1,2,3,4], [1,2,3,4])) - [[1], [2, 3], [4], []] - - When a ``None`` object is encountered in *sizes*, the returned list will - contain items up to the end of *iterable* the same way that itertools.slice - does: - - >>> list(split_into([1,2,3,4,5,6,7,8,9,0], [2,3,None])) - [[1, 2], [3, 4, 5], [6, 7, 8, 9, 0]] - - :func:`split_into` can be useful for grouping a series of items where the - sizes of the groups are not uniform. An example would be where in a row - from a table, multiple columns represent elements of the same feature - (e.g. a point represented by x,y,z) but, the format is not the same for - all columns. - """ - # convert the iterable argument into an iterator so its contents can - # be consumed by islice in case it is a generator - it = iter(iterable) - - for size in sizes: - if size is None: - yield list(it) - return - else: - yield list(islice(it, size)) - - -def padded(iterable, fillvalue=None, n=None, next_multiple=False): - """Yield the elements from *iterable*, followed by *fillvalue*, such that - at least *n* items are emitted. - - >>> list(padded([1, 2, 3], '?', 5)) - [1, 2, 3, '?', '?'] - - If *next_multiple* is ``True``, *fillvalue* will be emitted until the - number of items emitted is a multiple of *n*:: - - >>> list(padded([1, 2, 3, 4], n=3, next_multiple=True)) - [1, 2, 3, 4, None, None] - - If *n* is ``None``, *fillvalue* will be emitted indefinitely. - - """ - it = iter(iterable) - if n is None: - yield from chain(it, repeat(fillvalue)) - elif n < 1: - raise ValueError('n must be at least 1') - else: - item_count = 0 - for item in it: - yield item - item_count += 1 - - remaining = (n - item_count) % n if next_multiple else n - item_count - for _ in range(remaining): - yield fillvalue - - -def repeat_each(iterable, n=2): - """Repeat each element in *iterable* *n* times. - - >>> list(repeat_each('ABC', 3)) - ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'] - """ - return chain.from_iterable(map(repeat, iterable, repeat(n))) - - -def repeat_last(iterable, default=None): - """After the *iterable* is exhausted, keep yielding its last element. - - >>> list(islice(repeat_last(range(3)), 5)) - [0, 1, 2, 2, 2] - - If the iterable is empty, yield *default* forever:: - - >>> list(islice(repeat_last(range(0), 42), 5)) - [42, 42, 42, 42, 42] - - """ - item = _marker - for item in iterable: - yield item - final = default if item is _marker else item - yield from repeat(final) - - -def distribute(n, iterable): - """Distribute the items from *iterable* among *n* smaller iterables. - - >>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6]) - >>> list(group_1) - [1, 3, 5] - >>> list(group_2) - [2, 4, 6] - - If the length of *iterable* is not evenly divisible by *n*, then the - length of the returned iterables will not be identical: - - >>> children = distribute(3, [1, 2, 3, 4, 5, 6, 7]) - >>> [list(c) for c in children] - [[1, 4, 7], [2, 5], [3, 6]] - - If the length of *iterable* is smaller than *n*, then the last returned - iterables will be empty: - - >>> children = distribute(5, [1, 2, 3]) - >>> [list(c) for c in children] - [[1], [2], [3], [], []] - - This function uses :func:`itertools.tee` and may require significant - storage. If you need the order items in the smaller iterables to match the - original iterable, see :func:`divide`. - - """ - if n < 1: - raise ValueError('n must be at least 1') - - children = tee(iterable, n) - return [islice(it, index, None, n) for index, it in enumerate(children)] - - -def stagger(iterable, offsets=(-1, 0, 1), longest=False, fillvalue=None): - """Yield tuples whose elements are offset from *iterable*. - The amount by which the `i`-th item in each tuple is offset is given by - the `i`-th item in *offsets*. - - >>> list(stagger([0, 1, 2, 3])) - [(None, 0, 1), (0, 1, 2), (1, 2, 3)] - >>> list(stagger(range(8), offsets=(0, 2, 4))) - [(0, 2, 4), (1, 3, 5), (2, 4, 6), (3, 5, 7)] - - By default, the sequence will end when the final element of a tuple is the - last item in the iterable. To continue until the first element of a tuple - is the last item in the iterable, set *longest* to ``True``:: - - >>> list(stagger([0, 1, 2, 3], longest=True)) - [(None, 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, None), (3, None, None)] - - By default, ``None`` will be used to replace offsets beyond the end of the - sequence. Specify *fillvalue* to use some other value. - - """ - children = tee(iterable, len(offsets)) - - return zip_offset( - *children, offsets=offsets, longest=longest, fillvalue=fillvalue - ) - - -def zip_equal(*iterables): - """``zip`` the input *iterables* together, but raise - ``UnequalIterablesError`` if they aren't all the same length. - - >>> it_1 = range(3) - >>> it_2 = iter('abc') - >>> list(zip_equal(it_1, it_2)) - [(0, 'a'), (1, 'b'), (2, 'c')] - - >>> it_1 = range(3) - >>> it_2 = iter('abcd') - >>> list(zip_equal(it_1, it_2)) # doctest: +IGNORE_EXCEPTION_DETAIL - Traceback (most recent call last): - ... - more_itertools.more.UnequalIterablesError: Iterables have different - lengths - - """ - if hexversion >= 0x30A00A6: - warnings.warn( - ( - 'zip_equal will be removed in a future version of ' - 'more-itertools. Use the builtin zip function with ' - 'strict=True instead.' - ), - DeprecationWarning, - ) - - return _zip_equal(*iterables) - - -def zip_offset(*iterables, offsets, longest=False, fillvalue=None): - """``zip`` the input *iterables* together, but offset the `i`-th iterable - by the `i`-th item in *offsets*. - - >>> list(zip_offset('0123', 'abcdef', offsets=(0, 1))) - [('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e')] - - This can be used as a lightweight alternative to SciPy or pandas to analyze - data sets in which some series have a lead or lag relationship. - - By default, the sequence will end when the shortest iterable is exhausted. - To continue until the longest iterable is exhausted, set *longest* to - ``True``. - - >>> list(zip_offset('0123', 'abcdef', offsets=(0, 1), longest=True)) - [('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e'), (None, 'f')] - - By default, ``None`` will be used to replace offsets beyond the end of the - sequence. Specify *fillvalue* to use some other value. - - """ - if len(iterables) != len(offsets): - raise ValueError("Number of iterables and offsets didn't match") - - staggered = [] - for it, n in zip(iterables, offsets): - if n < 0: - staggered.append(chain(repeat(fillvalue, -n), it)) - elif n > 0: - staggered.append(islice(it, n, None)) - else: - staggered.append(it) - - if longest: - return zip_longest(*staggered, fillvalue=fillvalue) - - return zip(*staggered) - - -def sort_together(iterables, key_list=(0,), key=None, reverse=False): - """Return the input iterables sorted together, with *key_list* as the - priority for sorting. All iterables are trimmed to the length of the - shortest one. - - This can be used like the sorting function in a spreadsheet. If each - iterable represents a column of data, the key list determines which - columns are used for sorting. - - By default, all iterables are sorted using the ``0``-th iterable:: - - >>> iterables = [(4, 3, 2, 1), ('a', 'b', 'c', 'd')] - >>> sort_together(iterables) - [(1, 2, 3, 4), ('d', 'c', 'b', 'a')] - - Set a different key list to sort according to another iterable. - Specifying multiple keys dictates how ties are broken:: - - >>> iterables = [(3, 1, 2), (0, 1, 0), ('c', 'b', 'a')] - >>> sort_together(iterables, key_list=(1, 2)) - [(2, 3, 1), (0, 0, 1), ('a', 'c', 'b')] - - To sort by a function of the elements of the iterable, pass a *key* - function. Its arguments are the elements of the iterables corresponding to - the key list:: - - >>> names = ('a', 'b', 'c') - >>> lengths = (1, 2, 3) - >>> widths = (5, 2, 1) - >>> def area(length, width): - ... return length * width - >>> sort_together([names, lengths, widths], key_list=(1, 2), key=area) - [('c', 'b', 'a'), (3, 2, 1), (1, 2, 5)] - - Set *reverse* to ``True`` to sort in descending order. - - >>> sort_together([(1, 2, 3), ('c', 'b', 'a')], reverse=True) - [(3, 2, 1), ('a', 'b', 'c')] - - """ - if key is None: - # if there is no key function, the key argument to sorted is an - # itemgetter - key_argument = itemgetter(*key_list) - else: - # if there is a key function, call it with the items at the offsets - # specified by the key function as arguments - key_list = list(key_list) - if len(key_list) == 1: - # if key_list contains a single item, pass the item at that offset - # as the only argument to the key function - key_offset = key_list[0] - key_argument = lambda zipped_items: key(zipped_items[key_offset]) - else: - # if key_list contains multiple items, use itemgetter to return a - # tuple of items, which we pass as *args to the key function - get_key_items = itemgetter(*key_list) - key_argument = lambda zipped_items: key( - *get_key_items(zipped_items) - ) - - return list( - zip(*sorted(zip(*iterables), key=key_argument, reverse=reverse)) - ) - - -def unzip(iterable): - """The inverse of :func:`zip`, this function disaggregates the elements - of the zipped *iterable*. - - The ``i``-th iterable contains the ``i``-th element from each element - of the zipped iterable. The first element is used to determine the - length of the remaining elements. - - >>> iterable = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] - >>> letters, numbers = unzip(iterable) - >>> list(letters) - ['a', 'b', 'c', 'd'] - >>> list(numbers) - [1, 2, 3, 4] - - This is similar to using ``zip(*iterable)``, but it avoids reading - *iterable* into memory. Note, however, that this function uses - :func:`itertools.tee` and thus may require significant storage. - - """ - head, iterable = spy(iter(iterable)) - if not head: - # empty iterable, e.g. zip([], [], []) - return () - # spy returns a one-length iterable as head - head = head[0] - iterables = tee(iterable, len(head)) - - def itemgetter(i): - def getter(obj): - try: - return obj[i] - except IndexError: - # basically if we have an iterable like - # iter([(1, 2, 3), (4, 5), (6,)]) - # the second unzipped iterable would fail at the third tuple - # since it would try to access tup[1] - # same with the third unzipped iterable and the second tuple - # to support these "improperly zipped" iterables, - # we create a custom itemgetter - # which just stops the unzipped iterables - # at first length mismatch - raise StopIteration - - return getter - - return tuple(map(itemgetter(i), it) for i, it in enumerate(iterables)) - - -def divide(n, iterable): - """Divide the elements from *iterable* into *n* parts, maintaining - order. - - >>> group_1, group_2 = divide(2, [1, 2, 3, 4, 5, 6]) - >>> list(group_1) - [1, 2, 3] - >>> list(group_2) - [4, 5, 6] - - If the length of *iterable* is not evenly divisible by *n*, then the - length of the returned iterables will not be identical: - - >>> children = divide(3, [1, 2, 3, 4, 5, 6, 7]) - >>> [list(c) for c in children] - [[1, 2, 3], [4, 5], [6, 7]] - - If the length of the iterable is smaller than n, then the last returned - iterables will be empty: - - >>> children = divide(5, [1, 2, 3]) - >>> [list(c) for c in children] - [[1], [2], [3], [], []] - - This function will exhaust the iterable before returning and may require - significant storage. If order is not important, see :func:`distribute`, - which does not first pull the iterable into memory. - - """ - if n < 1: - raise ValueError('n must be at least 1') - - try: - iterable[:0] - except TypeError: - seq = tuple(iterable) - else: - seq = iterable - - q, r = divmod(len(seq), n) - - ret = [] - stop = 0 - for i in range(1, n + 1): - start = stop - stop += q + 1 if i <= r else q - ret.append(iter(seq[start:stop])) - - return ret - - -def always_iterable(obj, base_type=(str, bytes)): - """If *obj* is iterable, return an iterator over its items:: - - >>> obj = (1, 2, 3) - >>> list(always_iterable(obj)) - [1, 2, 3] - - If *obj* is not iterable, return a one-item iterable containing *obj*:: - - >>> obj = 1 - >>> list(always_iterable(obj)) - [1] - - If *obj* is ``None``, return an empty iterable: - - >>> obj = None - >>> list(always_iterable(None)) - [] - - By default, binary and text strings are not considered iterable:: - - >>> obj = 'foo' - >>> list(always_iterable(obj)) - ['foo'] - - If *base_type* is set, objects for which ``isinstance(obj, base_type)`` - returns ``True`` won't be considered iterable. - - >>> obj = {'a': 1} - >>> list(always_iterable(obj)) # Iterate over the dict's keys - ['a'] - >>> list(always_iterable(obj, base_type=dict)) # Treat dicts as a unit - [{'a': 1}] - - Set *base_type* to ``None`` to avoid any special handling and treat objects - Python considers iterable as iterable: - - >>> obj = 'foo' - >>> list(always_iterable(obj, base_type=None)) - ['f', 'o', 'o'] - """ - if obj is None: - return iter(()) - - if (base_type is not None) and isinstance(obj, base_type): - return iter((obj,)) - - try: - return iter(obj) - except TypeError: - return iter((obj,)) - - -def adjacent(predicate, iterable, distance=1): - """Return an iterable over `(bool, item)` tuples where the `item` is - drawn from *iterable* and the `bool` indicates whether - that item satisfies the *predicate* or is adjacent to an item that does. - - For example, to find whether items are adjacent to a ``3``:: - - >>> list(adjacent(lambda x: x == 3, range(6))) - [(False, 0), (False, 1), (True, 2), (True, 3), (True, 4), (False, 5)] - - Set *distance* to change what counts as adjacent. For example, to find - whether items are two places away from a ``3``: - - >>> list(adjacent(lambda x: x == 3, range(6), distance=2)) - [(False, 0), (True, 1), (True, 2), (True, 3), (True, 4), (True, 5)] - - This is useful for contextualizing the results of a search function. - For example, a code comparison tool might want to identify lines that - have changed, but also surrounding lines to give the viewer of the diff - context. - - The predicate function will only be called once for each item in the - iterable. - - See also :func:`groupby_transform`, which can be used with this function - to group ranges of items with the same `bool` value. - - """ - # Allow distance=0 mainly for testing that it reproduces results with map() - if distance < 0: - raise ValueError('distance must be at least 0') - - i1, i2 = tee(iterable) - padding = [False] * distance - selected = chain(padding, map(predicate, i1), padding) - adjacent_to_selected = map(any, windowed(selected, 2 * distance + 1)) - return zip(adjacent_to_selected, i2) - - -def groupby_transform(iterable, keyfunc=None, valuefunc=None, reducefunc=None): - """An extension of :func:`itertools.groupby` that can apply transformations - to the grouped data. - - * *keyfunc* is a function computing a key value for each item in *iterable* - * *valuefunc* is a function that transforms the individual items from - *iterable* after grouping - * *reducefunc* is a function that transforms each group of items - - >>> iterable = 'aAAbBBcCC' - >>> keyfunc = lambda k: k.upper() - >>> valuefunc = lambda v: v.lower() - >>> reducefunc = lambda g: ''.join(g) - >>> list(groupby_transform(iterable, keyfunc, valuefunc, reducefunc)) - [('A', 'aaa'), ('B', 'bbb'), ('C', 'ccc')] - - Each optional argument defaults to an identity function if not specified. - - :func:`groupby_transform` is useful when grouping elements of an iterable - using a separate iterable as the key. To do this, :func:`zip` the iterables - and pass a *keyfunc* that extracts the first element and a *valuefunc* - that extracts the second element:: - - >>> from operator import itemgetter - >>> keys = [0, 0, 1, 1, 1, 2, 2, 2, 3] - >>> values = 'abcdefghi' - >>> iterable = zip(keys, values) - >>> grouper = groupby_transform(iterable, itemgetter(0), itemgetter(1)) - >>> [(k, ''.join(g)) for k, g in grouper] - [(0, 'ab'), (1, 'cde'), (2, 'fgh'), (3, 'i')] - - Note that the order of items in the iterable is significant. - Only adjacent items are grouped together, so if you don't want any - duplicate groups, you should sort the iterable by the key function. - - """ - ret = groupby(iterable, keyfunc) - if valuefunc: - ret = ((k, map(valuefunc, g)) for k, g in ret) - if reducefunc: - ret = ((k, reducefunc(g)) for k, g in ret) - - return ret - - -class numeric_range(abc.Sequence, abc.Hashable): - """An extension of the built-in ``range()`` function whose arguments can - be any orderable numeric type. - - With only *stop* specified, *start* defaults to ``0`` and *step* - defaults to ``1``. The output items will match the type of *stop*: - - >>> list(numeric_range(3.5)) - [0.0, 1.0, 2.0, 3.0] - - With only *start* and *stop* specified, *step* defaults to ``1``. The - output items will match the type of *start*: - - >>> from decimal import Decimal - >>> start = Decimal('2.1') - >>> stop = Decimal('5.1') - >>> list(numeric_range(start, stop)) - [Decimal('2.1'), Decimal('3.1'), Decimal('4.1')] - - With *start*, *stop*, and *step* specified the output items will match - the type of ``start + step``: - - >>> from fractions import Fraction - >>> start = Fraction(1, 2) # Start at 1/2 - >>> stop = Fraction(5, 2) # End at 5/2 - >>> step = Fraction(1, 2) # Count by 1/2 - >>> list(numeric_range(start, stop, step)) - [Fraction(1, 2), Fraction(1, 1), Fraction(3, 2), Fraction(2, 1)] - - If *step* is zero, ``ValueError`` is raised. Negative steps are supported: - - >>> list(numeric_range(3, -1, -1.0)) - [3.0, 2.0, 1.0, 0.0] - - Be aware of the limitations of floating point numbers; the representation - of the yielded numbers may be surprising. - - ``datetime.datetime`` objects can be used for *start* and *stop*, if *step* - is a ``datetime.timedelta`` object: - - >>> import datetime - >>> start = datetime.datetime(2019, 1, 1) - >>> stop = datetime.datetime(2019, 1, 3) - >>> step = datetime.timedelta(days=1) - >>> items = iter(numeric_range(start, stop, step)) - >>> next(items) - datetime.datetime(2019, 1, 1, 0, 0) - >>> next(items) - datetime.datetime(2019, 1, 2, 0, 0) - - """ - - _EMPTY_HASH = hash(range(0, 0)) - - def __init__(self, *args): - argc = len(args) - if argc == 1: - (self._stop,) = args - self._start = type(self._stop)(0) - self._step = type(self._stop - self._start)(1) - elif argc == 2: - self._start, self._stop = args - self._step = type(self._stop - self._start)(1) - elif argc == 3: - self._start, self._stop, self._step = args - elif argc == 0: - raise TypeError( - 'numeric_range expected at least ' - '1 argument, got {}'.format(argc) - ) - else: - raise TypeError( - 'numeric_range expected at most ' - '3 arguments, got {}'.format(argc) - ) - - self._zero = type(self._step)(0) - if self._step == self._zero: - raise ValueError('numeric_range() arg 3 must not be zero') - self._growing = self._step > self._zero - self._init_len() - - def __bool__(self): - if self._growing: - return self._start < self._stop - else: - return self._start > self._stop - - def __contains__(self, elem): - if self._growing: - if self._start <= elem < self._stop: - return (elem - self._start) % self._step == self._zero - else: - if self._start >= elem > self._stop: - return (self._start - elem) % (-self._step) == self._zero - - return False - - def __eq__(self, other): - if isinstance(other, numeric_range): - empty_self = not bool(self) - empty_other = not bool(other) - if empty_self or empty_other: - return empty_self and empty_other # True if both empty - else: - return ( - self._start == other._start - and self._step == other._step - and self._get_by_index(-1) == other._get_by_index(-1) - ) - else: - return False - - def __getitem__(self, key): - if isinstance(key, int): - return self._get_by_index(key) - elif isinstance(key, slice): - step = self._step if key.step is None else key.step * self._step - - if key.start is None or key.start <= -self._len: - start = self._start - elif key.start >= self._len: - start = self._stop - else: # -self._len < key.start < self._len - start = self._get_by_index(key.start) - - if key.stop is None or key.stop >= self._len: - stop = self._stop - elif key.stop <= -self._len: - stop = self._start - else: # -self._len < key.stop < self._len - stop = self._get_by_index(key.stop) - - return numeric_range(start, stop, step) - else: - raise TypeError( - 'numeric range indices must be ' - 'integers or slices, not {}'.format(type(key).__name__) - ) - - def __hash__(self): - if self: - return hash((self._start, self._get_by_index(-1), self._step)) - else: - return self._EMPTY_HASH - - def __iter__(self): - values = (self._start + (n * self._step) for n in count()) - if self._growing: - return takewhile(partial(gt, self._stop), values) - else: - return takewhile(partial(lt, self._stop), values) - - def __len__(self): - return self._len - - def _init_len(self): - if self._growing: - start = self._start - stop = self._stop - step = self._step - else: - start = self._stop - stop = self._start - step = -self._step - distance = stop - start - if distance <= self._zero: - self._len = 0 - else: # distance > 0 and step > 0: regular euclidean division - q, r = divmod(distance, step) - self._len = int(q) + int(r != self._zero) - - def __reduce__(self): - return numeric_range, (self._start, self._stop, self._step) - - def __repr__(self): - if self._step == 1: - return "numeric_range({}, {})".format( - repr(self._start), repr(self._stop) - ) - else: - return "numeric_range({}, {}, {})".format( - repr(self._start), repr(self._stop), repr(self._step) - ) - - def __reversed__(self): - return iter( - numeric_range( - self._get_by_index(-1), self._start - self._step, -self._step - ) - ) - - def count(self, value): - return int(value in self) - - def index(self, value): - if self._growing: - if self._start <= value < self._stop: - q, r = divmod(value - self._start, self._step) - if r == self._zero: - return int(q) - else: - if self._start >= value > self._stop: - q, r = divmod(self._start - value, -self._step) - if r == self._zero: - return int(q) - - raise ValueError("{} is not in numeric range".format(value)) - - def _get_by_index(self, i): - if i < 0: - i += self._len - if i < 0 or i >= self._len: - raise IndexError("numeric range object index out of range") - return self._start + i * self._step - - -def count_cycle(iterable, n=None): - """Cycle through the items from *iterable* up to *n* times, yielding - the number of completed cycles along with each item. If *n* is omitted the - process repeats indefinitely. - - >>> list(count_cycle('AB', 3)) - [(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')] - - """ - iterable = tuple(iterable) - if not iterable: - return iter(()) - counter = count() if n is None else range(n) - return ((i, item) for i in counter for item in iterable) - - -def mark_ends(iterable): - """Yield 3-tuples of the form ``(is_first, is_last, item)``. - - >>> list(mark_ends('ABC')) - [(True, False, 'A'), (False, False, 'B'), (False, True, 'C')] - - Use this when looping over an iterable to take special action on its first - and/or last items: - - >>> iterable = ['Header', 100, 200, 'Footer'] - >>> total = 0 - >>> for is_first, is_last, item in mark_ends(iterable): - ... if is_first: - ... continue # Skip the header - ... if is_last: - ... continue # Skip the footer - ... total += item - >>> print(total) - 300 - """ - it = iter(iterable) - - try: - b = next(it) - except StopIteration: - return - - try: - for i in count(): - a = b - b = next(it) - yield i == 0, False, a - - except StopIteration: - yield i == 0, True, a - - -def locate(iterable, pred=bool, window_size=None): - """Yield the index of each item in *iterable* for which *pred* returns - ``True``. - - *pred* defaults to :func:`bool`, which will select truthy items: - - >>> list(locate([0, 1, 1, 0, 1, 0, 0])) - [1, 2, 4] - - Set *pred* to a custom function to, e.g., find the indexes for a particular - item. - - >>> list(locate(['a', 'b', 'c', 'b'], lambda x: x == 'b')) - [1, 3] - - If *window_size* is given, then the *pred* function will be called with - that many items. This enables searching for sub-sequences: - - >>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3] - >>> pred = lambda *args: args == (1, 2, 3) - >>> list(locate(iterable, pred=pred, window_size=3)) - [1, 5, 9] - - Use with :func:`seekable` to find indexes and then retrieve the associated - items: - - >>> from itertools import count - >>> from more_itertools import seekable - >>> source = (3 * n + 1 if (n % 2) else n // 2 for n in count()) - >>> it = seekable(source) - >>> pred = lambda x: x > 100 - >>> indexes = locate(it, pred=pred) - >>> i = next(indexes) - >>> it.seek(i) - >>> next(it) - 106 - - """ - if window_size is None: - return compress(count(), map(pred, iterable)) - - if window_size < 1: - raise ValueError('window size must be at least 1') - - it = windowed(iterable, window_size, fillvalue=_marker) - return compress(count(), starmap(pred, it)) - - -def longest_common_prefix(iterables): - """Yield elements of the longest common prefix amongst given *iterables*. - - >>> ''.join(longest_common_prefix(['abcd', 'abc', 'abf'])) - 'ab' - - """ - return (c[0] for c in takewhile(all_equal, zip(*iterables))) - - -def lstrip(iterable, pred): - """Yield the items from *iterable*, but strip any from the beginning - for which *pred* returns ``True``. - - For example, to remove a set of items from the start of an iterable: - - >>> iterable = (None, False, None, 1, 2, None, 3, False, None) - >>> pred = lambda x: x in {None, False, ''} - >>> list(lstrip(iterable, pred)) - [1, 2, None, 3, False, None] - - This function is analogous to to :func:`str.lstrip`, and is essentially - an wrapper for :func:`itertools.dropwhile`. - - """ - return dropwhile(pred, iterable) - - -def rstrip(iterable, pred): - """Yield the items from *iterable*, but strip any from the end - for which *pred* returns ``True``. - - For example, to remove a set of items from the end of an iterable: - - >>> iterable = (None, False, None, 1, 2, None, 3, False, None) - >>> pred = lambda x: x in {None, False, ''} - >>> list(rstrip(iterable, pred)) - [None, False, None, 1, 2, None, 3] - - This function is analogous to :func:`str.rstrip`. - - """ - cache = [] - cache_append = cache.append - cache_clear = cache.clear - for x in iterable: - if pred(x): - cache_append(x) - else: - yield from cache - cache_clear() - yield x - - -def strip(iterable, pred): - """Yield the items from *iterable*, but strip any from the - beginning and end for which *pred* returns ``True``. - - For example, to remove a set of items from both ends of an iterable: - - >>> iterable = (None, False, None, 1, 2, None, 3, False, None) - >>> pred = lambda x: x in {None, False, ''} - >>> list(strip(iterable, pred)) - [1, 2, None, 3] - - This function is analogous to :func:`str.strip`. - - """ - return rstrip(lstrip(iterable, pred), pred) - - -class islice_extended: - """An extension of :func:`itertools.islice` that supports negative values - for *stop*, *start*, and *step*. - - >>> iterable = iter('abcdefgh') - >>> list(islice_extended(iterable, -4, -1)) - ['e', 'f', 'g'] - - Slices with negative values require some caching of *iterable*, but this - function takes care to minimize the amount of memory required. - - For example, you can use a negative step with an infinite iterator: - - >>> from itertools import count - >>> list(islice_extended(count(), 110, 99, -2)) - [110, 108, 106, 104, 102, 100] - - You can also use slice notation directly: - - >>> iterable = map(str, count()) - >>> it = islice_extended(iterable)[10:20:2] - >>> list(it) - ['10', '12', '14', '16', '18'] - - """ - - def __init__(self, iterable, *args): - it = iter(iterable) - if args: - self._iterable = _islice_helper(it, slice(*args)) - else: - self._iterable = it - - def __iter__(self): - return self - - def __next__(self): - return next(self._iterable) - - def __getitem__(self, key): - if isinstance(key, slice): - return islice_extended(_islice_helper(self._iterable, key)) - - raise TypeError('islice_extended.__getitem__ argument must be a slice') - - -def _islice_helper(it, s): - start = s.start - stop = s.stop - if s.step == 0: - raise ValueError('step argument must be a non-zero integer or None.') - step = s.step or 1 - - if step > 0: - start = 0 if (start is None) else start - - if start < 0: - # Consume all but the last -start items - cache = deque(enumerate(it, 1), maxlen=-start) - len_iter = cache[-1][0] if cache else 0 - - # Adjust start to be positive - i = max(len_iter + start, 0) - - # Adjust stop to be positive - if stop is None: - j = len_iter - elif stop >= 0: - j = min(stop, len_iter) - else: - j = max(len_iter + stop, 0) - - # Slice the cache - n = j - i - if n <= 0: - return - - for index, item in islice(cache, 0, n, step): - yield item - elif (stop is not None) and (stop < 0): - # Advance to the start position - next(islice(it, start, start), None) - - # When stop is negative, we have to carry -stop items while - # iterating - cache = deque(islice(it, -stop), maxlen=-stop) - - for index, item in enumerate(it): - cached_item = cache.popleft() - if index % step == 0: - yield cached_item - cache.append(item) - else: - # When both start and stop are positive we have the normal case - yield from islice(it, start, stop, step) - else: - start = -1 if (start is None) else start - - if (stop is not None) and (stop < 0): - # Consume all but the last items - n = -stop - 1 - cache = deque(enumerate(it, 1), maxlen=n) - len_iter = cache[-1][0] if cache else 0 - - # If start and stop are both negative they are comparable and - # we can just slice. Otherwise we can adjust start to be negative - # and then slice. - if start < 0: - i, j = start, stop - else: - i, j = min(start - len_iter, -1), None - - for index, item in list(cache)[i:j:step]: - yield item - else: - # Advance to the stop position - if stop is not None: - m = stop + 1 - next(islice(it, m, m), None) - - # stop is positive, so if start is negative they are not comparable - # and we need the rest of the items. - if start < 0: - i = start - n = None - # stop is None and start is positive, so we just need items up to - # the start index. - elif stop is None: - i = None - n = start + 1 - # Both stop and start are positive, so they are comparable. - else: - i = None - n = start - stop - if n <= 0: - return - - cache = list(islice(it, n)) - - yield from cache[i::step] - - -def always_reversible(iterable): - """An extension of :func:`reversed` that supports all iterables, not - just those which implement the ``Reversible`` or ``Sequence`` protocols. - - >>> print(*always_reversible(x for x in range(3))) - 2 1 0 - - If the iterable is already reversible, this function returns the - result of :func:`reversed()`. If the iterable is not reversible, - this function will cache the remaining items in the iterable and - yield them in reverse order, which may require significant storage. - """ - try: - return reversed(iterable) - except TypeError: - return reversed(list(iterable)) - - -def consecutive_groups(iterable, ordering=lambda x: x): - """Yield groups of consecutive items using :func:`itertools.groupby`. - The *ordering* function determines whether two items are adjacent by - returning their position. - - By default, the ordering function is the identity function. This is - suitable for finding runs of numbers: - - >>> iterable = [1, 10, 11, 12, 20, 30, 31, 32, 33, 40] - >>> for group in consecutive_groups(iterable): - ... print(list(group)) - [1] - [10, 11, 12] - [20] - [30, 31, 32, 33] - [40] - - For finding runs of adjacent letters, try using the :meth:`index` method - of a string of letters: - - >>> from string import ascii_lowercase - >>> iterable = 'abcdfgilmnop' - >>> ordering = ascii_lowercase.index - >>> for group in consecutive_groups(iterable, ordering): - ... print(list(group)) - ['a', 'b', 'c', 'd'] - ['f', 'g'] - ['i'] - ['l', 'm', 'n', 'o', 'p'] - - Each group of consecutive items is an iterator that shares it source with - *iterable*. When an an output group is advanced, the previous group is - no longer available unless its elements are copied (e.g., into a ``list``). - - >>> iterable = [1, 2, 11, 12, 21, 22] - >>> saved_groups = [] - >>> for group in consecutive_groups(iterable): - ... saved_groups.append(list(group)) # Copy group elements - >>> saved_groups - [[1, 2], [11, 12], [21, 22]] - - """ - for k, g in groupby( - enumerate(iterable), key=lambda x: x[0] - ordering(x[1]) - ): - yield map(itemgetter(1), g) - - -def difference(iterable, func=sub, *, initial=None): - """This function is the inverse of :func:`itertools.accumulate`. By default - it will compute the first difference of *iterable* using - :func:`operator.sub`: - - >>> from itertools import accumulate - >>> iterable = accumulate([0, 1, 2, 3, 4]) # produces 0, 1, 3, 6, 10 - >>> list(difference(iterable)) - [0, 1, 2, 3, 4] - - *func* defaults to :func:`operator.sub`, but other functions can be - specified. They will be applied as follows:: - - A, B, C, D, ... --> A, func(B, A), func(C, B), func(D, C), ... - - For example, to do progressive division: - - >>> iterable = [1, 2, 6, 24, 120] - >>> func = lambda x, y: x // y - >>> list(difference(iterable, func)) - [1, 2, 3, 4, 5] - - If the *initial* keyword is set, the first element will be skipped when - computing successive differences. - - >>> it = [10, 11, 13, 16] # from accumulate([1, 2, 3], initial=10) - >>> list(difference(it, initial=10)) - [1, 2, 3] - - """ - a, b = tee(iterable) - try: - first = [next(b)] - except StopIteration: - return iter([]) - - if initial is not None: - first = [] - - return chain(first, map(func, b, a)) - - -class SequenceView(Sequence): - """Return a read-only view of the sequence object *target*. - - :class:`SequenceView` objects are analogous to Python's built-in - "dictionary view" types. They provide a dynamic view of a sequence's items, - meaning that when the sequence updates, so does the view. - - >>> seq = ['0', '1', '2'] - >>> view = SequenceView(seq) - >>> view - SequenceView(['0', '1', '2']) - >>> seq.append('3') - >>> view - SequenceView(['0', '1', '2', '3']) - - Sequence views support indexing, slicing, and length queries. They act - like the underlying sequence, except they don't allow assignment: - - >>> view[1] - '1' - >>> view[1:-1] - ['1', '2'] - >>> len(view) - 4 - - Sequence views are useful as an alternative to copying, as they don't - require (much) extra storage. - - """ - - def __init__(self, target): - if not isinstance(target, Sequence): - raise TypeError - self._target = target - - def __getitem__(self, index): - return self._target[index] - - def __len__(self): - return len(self._target) - - def __repr__(self): - return '{}({})'.format(self.__class__.__name__, repr(self._target)) - - -class seekable: - """Wrap an iterator to allow for seeking backward and forward. This - progressively caches the items in the source iterable so they can be - re-visited. - - Call :meth:`seek` with an index to seek to that position in the source - iterable. - - To "reset" an iterator, seek to ``0``: - - >>> from itertools import count - >>> it = seekable((str(n) for n in count())) - >>> next(it), next(it), next(it) - ('0', '1', '2') - >>> it.seek(0) - >>> next(it), next(it), next(it) - ('0', '1', '2') - >>> next(it) - '3' - - You can also seek forward: - - >>> it = seekable((str(n) for n in range(20))) - >>> it.seek(10) - >>> next(it) - '10' - >>> it.seek(20) # Seeking past the end of the source isn't a problem - >>> list(it) - [] - >>> it.seek(0) # Resetting works even after hitting the end - >>> next(it), next(it), next(it) - ('0', '1', '2') - - Call :meth:`peek` to look ahead one item without advancing the iterator: - - >>> it = seekable('1234') - >>> it.peek() - '1' - >>> list(it) - ['1', '2', '3', '4'] - >>> it.peek(default='empty') - 'empty' - - Before the iterator is at its end, calling :func:`bool` on it will return - ``True``. After it will return ``False``: - - >>> it = seekable('5678') - >>> bool(it) - True - >>> list(it) - ['5', '6', '7', '8'] - >>> bool(it) - False - - You may view the contents of the cache with the :meth:`elements` method. - That returns a :class:`SequenceView`, a view that updates automatically: - - >>> it = seekable((str(n) for n in range(10))) - >>> next(it), next(it), next(it) - ('0', '1', '2') - >>> elements = it.elements() - >>> elements - SequenceView(['0', '1', '2']) - >>> next(it) - '3' - >>> elements - SequenceView(['0', '1', '2', '3']) - - By default, the cache grows as the source iterable progresses, so beware of - wrapping very large or infinite iterables. Supply *maxlen* to limit the - size of the cache (this of course limits how far back you can seek). - - >>> from itertools import count - >>> it = seekable((str(n) for n in count()), maxlen=2) - >>> next(it), next(it), next(it), next(it) - ('0', '1', '2', '3') - >>> list(it.elements()) - ['2', '3'] - >>> it.seek(0) - >>> next(it), next(it), next(it), next(it) - ('2', '3', '4', '5') - >>> next(it) - '6' - - """ - - def __init__(self, iterable, maxlen=None): - self._source = iter(iterable) - if maxlen is None: - self._cache = [] - else: - self._cache = deque([], maxlen) - self._index = None - - def __iter__(self): - return self - - def __next__(self): - if self._index is not None: - try: - item = self._cache[self._index] - except IndexError: - self._index = None - else: - self._index += 1 - return item - - item = next(self._source) - self._cache.append(item) - return item - - def __bool__(self): - try: - self.peek() - except StopIteration: - return False - return True - - def peek(self, default=_marker): - try: - peeked = next(self) - except StopIteration: - if default is _marker: - raise - return default - if self._index is None: - self._index = len(self._cache) - self._index -= 1 - return peeked - - def elements(self): - return SequenceView(self._cache) - - def seek(self, index): - self._index = index - remainder = index - len(self._cache) - if remainder > 0: - consume(self, remainder) - - -class run_length: - """ - :func:`run_length.encode` compresses an iterable with run-length encoding. - It yields groups of repeated items with the count of how many times they - were repeated: - - >>> uncompressed = 'abbcccdddd' - >>> list(run_length.encode(uncompressed)) - [('a', 1), ('b', 2), ('c', 3), ('d', 4)] - - :func:`run_length.decode` decompresses an iterable that was previously - compressed with run-length encoding. It yields the items of the - decompressed iterable: - - >>> compressed = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] - >>> list(run_length.decode(compressed)) - ['a', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'd'] - - """ - - @staticmethod - def encode(iterable): - return ((k, ilen(g)) for k, g in groupby(iterable)) - - @staticmethod - def decode(iterable): - return chain.from_iterable(repeat(k, n) for k, n in iterable) - - -def exactly_n(iterable, n, predicate=bool): - """Return ``True`` if exactly ``n`` items in the iterable are ``True`` - according to the *predicate* function. - - >>> exactly_n([True, True, False], 2) - True - >>> exactly_n([True, True, False], 1) - False - >>> exactly_n([0, 1, 2, 3, 4, 5], 3, lambda x: x < 3) - True - - The iterable will be advanced until ``n + 1`` truthy items are encountered, - so avoid calling it on infinite iterables. - - """ - return len(take(n + 1, filter(predicate, iterable))) == n - - -def circular_shifts(iterable): - """Return a list of circular shifts of *iterable*. - - >>> circular_shifts(range(4)) - [(0, 1, 2, 3), (1, 2, 3, 0), (2, 3, 0, 1), (3, 0, 1, 2)] - """ - lst = list(iterable) - return take(len(lst), windowed(cycle(lst), len(lst))) - - -def make_decorator(wrapping_func, result_index=0): - """Return a decorator version of *wrapping_func*, which is a function that - modifies an iterable. *result_index* is the position in that function's - signature where the iterable goes. - - This lets you use itertools on the "production end," i.e. at function - definition. This can augment what the function returns without changing the - function's code. - - For example, to produce a decorator version of :func:`chunked`: - - >>> from more_itertools import chunked - >>> chunker = make_decorator(chunked, result_index=0) - >>> @chunker(3) - ... def iter_range(n): - ... return iter(range(n)) - ... - >>> list(iter_range(9)) - [[0, 1, 2], [3, 4, 5], [6, 7, 8]] - - To only allow truthy items to be returned: - - >>> truth_serum = make_decorator(filter, result_index=1) - >>> @truth_serum(bool) - ... def boolean_test(): - ... return [0, 1, '', ' ', False, True] - ... - >>> list(boolean_test()) - [1, ' ', True] - - The :func:`peekable` and :func:`seekable` wrappers make for practical - decorators: - - >>> from more_itertools import peekable - >>> peekable_function = make_decorator(peekable) - >>> @peekable_function() - ... def str_range(*args): - ... return (str(x) for x in range(*args)) - ... - >>> it = str_range(1, 20, 2) - >>> next(it), next(it), next(it) - ('1', '3', '5') - >>> it.peek() - '7' - >>> next(it) - '7' - - """ - - # See https://sites.google.com/site/bbayles/index/decorator_factory for - # notes on how this works. - def decorator(*wrapping_args, **wrapping_kwargs): - def outer_wrapper(f): - def inner_wrapper(*args, **kwargs): - result = f(*args, **kwargs) - wrapping_args_ = list(wrapping_args) - wrapping_args_.insert(result_index, result) - return wrapping_func(*wrapping_args_, **wrapping_kwargs) - - return inner_wrapper - - return outer_wrapper - - return decorator - - -def map_reduce(iterable, keyfunc, valuefunc=None, reducefunc=None): - """Return a dictionary that maps the items in *iterable* to categories - defined by *keyfunc*, transforms them with *valuefunc*, and - then summarizes them by category with *reducefunc*. - - *valuefunc* defaults to the identity function if it is unspecified. - If *reducefunc* is unspecified, no summarization takes place: - - >>> keyfunc = lambda x: x.upper() - >>> result = map_reduce('abbccc', keyfunc) - >>> sorted(result.items()) - [('A', ['a']), ('B', ['b', 'b']), ('C', ['c', 'c', 'c'])] - - Specifying *valuefunc* transforms the categorized items: - - >>> keyfunc = lambda x: x.upper() - >>> valuefunc = lambda x: 1 - >>> result = map_reduce('abbccc', keyfunc, valuefunc) - >>> sorted(result.items()) - [('A', [1]), ('B', [1, 1]), ('C', [1, 1, 1])] - - Specifying *reducefunc* summarizes the categorized items: - - >>> keyfunc = lambda x: x.upper() - >>> valuefunc = lambda x: 1 - >>> reducefunc = sum - >>> result = map_reduce('abbccc', keyfunc, valuefunc, reducefunc) - >>> sorted(result.items()) - [('A', 1), ('B', 2), ('C', 3)] - - You may want to filter the input iterable before applying the map/reduce - procedure: - - >>> all_items = range(30) - >>> items = [x for x in all_items if 10 <= x <= 20] # Filter - >>> keyfunc = lambda x: x % 2 # Evens map to 0; odds to 1 - >>> categories = map_reduce(items, keyfunc=keyfunc) - >>> sorted(categories.items()) - [(0, [10, 12, 14, 16, 18, 20]), (1, [11, 13, 15, 17, 19])] - >>> summaries = map_reduce(items, keyfunc=keyfunc, reducefunc=sum) - >>> sorted(summaries.items()) - [(0, 90), (1, 75)] - - Note that all items in the iterable are gathered into a list before the - summarization step, which may require significant storage. - - The returned object is a :obj:`collections.defaultdict` with the - ``default_factory`` set to ``None``, such that it behaves like a normal - dictionary. - - """ - valuefunc = (lambda x: x) if (valuefunc is None) else valuefunc - - ret = defaultdict(list) - for item in iterable: - key = keyfunc(item) - value = valuefunc(item) - ret[key].append(value) - - if reducefunc is not None: - for key, value_list in ret.items(): - ret[key] = reducefunc(value_list) - - ret.default_factory = None - return ret - - -def rlocate(iterable, pred=bool, window_size=None): - """Yield the index of each item in *iterable* for which *pred* returns - ``True``, starting from the right and moving left. - - *pred* defaults to :func:`bool`, which will select truthy items: - - >>> list(rlocate([0, 1, 1, 0, 1, 0, 0])) # Truthy at 1, 2, and 4 - [4, 2, 1] - - Set *pred* to a custom function to, e.g., find the indexes for a particular - item: - - >>> iterable = iter('abcb') - >>> pred = lambda x: x == 'b' - >>> list(rlocate(iterable, pred)) - [3, 1] - - If *window_size* is given, then the *pred* function will be called with - that many items. This enables searching for sub-sequences: - - >>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3] - >>> pred = lambda *args: args == (1, 2, 3) - >>> list(rlocate(iterable, pred=pred, window_size=3)) - [9, 5, 1] - - Beware, this function won't return anything for infinite iterables. - If *iterable* is reversible, ``rlocate`` will reverse it and search from - the right. Otherwise, it will search from the left and return the results - in reverse order. - - See :func:`locate` to for other example applications. - - """ - if window_size is None: - try: - len_iter = len(iterable) - return (len_iter - i - 1 for i in locate(reversed(iterable), pred)) - except TypeError: - pass - - return reversed(list(locate(iterable, pred, window_size))) - - -def replace(iterable, pred, substitutes, count=None, window_size=1): - """Yield the items from *iterable*, replacing the items for which *pred* - returns ``True`` with the items from the iterable *substitutes*. - - >>> iterable = [1, 1, 0, 1, 1, 0, 1, 1] - >>> pred = lambda x: x == 0 - >>> substitutes = (2, 3) - >>> list(replace(iterable, pred, substitutes)) - [1, 1, 2, 3, 1, 1, 2, 3, 1, 1] - - If *count* is given, the number of replacements will be limited: - - >>> iterable = [1, 1, 0, 1, 1, 0, 1, 1, 0] - >>> pred = lambda x: x == 0 - >>> substitutes = [None] - >>> list(replace(iterable, pred, substitutes, count=2)) - [1, 1, None, 1, 1, None, 1, 1, 0] - - Use *window_size* to control the number of items passed as arguments to - *pred*. This allows for locating and replacing subsequences. - - >>> iterable = [0, 1, 2, 5, 0, 1, 2, 5] - >>> window_size = 3 - >>> pred = lambda *args: args == (0, 1, 2) # 3 items passed to pred - >>> substitutes = [3, 4] # Splice in these items - >>> list(replace(iterable, pred, substitutes, window_size=window_size)) - [3, 4, 5, 3, 4, 5] - - """ - if window_size < 1: - raise ValueError('window_size must be at least 1') - - # Save the substitutes iterable, since it's used more than once - substitutes = tuple(substitutes) - - # Add padding such that the number of windows matches the length of the - # iterable - it = chain(iterable, [_marker] * (window_size - 1)) - windows = windowed(it, window_size) - - n = 0 - for w in windows: - # If the current window matches our predicate (and we haven't hit - # our maximum number of replacements), splice in the substitutes - # and then consume the following windows that overlap with this one. - # For example, if the iterable is (0, 1, 2, 3, 4...) - # and the window size is 2, we have (0, 1), (1, 2), (2, 3)... - # If the predicate matches on (0, 1), we need to zap (0, 1) and (1, 2) - if pred(*w): - if (count is None) or (n < count): - n += 1 - yield from substitutes - consume(windows, window_size - 1) - continue - - # If there was no match (or we've reached the replacement limit), - # yield the first item from the window. - if w and (w[0] is not _marker): - yield w[0] - - -def partitions(iterable): - """Yield all possible order-preserving partitions of *iterable*. - - >>> iterable = 'abc' - >>> for part in partitions(iterable): - ... print([''.join(p) for p in part]) - ['abc'] - ['a', 'bc'] - ['ab', 'c'] - ['a', 'b', 'c'] - - This is unrelated to :func:`partition`. - - """ - sequence = list(iterable) - n = len(sequence) - for i in powerset(range(1, n)): - yield [sequence[i:j] for i, j in zip((0,) + i, i + (n,))] - - -def set_partitions(iterable, k=None): - """ - Yield the set partitions of *iterable* into *k* parts. Set partitions are - not order-preserving. - - >>> iterable = 'abc' - >>> for part in set_partitions(iterable, 2): - ... print([''.join(p) for p in part]) - ['a', 'bc'] - ['ab', 'c'] - ['b', 'ac'] - - - If *k* is not given, every set partition is generated. - - >>> iterable = 'abc' - >>> for part in set_partitions(iterable): - ... print([''.join(p) for p in part]) - ['abc'] - ['a', 'bc'] - ['ab', 'c'] - ['b', 'ac'] - ['a', 'b', 'c'] - - """ - L = list(iterable) - n = len(L) - if k is not None: - if k < 1: - raise ValueError( - "Can't partition in a negative or zero number of groups" - ) - elif k > n: - return - - def set_partitions_helper(L, k): - n = len(L) - if k == 1: - yield [L] - elif n == k: - yield [[s] for s in L] - else: - e, *M = L - for p in set_partitions_helper(M, k - 1): - yield [[e], *p] - for p in set_partitions_helper(M, k): - for i in range(len(p)): - yield p[:i] + [[e] + p[i]] + p[i + 1 :] - - if k is None: - for k in range(1, n + 1): - yield from set_partitions_helper(L, k) - else: - yield from set_partitions_helper(L, k) - - -class time_limited: - """ - Yield items from *iterable* until *limit_seconds* have passed. - If the time limit expires before all items have been yielded, the - ``timed_out`` parameter will be set to ``True``. - - >>> from time import sleep - >>> def generator(): - ... yield 1 - ... yield 2 - ... sleep(0.2) - ... yield 3 - >>> iterable = time_limited(0.1, generator()) - >>> list(iterable) - [1, 2] - >>> iterable.timed_out - True - - Note that the time is checked before each item is yielded, and iteration - stops if the time elapsed is greater than *limit_seconds*. If your time - limit is 1 second, but it takes 2 seconds to generate the first item from - the iterable, the function will run for 2 seconds and not yield anything. - - """ - - def __init__(self, limit_seconds, iterable): - if limit_seconds < 0: - raise ValueError('limit_seconds must be positive') - self.limit_seconds = limit_seconds - self._iterable = iter(iterable) - self._start_time = monotonic() - self.timed_out = False - - def __iter__(self): - return self - - def __next__(self): - item = next(self._iterable) - if monotonic() - self._start_time > self.limit_seconds: - self.timed_out = True - raise StopIteration - - return item - - -def only(iterable, default=None, too_long=None): - """If *iterable* has only one item, return it. - If it has zero items, return *default*. - If it has more than one item, raise the exception given by *too_long*, - which is ``ValueError`` by default. - - >>> only([], default='missing') - 'missing' - >>> only([1]) - 1 - >>> only([1, 2]) # doctest: +IGNORE_EXCEPTION_DETAIL - Traceback (most recent call last): - ... - ValueError: Expected exactly one item in iterable, but got 1, 2, - and perhaps more.' - >>> only([1, 2], too_long=TypeError) # doctest: +IGNORE_EXCEPTION_DETAIL - Traceback (most recent call last): - ... - TypeError - - Note that :func:`only` attempts to advance *iterable* twice to ensure there - is only one item. See :func:`spy` or :func:`peekable` to check - iterable contents less destructively. - """ - it = iter(iterable) - first_value = next(it, default) - - try: - second_value = next(it) - except StopIteration: - pass - else: - msg = ( - 'Expected exactly one item in iterable, but got {!r}, {!r}, ' - 'and perhaps more.'.format(first_value, second_value) - ) - raise too_long or ValueError(msg) - - return first_value - - -class _IChunk: - def __init__(self, iterable, n): - self._it = islice(iterable, n) - self._cache = deque() - - def fill_cache(self): - self._cache.extend(self._it) - - def __iter__(self): - return self - - def __next__(self): - try: - return next(self._it) - except StopIteration: - if self._cache: - return self._cache.popleft() - else: - raise - - -def ichunked(iterable, n): - """Break *iterable* into sub-iterables with *n* elements each. - :func:`ichunked` is like :func:`chunked`, but it yields iterables - instead of lists. - - If the sub-iterables are read in order, the elements of *iterable* - won't be stored in memory. - If they are read out of order, :func:`itertools.tee` is used to cache - elements as necessary. - - >>> from itertools import count - >>> all_chunks = ichunked(count(), 4) - >>> c_1, c_2, c_3 = next(all_chunks), next(all_chunks), next(all_chunks) - >>> list(c_2) # c_1's elements have been cached; c_3's haven't been - [4, 5, 6, 7] - >>> list(c_1) - [0, 1, 2, 3] - >>> list(c_3) - [8, 9, 10, 11] - - """ - source = peekable(iter(iterable)) - ichunk_marker = object() - while True: - # Check to see whether we're at the end of the source iterable - item = source.peek(ichunk_marker) - if item is ichunk_marker: - return - - chunk = _IChunk(source, n) - yield chunk - - # Advance the source iterable and fill previous chunk's cache - chunk.fill_cache() - - -def iequals(*iterables): - """Return ``True`` if all given *iterables* are equal to each other, - which means that they contain the same elements in the same order. - - The function is useful for comparing iterables of different data types - or iterables that do not support equality checks. - - >>> iequals("abc", ['a', 'b', 'c'], ('a', 'b', 'c'), iter("abc")) - True - - >>> iequals("abc", "acb") - False - - Not to be confused with :func:`all_equals`, which checks whether all - elements of iterable are equal to each other. - - """ - return all(map(all_equal, zip_longest(*iterables, fillvalue=object()))) - - -def distinct_combinations(iterable, r): - """Yield the distinct combinations of *r* items taken from *iterable*. - - >>> list(distinct_combinations([0, 0, 1], 2)) - [(0, 0), (0, 1)] - - Equivalent to ``set(combinations(iterable))``, except duplicates are not - generated and thrown away. For larger input sequences this is much more - efficient. - - """ - if r < 0: - raise ValueError('r must be non-negative') - elif r == 0: - yield () - return - pool = tuple(iterable) - generators = [unique_everseen(enumerate(pool), key=itemgetter(1))] - current_combo = [None] * r - level = 0 - while generators: - try: - cur_idx, p = next(generators[-1]) - except StopIteration: - generators.pop() - level -= 1 - continue - current_combo[level] = p - if level + 1 == r: - yield tuple(current_combo) - else: - generators.append( - unique_everseen( - enumerate(pool[cur_idx + 1 :], cur_idx + 1), - key=itemgetter(1), - ) - ) - level += 1 - - -def filter_except(validator, iterable, *exceptions): - """Yield the items from *iterable* for which the *validator* function does - not raise one of the specified *exceptions*. - - *validator* is called for each item in *iterable*. - It should be a function that accepts one argument and raises an exception - if that item is not valid. - - >>> iterable = ['1', '2', 'three', '4', None] - >>> list(filter_except(int, iterable, ValueError, TypeError)) - ['1', '2', '4'] - - If an exception other than one given by *exceptions* is raised by - *validator*, it is raised like normal. - """ - for item in iterable: - try: - validator(item) - except exceptions: - pass - else: - yield item - - -def map_except(function, iterable, *exceptions): - """Transform each item from *iterable* with *function* and yield the - result, unless *function* raises one of the specified *exceptions*. - - *function* is called to transform each item in *iterable*. - It should accept one argument. - - >>> iterable = ['1', '2', 'three', '4', None] - >>> list(map_except(int, iterable, ValueError, TypeError)) - [1, 2, 4] - - If an exception other than one given by *exceptions* is raised by - *function*, it is raised like normal. - """ - for item in iterable: - try: - yield function(item) - except exceptions: - pass - - -def map_if(iterable, pred, func, func_else=lambda x: x): - """Evaluate each item from *iterable* using *pred*. If the result is - equivalent to ``True``, transform the item with *func* and yield it. - Otherwise, transform the item with *func_else* and yield it. - - *pred*, *func*, and *func_else* should each be functions that accept - one argument. By default, *func_else* is the identity function. - - >>> from math import sqrt - >>> iterable = list(range(-5, 5)) - >>> iterable - [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4] - >>> list(map_if(iterable, lambda x: x > 3, lambda x: 'toobig')) - [-5, -4, -3, -2, -1, 0, 1, 2, 3, 'toobig'] - >>> list(map_if(iterable, lambda x: x >= 0, - ... lambda x: f'{sqrt(x):.2f}', lambda x: None)) - [None, None, None, None, None, '0.00', '1.00', '1.41', '1.73', '2.00'] - """ - for item in iterable: - yield func(item) if pred(item) else func_else(item) - - -def _sample_unweighted(iterable, k): - # Implementation of "Algorithm L" from the 1994 paper by Kim-Hung Li: - # "Reservoir-Sampling Algorithms of Time Complexity O(n(1+log(N/n)))". - - # Fill up the reservoir (collection of samples) with the first `k` samples - reservoir = take(k, iterable) - - # Generate random number that's the largest in a sample of k U(0,1) numbers - # Largest order statistic: https://en.wikipedia.org/wiki/Order_statistic - W = exp(log(random()) / k) - - # The number of elements to skip before changing the reservoir is a random - # number with a geometric distribution. Sample it using random() and logs. - next_index = k + floor(log(random()) / log(1 - W)) - - for index, element in enumerate(iterable, k): - if index == next_index: - reservoir[randrange(k)] = element - # The new W is the largest in a sample of k U(0, `old_W`) numbers - W *= exp(log(random()) / k) - next_index += floor(log(random()) / log(1 - W)) + 1 - - return reservoir - - -def _sample_weighted(iterable, k, weights): - # Implementation of "A-ExpJ" from the 2006 paper by Efraimidis et al. : - # "Weighted random sampling with a reservoir". - - # Log-transform for numerical stability for weights that are small/large - weight_keys = (log(random()) / weight for weight in weights) - - # Fill up the reservoir (collection of samples) with the first `k` - # weight-keys and elements, then heapify the list. - reservoir = take(k, zip(weight_keys, iterable)) - heapify(reservoir) - - # The number of jumps before changing the reservoir is a random variable - # with an exponential distribution. Sample it using random() and logs. - smallest_weight_key, _ = reservoir[0] - weights_to_skip = log(random()) / smallest_weight_key - - for weight, element in zip(weights, iterable): - if weight >= weights_to_skip: - # The notation here is consistent with the paper, but we store - # the weight-keys in log-space for better numerical stability. - smallest_weight_key, _ = reservoir[0] - t_w = exp(weight * smallest_weight_key) - r_2 = uniform(t_w, 1) # generate U(t_w, 1) - weight_key = log(r_2) / weight - heapreplace(reservoir, (weight_key, element)) - smallest_weight_key, _ = reservoir[0] - weights_to_skip = log(random()) / smallest_weight_key - else: - weights_to_skip -= weight - - # Equivalent to [element for weight_key, element in sorted(reservoir)] - return [heappop(reservoir)[1] for _ in range(k)] - - -def sample(iterable, k, weights=None): - """Return a *k*-length list of elements chosen (without replacement) - from the *iterable*. Like :func:`random.sample`, but works on iterables - of unknown length. - - >>> iterable = range(100) - >>> sample(iterable, 5) # doctest: +SKIP - [81, 60, 96, 16, 4] - - An iterable with *weights* may also be given: - - >>> iterable = range(100) - >>> weights = (i * i + 1 for i in range(100)) - >>> sampled = sample(iterable, 5, weights=weights) # doctest: +SKIP - [79, 67, 74, 66, 78] - - The algorithm can also be used to generate weighted random permutations. - The relative weight of each item determines the probability that it - appears late in the permutation. - - >>> data = "abcdefgh" - >>> weights = range(1, len(data) + 1) - >>> sample(data, k=len(data), weights=weights) # doctest: +SKIP - ['c', 'a', 'b', 'e', 'g', 'd', 'h', 'f'] - """ - if k == 0: - return [] - - iterable = iter(iterable) - if weights is None: - return _sample_unweighted(iterable, k) - else: - weights = iter(weights) - return _sample_weighted(iterable, k, weights) - - -def is_sorted(iterable, key=None, reverse=False, strict=False): - """Returns ``True`` if the items of iterable are in sorted order, and - ``False`` otherwise. *key* and *reverse* have the same meaning that they do - in the built-in :func:`sorted` function. - - >>> is_sorted(['1', '2', '3', '4', '5'], key=int) - True - >>> is_sorted([5, 4, 3, 1, 2], reverse=True) - False - - If *strict*, tests for strict sorting, that is, returns ``False`` if equal - elements are found: - - >>> is_sorted([1, 2, 2]) - True - >>> is_sorted([1, 2, 2], strict=True) - False - - The function returns ``False`` after encountering the first out-of-order - item. If there are no out-of-order items, the iterable is exhausted. - """ - - compare = (le if reverse else ge) if strict else (lt if reverse else gt) - it = iterable if key is None else map(key, iterable) - return not any(starmap(compare, pairwise(it))) - - -class AbortThread(BaseException): - pass - - -class callback_iter: - """Convert a function that uses callbacks to an iterator. - - Let *func* be a function that takes a `callback` keyword argument. - For example: - - >>> def func(callback=None): - ... for i, c in [(1, 'a'), (2, 'b'), (3, 'c')]: - ... if callback: - ... callback(i, c) - ... return 4 - - - Use ``with callback_iter(func)`` to get an iterator over the parameters - that are delivered to the callback. - - >>> with callback_iter(func) as it: - ... for args, kwargs in it: - ... print(args) - (1, 'a') - (2, 'b') - (3, 'c') - - The function will be called in a background thread. The ``done`` property - indicates whether it has completed execution. - - >>> it.done - True - - If it completes successfully, its return value will be available - in the ``result`` property. - - >>> it.result - 4 - - Notes: - - * If the function uses some keyword argument besides ``callback``, supply - *callback_kwd*. - * If it finished executing, but raised an exception, accessing the - ``result`` property will raise the same exception. - * If it hasn't finished executing, accessing the ``result`` - property from within the ``with`` block will raise ``RuntimeError``. - * If it hasn't finished executing, accessing the ``result`` property from - outside the ``with`` block will raise a - ``more_itertools.AbortThread`` exception. - * Provide *wait_seconds* to adjust how frequently the it is polled for - output. - - """ - - def __init__(self, func, callback_kwd='callback', wait_seconds=0.1): - self._func = func - self._callback_kwd = callback_kwd - self._aborted = False - self._future = None - self._wait_seconds = wait_seconds - # Lazily import concurrent.future - self._executor = __import__( - ).futures.__import__("concurrent.futures").futures.ThreadPoolExecutor(max_workers=1) - self._iterator = self._reader() - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - self._aborted = True - self._executor.shutdown() - - def __iter__(self): - return self - - def __next__(self): - return next(self._iterator) - - @property - def done(self): - if self._future is None: - return False - return self._future.done() - - @property - def result(self): - if not self.done: - raise RuntimeError('Function has not yet completed') - - return self._future.result() - - def _reader(self): - q = Queue() - - def callback(*args, **kwargs): - if self._aborted: - raise AbortThread('canceled by user') - - q.put((args, kwargs)) - - self._future = self._executor.submit( - self._func, **{self._callback_kwd: callback} - ) - - while True: - try: - item = q.get(timeout=self._wait_seconds) - except Empty: - pass - else: - q.task_done() - yield item - - if self._future.done(): - break - - remaining = [] - while True: - try: - item = q.get_nowait() - except Empty: - break - else: - q.task_done() - remaining.append(item) - q.join() - yield from remaining - - -def windowed_complete(iterable, n): - """ - Yield ``(beginning, middle, end)`` tuples, where: - - * Each ``middle`` has *n* items from *iterable* - * Each ``beginning`` has the items before the ones in ``middle`` - * Each ``end`` has the items after the ones in ``middle`` - - >>> iterable = range(7) - >>> n = 3 - >>> for beginning, middle, end in windowed_complete(iterable, n): - ... print(beginning, middle, end) - () (0, 1, 2) (3, 4, 5, 6) - (0,) (1, 2, 3) (4, 5, 6) - (0, 1) (2, 3, 4) (5, 6) - (0, 1, 2) (3, 4, 5) (6,) - (0, 1, 2, 3) (4, 5, 6) () - - Note that *n* must be at least 0 and most equal to the length of - *iterable*. - - This function will exhaust the iterable and may require significant - storage. - """ - if n < 0: - raise ValueError('n must be >= 0') - - seq = tuple(iterable) - size = len(seq) - - if n > size: - raise ValueError('n must be <= len(seq)') - - for i in range(size - n + 1): - beginning = seq[:i] - middle = seq[i : i + n] - end = seq[i + n :] - yield beginning, middle, end - - -def all_unique(iterable, key=None): - """ - Returns ``True`` if all the elements of *iterable* are unique (no two - elements are equal). - - >>> all_unique('ABCB') - False - - If a *key* function is specified, it will be used to make comparisons. - - >>> all_unique('ABCb') - True - >>> all_unique('ABCb', str.lower) - False - - The function returns as soon as the first non-unique element is - encountered. Iterables with a mix of hashable and unhashable items can - be used, but the function will be slower for unhashable items. - """ - seenset = set() - seenset_add = seenset.add - seenlist = [] - seenlist_add = seenlist.append - for element in map(key, iterable) if key else iterable: - try: - if element in seenset: - return False - seenset_add(element) - except TypeError: - if element in seenlist: - return False - seenlist_add(element) - return True - - -def nth_product(index, *args): - """Equivalent to ``list(product(*args))[index]``. - - The products of *args* can be ordered lexicographically. - :func:`nth_product` computes the product at sort position *index* without - computing the previous products. - - >>> nth_product(8, range(2), range(2), range(2), range(2)) - (1, 0, 0, 0) - - ``IndexError`` will be raised if the given *index* is invalid. - """ - pools = list(map(tuple, reversed(args))) - ns = list(map(len, pools)) - - c = reduce(mul, ns) - - if index < 0: - index += c - - if not 0 <= index < c: - raise IndexError - - result = [] - for pool, n in zip(pools, ns): - result.append(pool[index % n]) - index //= n - - return tuple(reversed(result)) - - -def nth_permutation(iterable, r, index): - """Equivalent to ``list(permutations(iterable, r))[index]``` - - The subsequences of *iterable* that are of length *r* where order is - important can be ordered lexicographically. :func:`nth_permutation` - computes the subsequence at sort position *index* directly, without - computing the previous subsequences. - - >>> nth_permutation('ghijk', 2, 5) - ('h', 'i') - - ``ValueError`` will be raised If *r* is negative or greater than the length - of *iterable*. - ``IndexError`` will be raised if the given *index* is invalid. - """ - pool = list(iterable) - n = len(pool) - - if r is None or r == n: - r, c = n, factorial(n) - elif not 0 <= r < n: - raise ValueError - else: - c = factorial(n) // factorial(n - r) - - if index < 0: - index += c - - if not 0 <= index < c: - raise IndexError - - if c == 0: - return tuple() - - result = [0] * r - q = index * factorial(n) // c if r < n else index - for d in range(1, n + 1): - q, i = divmod(q, d) - if 0 <= n - d < r: - result[n - d] = i - if q == 0: - break - - return tuple(map(pool.pop, result)) - - -def value_chain(*args): - """Yield all arguments passed to the function in the same order in which - they were passed. If an argument itself is iterable then iterate over its - values. - - >>> list(value_chain(1, 2, 3, [4, 5, 6])) - [1, 2, 3, 4, 5, 6] - - Binary and text strings are not considered iterable and are emitted - as-is: - - >>> list(value_chain('12', '34', ['56', '78'])) - ['12', '34', '56', '78'] - - - Multiple levels of nesting are not flattened. - - """ - for value in args: - if isinstance(value, (str, bytes)): - yield value - continue - try: - yield from value - except TypeError: - yield value - - -def product_index(element, *args): - """Equivalent to ``list(product(*args)).index(element)`` - - The products of *args* can be ordered lexicographically. - :func:`product_index` computes the first index of *element* without - computing the previous products. - - >>> product_index([8, 2], range(10), range(5)) - 42 - - ``ValueError`` will be raised if the given *element* isn't in the product - of *args*. - """ - index = 0 - - for x, pool in zip_longest(element, args, fillvalue=_marker): - if x is _marker or pool is _marker: - raise ValueError('element is not a product of args') - - pool = tuple(pool) - index = index * len(pool) + pool.index(x) - - return index - - -def combination_index(element, iterable): - """Equivalent to ``list(combinations(iterable, r)).index(element)`` - - The subsequences of *iterable* that are of length *r* can be ordered - lexicographically. :func:`combination_index` computes the index of the - first *element*, without computing the previous combinations. - - >>> combination_index('adf', 'abcdefg') - 10 - - ``ValueError`` will be raised if the given *element* isn't one of the - combinations of *iterable*. - """ - element = enumerate(element) - k, y = next(element, (None, None)) - if k is None: - return 0 - - indexes = [] - pool = enumerate(iterable) - for n, x in pool: - if x == y: - indexes.append(n) - tmp, y = next(element, (None, None)) - if tmp is None: - break - else: - k = tmp - else: - raise ValueError('element is not a combination of iterable') - - n, _ = last(pool, default=(n, None)) - - # Python versions below 3.8 don't have math.comb - index = 1 - for i, j in enumerate(reversed(indexes), start=1): - j = n - j - if i <= j: - index += factorial(j) // (factorial(i) * factorial(j - i)) - - return factorial(n + 1) // (factorial(k + 1) * factorial(n - k)) - index - - -def permutation_index(element, iterable): - """Equivalent to ``list(permutations(iterable, r)).index(element)``` - - The subsequences of *iterable* that are of length *r* where order is - important can be ordered lexicographically. :func:`permutation_index` - computes the index of the first *element* directly, without computing - the previous permutations. - - >>> permutation_index([1, 3, 2], range(5)) - 19 - - ``ValueError`` will be raised if the given *element* isn't one of the - permutations of *iterable*. - """ - index = 0 - pool = list(iterable) - for i, x in zip(range(len(pool), -1, -1), element): - r = pool.index(x) - index = index * i + r - del pool[r] - - return index - - -class countable: - """Wrap *iterable* and keep a count of how many items have been consumed. - - The ``items_seen`` attribute starts at ``0`` and increments as the iterable - is consumed: - - >>> iterable = map(str, range(10)) - >>> it = countable(iterable) - >>> it.items_seen - 0 - >>> next(it), next(it) - ('0', '1') - >>> list(it) - ['2', '3', '4', '5', '6', '7', '8', '9'] - >>> it.items_seen - 10 - """ - - def __init__(self, iterable): - self._it = iter(iterable) - self.items_seen = 0 - - def __iter__(self): - return self - - def __next__(self): - item = next(self._it) - self.items_seen += 1 - - return item - - -def chunked_even(iterable, n): - """Break *iterable* into lists of approximately length *n*. - Items are distributed such the lengths of the lists differ by at most - 1 item. - - >>> iterable = [1, 2, 3, 4, 5, 6, 7] - >>> n = 3 - >>> list(chunked_even(iterable, n)) # List lengths: 3, 2, 2 - [[1, 2, 3], [4, 5], [6, 7]] - >>> list(chunked(iterable, n)) # List lengths: 3, 3, 1 - [[1, 2, 3], [4, 5, 6], [7]] - - """ - - len_method = getattr(iterable, '__len__', None) - - if len_method is None: - return _chunked_even_online(iterable, n) - else: - return _chunked_even_finite(iterable, len_method(), n) - - -def _chunked_even_online(iterable, n): - buffer = [] - maxbuf = n + (n - 2) * (n - 1) - for x in iterable: - buffer.append(x) - if len(buffer) == maxbuf: - yield buffer[:n] - buffer = buffer[n:] - yield from _chunked_even_finite(buffer, len(buffer), n) - - -def _chunked_even_finite(iterable, N, n): - if N < 1: - return - - # Lists are either size `full_size <= n` or `partial_size = full_size - 1` - q, r = divmod(N, n) - num_lists = q + (1 if r > 0 else 0) - q, r = divmod(N, num_lists) - full_size = q + (1 if r > 0 else 0) - partial_size = full_size - 1 - num_full = N - partial_size * num_lists - num_partial = num_lists - num_full - - buffer = [] - iterator = iter(iterable) - - # Yield num_full lists of full_size - for x in iterator: - buffer.append(x) - if len(buffer) == full_size: - yield buffer - buffer = [] - num_full -= 1 - if num_full <= 0: - break - - # Yield num_partial lists of partial_size - for x in iterator: - buffer.append(x) - if len(buffer) == partial_size: - yield buffer - buffer = [] - num_partial -= 1 - - -def zip_broadcast(*objects, scalar_types=(str, bytes), strict=False): - """A version of :func:`zip` that "broadcasts" any scalar - (i.e., non-iterable) items into output tuples. - - >>> iterable_1 = [1, 2, 3] - >>> iterable_2 = ['a', 'b', 'c'] - >>> scalar = '_' - >>> list(zip_broadcast(iterable_1, iterable_2, scalar)) - [(1, 'a', '_'), (2, 'b', '_'), (3, 'c', '_')] - - The *scalar_types* keyword argument determines what types are considered - scalar. It is set to ``(str, bytes)`` by default. Set it to ``None`` to - treat strings and byte strings as iterable: - - >>> list(zip_broadcast('abc', 0, 'xyz', scalar_types=None)) - [('a', 0, 'x'), ('b', 0, 'y'), ('c', 0, 'z')] - - If the *strict* keyword argument is ``True``, then - ``UnequalIterablesError`` will be raised if any of the iterables have - different lengths. - """ - - def is_scalar(obj): - if scalar_types and isinstance(obj, scalar_types): - return True - try: - iter(obj) - except TypeError: - return True - else: - return False - - size = len(objects) - if not size: - return - - iterables, iterable_positions = [], [] - scalars, scalar_positions = [], [] - for i, obj in enumerate(objects): - if is_scalar(obj): - scalars.append(obj) - scalar_positions.append(i) - else: - iterables.append(iter(obj)) - iterable_positions.append(i) - - if len(scalars) == size: - yield tuple(objects) - return - - zipper = _zip_equal if strict else zip - for item in zipper(*iterables): - new_item = [None] * size - - for i, elem in zip(iterable_positions, item): - new_item[i] = elem - - for i, elem in zip(scalar_positions, scalars): - new_item[i] = elem - - yield tuple(new_item) - - -def unique_in_window(iterable, n, key=None): - """Yield the items from *iterable* that haven't been seen recently. - *n* is the size of the lookback window. - - >>> iterable = [0, 1, 0, 2, 3, 0] - >>> n = 3 - >>> list(unique_in_window(iterable, n)) - [0, 1, 2, 3, 0] - - The *key* function, if provided, will be used to determine uniqueness: - - >>> list(unique_in_window('abAcda', 3, key=lambda x: x.lower())) - ['a', 'b', 'c', 'd', 'a'] - - The items in *iterable* must be hashable. - - """ - if n <= 0: - raise ValueError('n must be greater than 0') - - window = deque(maxlen=n) - uniques = set() - use_key = key is not None - - for item in iterable: - k = key(item) if use_key else item - if k in uniques: - continue - - if len(uniques) == n: - uniques.discard(window[0]) - - uniques.add(k) - window.append(k) - - yield item - - -def duplicates_everseen(iterable, key=None): - """Yield duplicate elements after their first appearance. - - >>> list(duplicates_everseen('mississippi')) - ['s', 'i', 's', 's', 'i', 'p', 'i'] - >>> list(duplicates_everseen('AaaBbbCccAaa', str.lower)) - ['a', 'a', 'b', 'b', 'c', 'c', 'A', 'a', 'a'] - - This function is analagous to :func:`unique_everseen` and is subject to - the same performance considerations. - - """ - seen_set = set() - seen_list = [] - use_key = key is not None - - for element in iterable: - k = key(element) if use_key else element - try: - if k not in seen_set: - seen_set.add(k) - else: - yield element - except TypeError: - if k not in seen_list: - seen_list.append(k) - else: - yield element - - -def duplicates_justseen(iterable, key=None): - """Yields serially-duplicate elements after their first appearance. - - >>> list(duplicates_justseen('mississippi')) - ['s', 's', 'p'] - >>> list(duplicates_justseen('AaaBbbCccAaa', str.lower)) - ['a', 'a', 'b', 'b', 'c', 'c', 'a', 'a'] - - This function is analagous to :func:`unique_justseen`. - - """ - return flatten( - map( - lambda group_tuple: islice_extended(group_tuple[1])[1:], - groupby(iterable, key), - ) - ) - - -def minmax(iterable_or_value, *others, key=None, default=_marker): - """Returns both the smallest and largest items in an iterable - or the largest of two or more arguments. - - >>> minmax([3, 1, 5]) - (1, 5) - - >>> minmax(4, 2, 6) - (2, 6) - - If a *key* function is provided, it will be used to transform the input - items for comparison. - - >>> minmax([5, 30], key=str) # '30' sorts before '5' - (30, 5) - - If a *default* value is provided, it will be returned if there are no - input items. - - >>> minmax([], default=(0, 0)) - (0, 0) - - Otherwise ``ValueError`` is raised. - - This function is based on the - `recipe `__ by - Raymond Hettinger and takes care to minimize the number of comparisons - performed. - """ - iterable = (iterable_or_value, *others) if others else iterable_or_value - - it = iter(iterable) - - try: - lo = hi = next(it) - except StopIteration as e: - if default is _marker: - raise ValueError( - '`minmax()` argument is an empty iterable. ' - 'Provide a `default` value to suppress this error.' - ) from e - return default - - # Different branches depending on the presence of key. This saves a lot - # of unimportant copies which would slow the "key=None" branch - # significantly down. - if key is None: - for x, y in zip_longest(it, it, fillvalue=lo): - if y < x: - x, y = y, x - if x < lo: - lo = x - if hi < y: - hi = y - - else: - lo_key = hi_key = key(lo) - - for x, y in zip_longest(it, it, fillvalue=lo): - x_key, y_key = key(x), key(y) - - if y_key < x_key: - x, y, x_key, y_key = y, x, y_key, x_key - if x_key < lo_key: - lo, lo_key = x, x_key - if hi_key < y_key: - hi, hi_key = y, y_key - - return lo, hi - - -def constrained_batches( - iterable, max_size, max_count=None, get_len=len, strict=True -): - """Yield batches of items from *iterable* with a combined size limited by - *max_size*. - - >>> iterable = [b'12345', b'123', b'12345678', b'1', b'1', b'12', b'1'] - >>> list(constrained_batches(iterable, 10)) - [(b'12345', b'123'), (b'12345678', b'1', b'1'), (b'12', b'1')] - - If a *max_count* is supplied, the number of items per batch is also - limited: - - >>> iterable = [b'12345', b'123', b'12345678', b'1', b'1', b'12', b'1'] - >>> list(constrained_batches(iterable, 10, max_count = 2)) - [(b'12345', b'123'), (b'12345678', b'1'), (b'1', b'12'), (b'1',)] - - If a *get_len* function is supplied, use that instead of :func:`len` to - determine item size. - - If *strict* is ``True``, raise ``ValueError`` if any single item is bigger - than *max_size*. Otherwise, allow single items to exceed *max_size*. - """ - if max_size <= 0: - raise ValueError('maximum size must be greater than zero') - - batch = [] - batch_size = 0 - batch_count = 0 - for item in iterable: - item_len = get_len(item) - if strict and item_len > max_size: - raise ValueError('item size exceeds maximum size') - - reached_count = batch_count == max_count - reached_size = item_len + batch_size > max_size - if batch_count and (reached_size or reached_count): - yield tuple(batch) - batch.clear() - batch_size = 0 - batch_count = 0 - - batch.append(item) - batch_size += item_len - batch_count += 1 - - if batch: - yield tuple(batch) - - -def gray_product(*iterables): - """Like :func:`itertools.product`, but return tuples in an order such - that only one element in the generated tuple changes from one iteration - to the next. - - >>> list(gray_product('AB','CD')) - [('A', 'C'), ('B', 'C'), ('B', 'D'), ('A', 'D')] - - This function consumes all of the input iterables before producing output. - If any of the input iterables have fewer than two items, ``ValueError`` - is raised. - - For information on the algorithm, see - `this section `__ - of Donald Knuth's *The Art of Computer Programming*. - """ - all_iterables = tuple(tuple(x) for x in iterables) - iterable_count = len(all_iterables) - for iterable in all_iterables: - if len(iterable) < 2: - raise ValueError("each iterable must have two or more items") - - # This is based on "Algorithm H" from section 7.2.1.1, page 20. - # a holds the indexes of the source iterables for the n-tuple to be yielded - # f is the array of "focus pointers" - # o is the array of "directions" - a = [0] * iterable_count - f = list(range(iterable_count + 1)) - o = [1] * iterable_count - while True: - yield tuple(all_iterables[i][a[i]] for i in range(iterable_count)) - j = f[0] - f[0] = 0 - if j == iterable_count: - break - a[j] = a[j] + o[j] - if a[j] == 0 or a[j] == len(all_iterables[j]) - 1: - o[j] = -o[j] - f[j] = f[j + 1] - f[j + 1] = j + 1 diff --git a/pkg_resources/_vendor/more_itertools/more.pyi b/pkg_resources/_vendor/more_itertools/more.pyi deleted file mode 100644 index 75c5232c1a..0000000000 --- a/pkg_resources/_vendor/more_itertools/more.pyi +++ /dev/null @@ -1,666 +0,0 @@ -"""Stubs for more_itertools.more""" -from __future__ import annotations - -from types import TracebackType -from typing import ( - Any, - Callable, - Container, - ContextManager, - Generic, - Hashable, - Iterable, - Iterator, - overload, - Reversible, - Sequence, - Sized, - Type, - TypeVar, - type_check_only, -) -from typing_extensions import Protocol - -# Type and type variable definitions -_T = TypeVar('_T') -_T1 = TypeVar('_T1') -_T2 = TypeVar('_T2') -_U = TypeVar('_U') -_V = TypeVar('_V') -_W = TypeVar('_W') -_T_co = TypeVar('_T_co', covariant=True) -_GenFn = TypeVar('_GenFn', bound=Callable[..., Iterator[object]]) -_Raisable = BaseException | Type[BaseException] - -@type_check_only -class _SizedIterable(Protocol[_T_co], Sized, Iterable[_T_co]): ... - -@type_check_only -class _SizedReversible(Protocol[_T_co], Sized, Reversible[_T_co]): ... - -@type_check_only -class _SupportsSlicing(Protocol[_T_co]): - def __getitem__(self, __k: slice) -> _T_co: ... - -def chunked( - iterable: Iterable[_T], n: int | None, strict: bool = ... -) -> Iterator[list[_T]]: ... -@overload -def first(iterable: Iterable[_T]) -> _T: ... -@overload -def first(iterable: Iterable[_T], default: _U) -> _T | _U: ... -@overload -def last(iterable: Iterable[_T]) -> _T: ... -@overload -def last(iterable: Iterable[_T], default: _U) -> _T | _U: ... -@overload -def nth_or_last(iterable: Iterable[_T], n: int) -> _T: ... -@overload -def nth_or_last(iterable: Iterable[_T], n: int, default: _U) -> _T | _U: ... - -class peekable(Generic[_T], Iterator[_T]): - def __init__(self, iterable: Iterable[_T]) -> None: ... - def __iter__(self) -> peekable[_T]: ... - def __bool__(self) -> bool: ... - @overload - def peek(self) -> _T: ... - @overload - def peek(self, default: _U) -> _T | _U: ... - def prepend(self, *items: _T) -> None: ... - def __next__(self) -> _T: ... - @overload - def __getitem__(self, index: int) -> _T: ... - @overload - def __getitem__(self, index: slice) -> list[_T]: ... - -def consumer(func: _GenFn) -> _GenFn: ... -def ilen(iterable: Iterable[object]) -> int: ... -def iterate(func: Callable[[_T], _T], start: _T) -> Iterator[_T]: ... -def with_iter( - context_manager: ContextManager[Iterable[_T]], -) -> Iterator[_T]: ... -def one( - iterable: Iterable[_T], - too_short: _Raisable | None = ..., - too_long: _Raisable | None = ..., -) -> _T: ... -def raise_(exception: _Raisable, *args: Any) -> None: ... -def strictly_n( - iterable: Iterable[_T], - n: int, - too_short: _GenFn | None = ..., - too_long: _GenFn | None = ..., -) -> list[_T]: ... -def distinct_permutations( - iterable: Iterable[_T], r: int | None = ... -) -> Iterator[tuple[_T, ...]]: ... -def intersperse( - e: _U, iterable: Iterable[_T], n: int = ... -) -> Iterator[_T | _U]: ... -def unique_to_each(*iterables: Iterable[_T]) -> list[list[_T]]: ... -@overload -def windowed( - seq: Iterable[_T], n: int, *, step: int = ... -) -> Iterator[tuple[_T | None, ...]]: ... -@overload -def windowed( - seq: Iterable[_T], n: int, fillvalue: _U, step: int = ... -) -> Iterator[tuple[_T | _U, ...]]: ... -def substrings(iterable: Iterable[_T]) -> Iterator[tuple[_T, ...]]: ... -def substrings_indexes( - seq: Sequence[_T], reverse: bool = ... -) -> Iterator[tuple[Sequence[_T], int, int]]: ... - -class bucket(Generic[_T, _U], Container[_U]): - def __init__( - self, - iterable: Iterable[_T], - key: Callable[[_T], _U], - validator: Callable[[object], object] | None = ..., - ) -> None: ... - def __contains__(self, value: object) -> bool: ... - def __iter__(self) -> Iterator[_U]: ... - def __getitem__(self, value: object) -> Iterator[_T]: ... - -def spy( - iterable: Iterable[_T], n: int = ... -) -> tuple[list[_T], Iterator[_T]]: ... -def interleave(*iterables: Iterable[_T]) -> Iterator[_T]: ... -def interleave_longest(*iterables: Iterable[_T]) -> Iterator[_T]: ... -def interleave_evenly( - iterables: list[Iterable[_T]], lengths: list[int] | None = ... -) -> Iterator[_T]: ... -def collapse( - iterable: Iterable[Any], - base_type: type | None = ..., - levels: int | None = ..., -) -> Iterator[Any]: ... -@overload -def side_effect( - func: Callable[[_T], object], - iterable: Iterable[_T], - chunk_size: None = ..., - before: Callable[[], object] | None = ..., - after: Callable[[], object] | None = ..., -) -> Iterator[_T]: ... -@overload -def side_effect( - func: Callable[[list[_T]], object], - iterable: Iterable[_T], - chunk_size: int, - before: Callable[[], object] | None = ..., - after: Callable[[], object] | None = ..., -) -> Iterator[_T]: ... -def sliced( - seq: _SupportsSlicing[_T], n: int, strict: bool = ... -) -> Iterator[_T]: ... -def split_at( - iterable: Iterable[_T], - pred: Callable[[_T], object], - maxsplit: int = ..., - keep_separator: bool = ..., -) -> Iterator[list[_T]]: ... -def split_before( - iterable: Iterable[_T], pred: Callable[[_T], object], maxsplit: int = ... -) -> Iterator[list[_T]]: ... -def split_after( - iterable: Iterable[_T], pred: Callable[[_T], object], maxsplit: int = ... -) -> Iterator[list[_T]]: ... -def split_when( - iterable: Iterable[_T], - pred: Callable[[_T, _T], object], - maxsplit: int = ..., -) -> Iterator[list[_T]]: ... -def split_into( - iterable: Iterable[_T], sizes: Iterable[int | None] -) -> Iterator[list[_T]]: ... -@overload -def padded( - iterable: Iterable[_T], - *, - n: int | None = ..., - next_multiple: bool = ..., -) -> Iterator[_T | None]: ... -@overload -def padded( - iterable: Iterable[_T], - fillvalue: _U, - n: int | None = ..., - next_multiple: bool = ..., -) -> Iterator[_T | _U]: ... -@overload -def repeat_last(iterable: Iterable[_T]) -> Iterator[_T]: ... -@overload -def repeat_last(iterable: Iterable[_T], default: _U) -> Iterator[_T | _U]: ... -def distribute(n: int, iterable: Iterable[_T]) -> list[Iterator[_T]]: ... -@overload -def stagger( - iterable: Iterable[_T], - offsets: _SizedIterable[int] = ..., - longest: bool = ..., -) -> Iterator[tuple[_T | None, ...]]: ... -@overload -def stagger( - iterable: Iterable[_T], - offsets: _SizedIterable[int] = ..., - longest: bool = ..., - fillvalue: _U = ..., -) -> Iterator[tuple[_T | _U, ...]]: ... - -class UnequalIterablesError(ValueError): - def __init__(self, details: tuple[int, int, int] | None = ...) -> None: ... - -@overload -def zip_equal(__iter1: Iterable[_T1]) -> Iterator[tuple[_T1]]: ... -@overload -def zip_equal( - __iter1: Iterable[_T1], __iter2: Iterable[_T2] -) -> Iterator[tuple[_T1, _T2]]: ... -@overload -def zip_equal( - __iter1: Iterable[_T], - __iter2: Iterable[_T], - __iter3: Iterable[_T], - *iterables: Iterable[_T], -) -> Iterator[tuple[_T, ...]]: ... -@overload -def zip_offset( - __iter1: Iterable[_T1], - *, - offsets: _SizedIterable[int], - longest: bool = ..., - fillvalue: None = None, -) -> Iterator[tuple[_T1 | None]]: ... -@overload -def zip_offset( - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - *, - offsets: _SizedIterable[int], - longest: bool = ..., - fillvalue: None = None, -) -> Iterator[tuple[_T1 | None, _T2 | None]]: ... -@overload -def zip_offset( - __iter1: Iterable[_T], - __iter2: Iterable[_T], - __iter3: Iterable[_T], - *iterables: Iterable[_T], - offsets: _SizedIterable[int], - longest: bool = ..., - fillvalue: None = None, -) -> Iterator[tuple[_T | None, ...]]: ... -@overload -def zip_offset( - __iter1: Iterable[_T1], - *, - offsets: _SizedIterable[int], - longest: bool = ..., - fillvalue: _U, -) -> Iterator[tuple[_T1 | _U]]: ... -@overload -def zip_offset( - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - *, - offsets: _SizedIterable[int], - longest: bool = ..., - fillvalue: _U, -) -> Iterator[tuple[_T1 | _U, _T2 | _U]]: ... -@overload -def zip_offset( - __iter1: Iterable[_T], - __iter2: Iterable[_T], - __iter3: Iterable[_T], - *iterables: Iterable[_T], - offsets: _SizedIterable[int], - longest: bool = ..., - fillvalue: _U, -) -> Iterator[tuple[_T | _U, ...]]: ... -def sort_together( - iterables: Iterable[Iterable[_T]], - key_list: Iterable[int] = ..., - key: Callable[..., Any] | None = ..., - reverse: bool = ..., -) -> list[tuple[_T, ...]]: ... -def unzip(iterable: Iterable[Sequence[_T]]) -> tuple[Iterator[_T], ...]: ... -def divide(n: int, iterable: Iterable[_T]) -> list[Iterator[_T]]: ... -def always_iterable( - obj: object, - base_type: type | tuple[type | tuple[Any, ...], ...] | None = ..., -) -> Iterator[Any]: ... -def adjacent( - predicate: Callable[[_T], bool], - iterable: Iterable[_T], - distance: int = ..., -) -> Iterator[tuple[bool, _T]]: ... -@overload -def groupby_transform( - iterable: Iterable[_T], - keyfunc: None = None, - valuefunc: None = None, - reducefunc: None = None, -) -> Iterator[tuple[_T, Iterator[_T]]]: ... -@overload -def groupby_transform( - iterable: Iterable[_T], - keyfunc: Callable[[_T], _U], - valuefunc: None, - reducefunc: None, -) -> Iterator[tuple[_U, Iterator[_T]]]: ... -@overload -def groupby_transform( - iterable: Iterable[_T], - keyfunc: None, - valuefunc: Callable[[_T], _V], - reducefunc: None, -) -> Iterable[tuple[_T, Iterable[_V]]]: ... -@overload -def groupby_transform( - iterable: Iterable[_T], - keyfunc: Callable[[_T], _U], - valuefunc: Callable[[_T], _V], - reducefunc: None, -) -> Iterable[tuple[_U, Iterator[_V]]]: ... -@overload -def groupby_transform( - iterable: Iterable[_T], - keyfunc: None, - valuefunc: None, - reducefunc: Callable[[Iterator[_T]], _W], -) -> Iterable[tuple[_T, _W]]: ... -@overload -def groupby_transform( - iterable: Iterable[_T], - keyfunc: Callable[[_T], _U], - valuefunc: None, - reducefunc: Callable[[Iterator[_T]], _W], -) -> Iterable[tuple[_U, _W]]: ... -@overload -def groupby_transform( - iterable: Iterable[_T], - keyfunc: None, - valuefunc: Callable[[_T], _V], - reducefunc: Callable[[Iterable[_V]], _W], -) -> Iterable[tuple[_T, _W]]: ... -@overload -def groupby_transform( - iterable: Iterable[_T], - keyfunc: Callable[[_T], _U], - valuefunc: Callable[[_T], _V], - reducefunc: Callable[[Iterable[_V]], _W], -) -> Iterable[tuple[_U, _W]]: ... - -class numeric_range(Generic[_T, _U], Sequence[_T], Hashable, Reversible[_T]): - @overload - def __init__(self, __stop: _T) -> None: ... - @overload - def __init__(self, __start: _T, __stop: _T) -> None: ... - @overload - def __init__(self, __start: _T, __stop: _T, __step: _U) -> None: ... - def __bool__(self) -> bool: ... - def __contains__(self, elem: object) -> bool: ... - def __eq__(self, other: object) -> bool: ... - @overload - def __getitem__(self, key: int) -> _T: ... - @overload - def __getitem__(self, key: slice) -> numeric_range[_T, _U]: ... - def __hash__(self) -> int: ... - def __iter__(self) -> Iterator[_T]: ... - def __len__(self) -> int: ... - def __reduce__( - self, - ) -> tuple[Type[numeric_range[_T, _U]], tuple[_T, _T, _U]]: ... - def __repr__(self) -> str: ... - def __reversed__(self) -> Iterator[_T]: ... - def count(self, value: _T) -> int: ... - def index(self, value: _T) -> int: ... # type: ignore - -def count_cycle( - iterable: Iterable[_T], n: int | None = ... -) -> Iterable[tuple[int, _T]]: ... -def mark_ends( - iterable: Iterable[_T], -) -> Iterable[tuple[bool, bool, _T]]: ... -def locate( - iterable: Iterable[object], - pred: Callable[..., Any] = ..., - window_size: int | None = ..., -) -> Iterator[int]: ... -def lstrip( - iterable: Iterable[_T], pred: Callable[[_T], object] -) -> Iterator[_T]: ... -def rstrip( - iterable: Iterable[_T], pred: Callable[[_T], object] -) -> Iterator[_T]: ... -def strip( - iterable: Iterable[_T], pred: Callable[[_T], object] -) -> Iterator[_T]: ... - -class islice_extended(Generic[_T], Iterator[_T]): - def __init__(self, iterable: Iterable[_T], *args: int | None) -> None: ... - def __iter__(self) -> islice_extended[_T]: ... - def __next__(self) -> _T: ... - def __getitem__(self, index: slice) -> islice_extended[_T]: ... - -def always_reversible(iterable: Iterable[_T]) -> Iterator[_T]: ... -def consecutive_groups( - iterable: Iterable[_T], ordering: Callable[[_T], int] = ... -) -> Iterator[Iterator[_T]]: ... -@overload -def difference( - iterable: Iterable[_T], - func: Callable[[_T, _T], _U] = ..., - *, - initial: None = ..., -) -> Iterator[_T | _U]: ... -@overload -def difference( - iterable: Iterable[_T], func: Callable[[_T, _T], _U] = ..., *, initial: _U -) -> Iterator[_U]: ... - -class SequenceView(Generic[_T], Sequence[_T]): - def __init__(self, target: Sequence[_T]) -> None: ... - @overload - def __getitem__(self, index: int) -> _T: ... - @overload - def __getitem__(self, index: slice) -> Sequence[_T]: ... - def __len__(self) -> int: ... - -class seekable(Generic[_T], Iterator[_T]): - def __init__( - self, iterable: Iterable[_T], maxlen: int | None = ... - ) -> None: ... - def __iter__(self) -> seekable[_T]: ... - def __next__(self) -> _T: ... - def __bool__(self) -> bool: ... - @overload - def peek(self) -> _T: ... - @overload - def peek(self, default: _U) -> _T | _U: ... - def elements(self) -> SequenceView[_T]: ... - def seek(self, index: int) -> None: ... - -class run_length: - @staticmethod - def encode(iterable: Iterable[_T]) -> Iterator[tuple[_T, int]]: ... - @staticmethod - def decode(iterable: Iterable[tuple[_T, int]]) -> Iterator[_T]: ... - -def exactly_n( - iterable: Iterable[_T], n: int, predicate: Callable[[_T], object] = ... -) -> bool: ... -def circular_shifts(iterable: Iterable[_T]) -> list[tuple[_T, ...]]: ... -def make_decorator( - wrapping_func: Callable[..., _U], result_index: int = ... -) -> Callable[..., Callable[[Callable[..., Any]], Callable[..., _U]]]: ... -@overload -def map_reduce( - iterable: Iterable[_T], - keyfunc: Callable[[_T], _U], - valuefunc: None = ..., - reducefunc: None = ..., -) -> dict[_U, list[_T]]: ... -@overload -def map_reduce( - iterable: Iterable[_T], - keyfunc: Callable[[_T], _U], - valuefunc: Callable[[_T], _V], - reducefunc: None = ..., -) -> dict[_U, list[_V]]: ... -@overload -def map_reduce( - iterable: Iterable[_T], - keyfunc: Callable[[_T], _U], - valuefunc: None = ..., - reducefunc: Callable[[list[_T]], _W] = ..., -) -> dict[_U, _W]: ... -@overload -def map_reduce( - iterable: Iterable[_T], - keyfunc: Callable[[_T], _U], - valuefunc: Callable[[_T], _V], - reducefunc: Callable[[list[_V]], _W], -) -> dict[_U, _W]: ... -def rlocate( - iterable: Iterable[_T], - pred: Callable[..., object] = ..., - window_size: int | None = ..., -) -> Iterator[int]: ... -def replace( - iterable: Iterable[_T], - pred: Callable[..., object], - substitutes: Iterable[_U], - count: int | None = ..., - window_size: int = ..., -) -> Iterator[_T | _U]: ... -def partitions(iterable: Iterable[_T]) -> Iterator[list[list[_T]]]: ... -def set_partitions( - iterable: Iterable[_T], k: int | None = ... -) -> Iterator[list[list[_T]]]: ... - -class time_limited(Generic[_T], Iterator[_T]): - def __init__( - self, limit_seconds: float, iterable: Iterable[_T] - ) -> None: ... - def __iter__(self) -> islice_extended[_T]: ... - def __next__(self) -> _T: ... - -@overload -def only( - iterable: Iterable[_T], *, too_long: _Raisable | None = ... -) -> _T | None: ... -@overload -def only( - iterable: Iterable[_T], default: _U, too_long: _Raisable | None = ... -) -> _T | _U: ... -def ichunked(iterable: Iterable[_T], n: int) -> Iterator[Iterator[_T]]: ... -def distinct_combinations( - iterable: Iterable[_T], r: int -) -> Iterator[tuple[_T, ...]]: ... -def filter_except( - validator: Callable[[Any], object], - iterable: Iterable[_T], - *exceptions: Type[BaseException], -) -> Iterator[_T]: ... -def map_except( - function: Callable[[Any], _U], - iterable: Iterable[_T], - *exceptions: Type[BaseException], -) -> Iterator[_U]: ... -def map_if( - iterable: Iterable[Any], - pred: Callable[[Any], bool], - func: Callable[[Any], Any], - func_else: Callable[[Any], Any] | None = ..., -) -> Iterator[Any]: ... -def sample( - iterable: Iterable[_T], - k: int, - weights: Iterable[float] | None = ..., -) -> list[_T]: ... -def is_sorted( - iterable: Iterable[_T], - key: Callable[[_T], _U] | None = ..., - reverse: bool = False, - strict: bool = False, -) -> bool: ... - -class AbortThread(BaseException): - pass - -class callback_iter(Generic[_T], Iterator[_T]): - def __init__( - self, - func: Callable[..., Any], - callback_kwd: str = ..., - wait_seconds: float = ..., - ) -> None: ... - def __enter__(self) -> callback_iter[_T]: ... - def __exit__( - self, - exc_type: Type[BaseException] | None, - exc_value: BaseException | None, - traceback: TracebackType | None, - ) -> bool | None: ... - def __iter__(self) -> callback_iter[_T]: ... - def __next__(self) -> _T: ... - def _reader(self) -> Iterator[_T]: ... - @property - def done(self) -> bool: ... - @property - def result(self) -> Any: ... - -def windowed_complete( - iterable: Iterable[_T], n: int -) -> Iterator[tuple[_T, ...]]: ... -def all_unique( - iterable: Iterable[_T], key: Callable[[_T], _U] | None = ... -) -> bool: ... -def nth_product(index: int, *args: Iterable[_T]) -> tuple[_T, ...]: ... -def nth_permutation( - iterable: Iterable[_T], r: int, index: int -) -> tuple[_T, ...]: ... -def value_chain(*args: _T | Iterable[_T]) -> Iterable[_T]: ... -def product_index(element: Iterable[_T], *args: Iterable[_T]) -> int: ... -def combination_index( - element: Iterable[_T], iterable: Iterable[_T] -) -> int: ... -def permutation_index( - element: Iterable[_T], iterable: Iterable[_T] -) -> int: ... -def repeat_each(iterable: Iterable[_T], n: int = ...) -> Iterator[_T]: ... - -class countable(Generic[_T], Iterator[_T]): - def __init__(self, iterable: Iterable[_T]) -> None: ... - def __iter__(self) -> countable[_T]: ... - def __next__(self) -> _T: ... - -def chunked_even(iterable: Iterable[_T], n: int) -> Iterator[list[_T]]: ... -def zip_broadcast( - *objects: _T | Iterable[_T], - scalar_types: type | tuple[type | tuple[Any, ...], ...] | None = ..., - strict: bool = ..., -) -> Iterable[tuple[_T, ...]]: ... -def unique_in_window( - iterable: Iterable[_T], n: int, key: Callable[[_T], _U] | None = ... -) -> Iterator[_T]: ... -def duplicates_everseen( - iterable: Iterable[_T], key: Callable[[_T], _U] | None = ... -) -> Iterator[_T]: ... -def duplicates_justseen( - iterable: Iterable[_T], key: Callable[[_T], _U] | None = ... -) -> Iterator[_T]: ... - -class _SupportsLessThan(Protocol): - def __lt__(self, __other: Any) -> bool: ... - -_SupportsLessThanT = TypeVar("_SupportsLessThanT", bound=_SupportsLessThan) - -@overload -def minmax( - iterable_or_value: Iterable[_SupportsLessThanT], *, key: None = None -) -> tuple[_SupportsLessThanT, _SupportsLessThanT]: ... -@overload -def minmax( - iterable_or_value: Iterable[_T], *, key: Callable[[_T], _SupportsLessThan] -) -> tuple[_T, _T]: ... -@overload -def minmax( - iterable_or_value: Iterable[_SupportsLessThanT], - *, - key: None = None, - default: _U, -) -> _U | tuple[_SupportsLessThanT, _SupportsLessThanT]: ... -@overload -def minmax( - iterable_or_value: Iterable[_T], - *, - key: Callable[[_T], _SupportsLessThan], - default: _U, -) -> _U | tuple[_T, _T]: ... -@overload -def minmax( - iterable_or_value: _SupportsLessThanT, - __other: _SupportsLessThanT, - *others: _SupportsLessThanT, -) -> tuple[_SupportsLessThanT, _SupportsLessThanT]: ... -@overload -def minmax( - iterable_or_value: _T, - __other: _T, - *others: _T, - key: Callable[[_T], _SupportsLessThan], -) -> tuple[_T, _T]: ... -def longest_common_prefix( - iterables: Iterable[Iterable[_T]], -) -> Iterator[_T]: ... -def iequals(*iterables: Iterable[object]) -> bool: ... -def constrained_batches( - iterable: Iterable[object], - max_size: int, - max_count: int | None = ..., - get_len: Callable[[_T], object] = ..., - strict: bool = ..., -) -> Iterator[tuple[_T]]: ... -def gray_product(*iterables: Iterable[_T]) -> Iterator[tuple[_T, ...]]: ... diff --git a/pkg_resources/_vendor/more_itertools/recipes.py b/pkg_resources/_vendor/more_itertools/recipes.py deleted file mode 100644 index 3facc2e3a6..0000000000 --- a/pkg_resources/_vendor/more_itertools/recipes.py +++ /dev/null @@ -1,930 +0,0 @@ -"""Imported from the recipes section of the itertools documentation. - -All functions taken from the recipes section of the itertools library docs -[1]_. -Some backward-compatible usability improvements have been made. - -.. [1] http://docs.python.org/library/itertools.html#recipes - -""" -import math -import operator -import warnings - -from collections import deque -from collections.abc import Sized -from functools import reduce -from itertools import ( - chain, - combinations, - compress, - count, - cycle, - groupby, - islice, - product, - repeat, - starmap, - tee, - zip_longest, -) -from random import randrange, sample, choice -from sys import hexversion - -__all__ = [ - 'all_equal', - 'batched', - 'before_and_after', - 'consume', - 'convolve', - 'dotproduct', - 'first_true', - 'factor', - 'flatten', - 'grouper', - 'iter_except', - 'iter_index', - 'matmul', - 'ncycles', - 'nth', - 'nth_combination', - 'padnone', - 'pad_none', - 'pairwise', - 'partition', - 'polynomial_from_roots', - 'powerset', - 'prepend', - 'quantify', - 'random_combination_with_replacement', - 'random_combination', - 'random_permutation', - 'random_product', - 'repeatfunc', - 'roundrobin', - 'sieve', - 'sliding_window', - 'subslices', - 'tabulate', - 'tail', - 'take', - 'transpose', - 'triplewise', - 'unique_everseen', - 'unique_justseen', -] - -_marker = object() - - -def take(n, iterable): - """Return first *n* items of the iterable as a list. - - >>> take(3, range(10)) - [0, 1, 2] - - If there are fewer than *n* items in the iterable, all of them are - returned. - - >>> take(10, range(3)) - [0, 1, 2] - - """ - return list(islice(iterable, n)) - - -def tabulate(function, start=0): - """Return an iterator over the results of ``func(start)``, - ``func(start + 1)``, ``func(start + 2)``... - - *func* should be a function that accepts one integer argument. - - If *start* is not specified it defaults to 0. It will be incremented each - time the iterator is advanced. - - >>> square = lambda x: x ** 2 - >>> iterator = tabulate(square, -3) - >>> take(4, iterator) - [9, 4, 1, 0] - - """ - return map(function, count(start)) - - -def tail(n, iterable): - """Return an iterator over the last *n* items of *iterable*. - - >>> t = tail(3, 'ABCDEFG') - >>> list(t) - ['E', 'F', 'G'] - - """ - # If the given iterable has a length, then we can use islice to get its - # final elements. Note that if the iterable is not actually Iterable, - # either islice or deque will throw a TypeError. This is why we don't - # check if it is Iterable. - if isinstance(iterable, Sized): - yield from islice(iterable, max(0, len(iterable) - n), None) - else: - yield from iter(deque(iterable, maxlen=n)) - - -def consume(iterator, n=None): - """Advance *iterable* by *n* steps. If *n* is ``None``, consume it - entirely. - - Efficiently exhausts an iterator without returning values. Defaults to - consuming the whole iterator, but an optional second argument may be - provided to limit consumption. - - >>> i = (x for x in range(10)) - >>> next(i) - 0 - >>> consume(i, 3) - >>> next(i) - 4 - >>> consume(i) - >>> next(i) - Traceback (most recent call last): - File "", line 1, in - StopIteration - - If the iterator has fewer items remaining than the provided limit, the - whole iterator will be consumed. - - >>> i = (x for x in range(3)) - >>> consume(i, 5) - >>> next(i) - Traceback (most recent call last): - File "", line 1, in - StopIteration - - """ - # Use functions that consume iterators at C speed. - if n is None: - # feed the entire iterator into a zero-length deque - deque(iterator, maxlen=0) - else: - # advance to the empty slice starting at position n - next(islice(iterator, n, n), None) - - -def nth(iterable, n, default=None): - """Returns the nth item or a default value. - - >>> l = range(10) - >>> nth(l, 3) - 3 - >>> nth(l, 20, "zebra") - 'zebra' - - """ - return next(islice(iterable, n, None), default) - - -def all_equal(iterable): - """ - Returns ``True`` if all the elements are equal to each other. - - >>> all_equal('aaaa') - True - >>> all_equal('aaab') - False - - """ - g = groupby(iterable) - return next(g, True) and not next(g, False) - - -def quantify(iterable, pred=bool): - """Return the how many times the predicate is true. - - >>> quantify([True, False, True]) - 2 - - """ - return sum(map(pred, iterable)) - - -def pad_none(iterable): - """Returns the sequence of elements and then returns ``None`` indefinitely. - - >>> take(5, pad_none(range(3))) - [0, 1, 2, None, None] - - Useful for emulating the behavior of the built-in :func:`map` function. - - See also :func:`padded`. - - """ - return chain(iterable, repeat(None)) - - -padnone = pad_none - - -def ncycles(iterable, n): - """Returns the sequence elements *n* times - - >>> list(ncycles(["a", "b"], 3)) - ['a', 'b', 'a', 'b', 'a', 'b'] - - """ - return chain.from_iterable(repeat(tuple(iterable), n)) - - -def dotproduct(vec1, vec2): - """Returns the dot product of the two iterables. - - >>> dotproduct([10, 10], [20, 20]) - 400 - - """ - return sum(map(operator.mul, vec1, vec2)) - - -def flatten(listOfLists): - """Return an iterator flattening one level of nesting in a list of lists. - - >>> list(flatten([[0, 1], [2, 3]])) - [0, 1, 2, 3] - - See also :func:`collapse`, which can flatten multiple levels of nesting. - - """ - return chain.from_iterable(listOfLists) - - -def repeatfunc(func, times=None, *args): - """Call *func* with *args* repeatedly, returning an iterable over the - results. - - If *times* is specified, the iterable will terminate after that many - repetitions: - - >>> from operator import add - >>> times = 4 - >>> args = 3, 5 - >>> list(repeatfunc(add, times, *args)) - [8, 8, 8, 8] - - If *times* is ``None`` the iterable will not terminate: - - >>> from random import randrange - >>> times = None - >>> args = 1, 11 - >>> take(6, repeatfunc(randrange, times, *args)) # doctest:+SKIP - [2, 4, 8, 1, 8, 4] - - """ - if times is None: - return starmap(func, repeat(args)) - return starmap(func, repeat(args, times)) - - -def _pairwise(iterable): - """Returns an iterator of paired items, overlapping, from the original - - >>> take(4, pairwise(count())) - [(0, 1), (1, 2), (2, 3), (3, 4)] - - On Python 3.10 and above, this is an alias for :func:`itertools.pairwise`. - - """ - a, b = tee(iterable) - next(b, None) - yield from zip(a, b) - - -try: - from itertools import pairwise as itertools_pairwise -except ImportError: - pairwise = _pairwise -else: - - def pairwise(iterable): - yield from itertools_pairwise(iterable) - - pairwise.__doc__ = _pairwise.__doc__ - - -class UnequalIterablesError(ValueError): - def __init__(self, details=None): - msg = 'Iterables have different lengths' - if details is not None: - msg += (': index 0 has length {}; index {} has length {}').format( - *details - ) - - super().__init__(msg) - - -def _zip_equal_generator(iterables): - for combo in zip_longest(*iterables, fillvalue=_marker): - for val in combo: - if val is _marker: - raise UnequalIterablesError() - yield combo - - -def _zip_equal(*iterables): - # Check whether the iterables are all the same size. - try: - first_size = len(iterables[0]) - for i, it in enumerate(iterables[1:], 1): - size = len(it) - if size != first_size: - break - else: - # If we didn't break out, we can use the built-in zip. - return zip(*iterables) - - # If we did break out, there was a mismatch. - raise UnequalIterablesError(details=(first_size, i, size)) - # If any one of the iterables didn't have a length, start reading - # them until one runs out. - except TypeError: - return _zip_equal_generator(iterables) - - -def grouper(iterable, n, incomplete='fill', fillvalue=None): - """Group elements from *iterable* into fixed-length groups of length *n*. - - >>> list(grouper('ABCDEF', 3)) - [('A', 'B', 'C'), ('D', 'E', 'F')] - - The keyword arguments *incomplete* and *fillvalue* control what happens for - iterables whose length is not a multiple of *n*. - - When *incomplete* is `'fill'`, the last group will contain instances of - *fillvalue*. - - >>> list(grouper('ABCDEFG', 3, incomplete='fill', fillvalue='x')) - [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')] - - When *incomplete* is `'ignore'`, the last group will not be emitted. - - >>> list(grouper('ABCDEFG', 3, incomplete='ignore', fillvalue='x')) - [('A', 'B', 'C'), ('D', 'E', 'F')] - - When *incomplete* is `'strict'`, a subclass of `ValueError` will be raised. - - >>> it = grouper('ABCDEFG', 3, incomplete='strict') - >>> list(it) # doctest: +IGNORE_EXCEPTION_DETAIL - Traceback (most recent call last): - ... - UnequalIterablesError - - """ - args = [iter(iterable)] * n - if incomplete == 'fill': - return zip_longest(*args, fillvalue=fillvalue) - if incomplete == 'strict': - return _zip_equal(*args) - if incomplete == 'ignore': - return zip(*args) - else: - raise ValueError('Expected fill, strict, or ignore') - - -def roundrobin(*iterables): - """Yields an item from each iterable, alternating between them. - - >>> list(roundrobin('ABC', 'D', 'EF')) - ['A', 'D', 'E', 'B', 'F', 'C'] - - This function produces the same output as :func:`interleave_longest`, but - may perform better for some inputs (in particular when the number of - iterables is small). - - """ - # Recipe credited to George Sakkis - pending = len(iterables) - nexts = cycle(iter(it).__next__ for it in iterables) - while pending: - try: - for next in nexts: - yield next() - except StopIteration: - pending -= 1 - nexts = cycle(islice(nexts, pending)) - - -def partition(pred, iterable): - """ - Returns a 2-tuple of iterables derived from the input iterable. - The first yields the items that have ``pred(item) == False``. - The second yields the items that have ``pred(item) == True``. - - >>> is_odd = lambda x: x % 2 != 0 - >>> iterable = range(10) - >>> even_items, odd_items = partition(is_odd, iterable) - >>> list(even_items), list(odd_items) - ([0, 2, 4, 6, 8], [1, 3, 5, 7, 9]) - - If *pred* is None, :func:`bool` is used. - - >>> iterable = [0, 1, False, True, '', ' '] - >>> false_items, true_items = partition(None, iterable) - >>> list(false_items), list(true_items) - ([0, False, ''], [1, True, ' ']) - - """ - if pred is None: - pred = bool - - evaluations = ((pred(x), x) for x in iterable) - t1, t2 = tee(evaluations) - return ( - (x for (cond, x) in t1 if not cond), - (x for (cond, x) in t2 if cond), - ) - - -def powerset(iterable): - """Yields all possible subsets of the iterable. - - >>> list(powerset([1, 2, 3])) - [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] - - :func:`powerset` will operate on iterables that aren't :class:`set` - instances, so repeated elements in the input will produce repeated elements - in the output. Use :func:`unique_everseen` on the input to avoid generating - duplicates: - - >>> seq = [1, 1, 0] - >>> list(powerset(seq)) - [(), (1,), (1,), (0,), (1, 1), (1, 0), (1, 0), (1, 1, 0)] - >>> from more_itertools import unique_everseen - >>> list(powerset(unique_everseen(seq))) - [(), (1,), (0,), (1, 0)] - - """ - s = list(iterable) - return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)) - - -def unique_everseen(iterable, key=None): - """ - Yield unique elements, preserving order. - - >>> list(unique_everseen('AAAABBBCCDAABBB')) - ['A', 'B', 'C', 'D'] - >>> list(unique_everseen('ABBCcAD', str.lower)) - ['A', 'B', 'C', 'D'] - - Sequences with a mix of hashable and unhashable items can be used. - The function will be slower (i.e., `O(n^2)`) for unhashable items. - - Remember that ``list`` objects are unhashable - you can use the *key* - parameter to transform the list to a tuple (which is hashable) to - avoid a slowdown. - - >>> iterable = ([1, 2], [2, 3], [1, 2]) - >>> list(unique_everseen(iterable)) # Slow - [[1, 2], [2, 3]] - >>> list(unique_everseen(iterable, key=tuple)) # Faster - [[1, 2], [2, 3]] - - Similary, you may want to convert unhashable ``set`` objects with - ``key=frozenset``. For ``dict`` objects, - ``key=lambda x: frozenset(x.items())`` can be used. - - """ - seenset = set() - seenset_add = seenset.add - seenlist = [] - seenlist_add = seenlist.append - use_key = key is not None - - for element in iterable: - k = key(element) if use_key else element - try: - if k not in seenset: - seenset_add(k) - yield element - except TypeError: - if k not in seenlist: - seenlist_add(k) - yield element - - -def unique_justseen(iterable, key=None): - """Yields elements in order, ignoring serial duplicates - - >>> list(unique_justseen('AAAABBBCCDAABBB')) - ['A', 'B', 'C', 'D', 'A', 'B'] - >>> list(unique_justseen('ABBCcAD', str.lower)) - ['A', 'B', 'C', 'A', 'D'] - - """ - return map(next, map(operator.itemgetter(1), groupby(iterable, key))) - - -def iter_except(func, exception, first=None): - """Yields results from a function repeatedly until an exception is raised. - - Converts a call-until-exception interface to an iterator interface. - Like ``iter(func, sentinel)``, but uses an exception instead of a sentinel - to end the loop. - - >>> l = [0, 1, 2] - >>> list(iter_except(l.pop, IndexError)) - [2, 1, 0] - - Multiple exceptions can be specified as a stopping condition: - - >>> l = [1, 2, 3, '...', 4, 5, 6] - >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError))) - [7, 6, 5] - >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError))) - [4, 3, 2] - >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError))) - [] - - """ - try: - if first is not None: - yield first() - while 1: - yield func() - except exception: - pass - - -def first_true(iterable, default=None, pred=None): - """ - Returns the first true value in the iterable. - - If no true value is found, returns *default* - - If *pred* is not None, returns the first item for which - ``pred(item) == True`` . - - >>> first_true(range(10)) - 1 - >>> first_true(range(10), pred=lambda x: x > 5) - 6 - >>> first_true(range(10), default='missing', pred=lambda x: x > 9) - 'missing' - - """ - return next(filter(pred, iterable), default) - - -def random_product(*args, repeat=1): - """Draw an item at random from each of the input iterables. - - >>> random_product('abc', range(4), 'XYZ') # doctest:+SKIP - ('c', 3, 'Z') - - If *repeat* is provided as a keyword argument, that many items will be - drawn from each iterable. - - >>> random_product('abcd', range(4), repeat=2) # doctest:+SKIP - ('a', 2, 'd', 3) - - This equivalent to taking a random selection from - ``itertools.product(*args, **kwarg)``. - - """ - pools = [tuple(pool) for pool in args] * repeat - return tuple(choice(pool) for pool in pools) - - -def random_permutation(iterable, r=None): - """Return a random *r* length permutation of the elements in *iterable*. - - If *r* is not specified or is ``None``, then *r* defaults to the length of - *iterable*. - - >>> random_permutation(range(5)) # doctest:+SKIP - (3, 4, 0, 1, 2) - - This equivalent to taking a random selection from - ``itertools.permutations(iterable, r)``. - - """ - pool = tuple(iterable) - r = len(pool) if r is None else r - return tuple(sample(pool, r)) - - -def random_combination(iterable, r): - """Return a random *r* length subsequence of the elements in *iterable*. - - >>> random_combination(range(5), 3) # doctest:+SKIP - (2, 3, 4) - - This equivalent to taking a random selection from - ``itertools.combinations(iterable, r)``. - - """ - pool = tuple(iterable) - n = len(pool) - indices = sorted(sample(range(n), r)) - return tuple(pool[i] for i in indices) - - -def random_combination_with_replacement(iterable, r): - """Return a random *r* length subsequence of elements in *iterable*, - allowing individual elements to be repeated. - - >>> random_combination_with_replacement(range(3), 5) # doctest:+SKIP - (0, 0, 1, 2, 2) - - This equivalent to taking a random selection from - ``itertools.combinations_with_replacement(iterable, r)``. - - """ - pool = tuple(iterable) - n = len(pool) - indices = sorted(randrange(n) for i in range(r)) - return tuple(pool[i] for i in indices) - - -def nth_combination(iterable, r, index): - """Equivalent to ``list(combinations(iterable, r))[index]``. - - The subsequences of *iterable* that are of length *r* can be ordered - lexicographically. :func:`nth_combination` computes the subsequence at - sort position *index* directly, without computing the previous - subsequences. - - >>> nth_combination(range(5), 3, 5) - (0, 3, 4) - - ``ValueError`` will be raised If *r* is negative or greater than the length - of *iterable*. - ``IndexError`` will be raised if the given *index* is invalid. - """ - pool = tuple(iterable) - n = len(pool) - if (r < 0) or (r > n): - raise ValueError - - c = 1 - k = min(r, n - r) - for i in range(1, k + 1): - c = c * (n - k + i) // i - - if index < 0: - index += c - - if (index < 0) or (index >= c): - raise IndexError - - result = [] - while r: - c, n, r = c * r // n, n - 1, r - 1 - while index >= c: - index -= c - c, n = c * (n - r) // n, n - 1 - result.append(pool[-1 - n]) - - return tuple(result) - - -def prepend(value, iterator): - """Yield *value*, followed by the elements in *iterator*. - - >>> value = '0' - >>> iterator = ['1', '2', '3'] - >>> list(prepend(value, iterator)) - ['0', '1', '2', '3'] - - To prepend multiple values, see :func:`itertools.chain` - or :func:`value_chain`. - - """ - return chain([value], iterator) - - -def convolve(signal, kernel): - """Convolve the iterable *signal* with the iterable *kernel*. - - >>> signal = (1, 2, 3, 4, 5) - >>> kernel = [3, 2, 1] - >>> list(convolve(signal, kernel)) - [3, 8, 14, 20, 26, 14, 5] - - Note: the input arguments are not interchangeable, as the *kernel* - is immediately consumed and stored. - - """ - kernel = tuple(kernel)[::-1] - n = len(kernel) - window = deque([0], maxlen=n) * n - for x in chain(signal, repeat(0, n - 1)): - window.append(x) - yield sum(map(operator.mul, kernel, window)) - - -def before_and_after(predicate, it): - """A variant of :func:`takewhile` that allows complete access to the - remainder of the iterator. - - >>> it = iter('ABCdEfGhI') - >>> all_upper, remainder = before_and_after(str.isupper, it) - >>> ''.join(all_upper) - 'ABC' - >>> ''.join(remainder) # takewhile() would lose the 'd' - 'dEfGhI' - - Note that the first iterator must be fully consumed before the second - iterator can generate valid results. - """ - it = iter(it) - transition = [] - - def true_iterator(): - for elem in it: - if predicate(elem): - yield elem - else: - transition.append(elem) - return - - # Note: this is different from itertools recipes to allow nesting - # before_and_after remainders into before_and_after again. See tests - # for an example. - remainder_iterator = chain(transition, it) - - return true_iterator(), remainder_iterator - - -def triplewise(iterable): - """Return overlapping triplets from *iterable*. - - >>> list(triplewise('ABCDE')) - [('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E')] - - """ - for (a, _), (b, c) in pairwise(pairwise(iterable)): - yield a, b, c - - -def sliding_window(iterable, n): - """Return a sliding window of width *n* over *iterable*. - - >>> list(sliding_window(range(6), 4)) - [(0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5)] - - If *iterable* has fewer than *n* items, then nothing is yielded: - - >>> list(sliding_window(range(3), 4)) - [] - - For a variant with more features, see :func:`windowed`. - """ - it = iter(iterable) - window = deque(islice(it, n), maxlen=n) - if len(window) == n: - yield tuple(window) - for x in it: - window.append(x) - yield tuple(window) - - -def subslices(iterable): - """Return all contiguous non-empty subslices of *iterable*. - - >>> list(subslices('ABC')) - [['A'], ['A', 'B'], ['A', 'B', 'C'], ['B'], ['B', 'C'], ['C']] - - This is similar to :func:`substrings`, but emits items in a different - order. - """ - seq = list(iterable) - slices = starmap(slice, combinations(range(len(seq) + 1), 2)) - return map(operator.getitem, repeat(seq), slices) - - -def polynomial_from_roots(roots): - """Compute a polynomial's coefficients from its roots. - - >>> roots = [5, -4, 3] # (x - 5) * (x + 4) * (x - 3) - >>> polynomial_from_roots(roots) # x^3 - 4 * x^2 - 17 * x + 60 - [1, -4, -17, 60] - """ - # Use math.prod for Python 3.8+, - prod = getattr(math, 'prod', lambda x: reduce(operator.mul, x, 1)) - roots = list(map(operator.neg, roots)) - return [ - sum(map(prod, combinations(roots, k))) for k in range(len(roots) + 1) - ] - - -def iter_index(iterable, value, start=0): - """Yield the index of each place in *iterable* that *value* occurs, - beginning with index *start*. - - See :func:`locate` for a more general means of finding the indexes - associated with particular values. - - >>> list(iter_index('AABCADEAF', 'A')) - [0, 1, 4, 7] - """ - try: - seq_index = iterable.index - except AttributeError: - # Slow path for general iterables - it = islice(iterable, start, None) - for i, element in enumerate(it, start): - if element is value or element == value: - yield i - else: - # Fast path for sequences - i = start - 1 - try: - while True: - i = seq_index(value, i + 1) - yield i - except ValueError: - pass - - -def sieve(n): - """Yield the primes less than n. - - >>> list(sieve(30)) - [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] - """ - isqrt = getattr(math, 'isqrt', lambda x: int(math.sqrt(x))) - data = bytearray((0, 1)) * (n // 2) - data[:3] = 0, 0, 0 - limit = isqrt(n) + 1 - for p in compress(range(limit), data): - data[p * p : n : p + p] = bytes(len(range(p * p, n, p + p))) - data[2] = 1 - return iter_index(data, 1) if n > 2 else iter([]) - - -def batched(iterable, n): - """Batch data into lists of length *n*. The last batch may be shorter. - - >>> list(batched('ABCDEFG', 3)) - [['A', 'B', 'C'], ['D', 'E', 'F'], ['G']] - - This recipe is from the ``itertools`` docs. This library also provides - :func:`chunked`, which has a different implementation. - """ - if hexversion >= 0x30C00A0: # Python 3.12.0a0 - warnings.warn( - ( - 'batched will be removed in a future version of ' - 'more-itertools. Use the standard library ' - 'itertools.batched function instead' - ), - DeprecationWarning, - ) - - it = iter(iterable) - while True: - batch = list(islice(it, n)) - if not batch: - break - yield batch - - -def transpose(it): - """Swap the rows and columns of the input. - - >>> list(transpose([(1, 2, 3), (11, 22, 33)])) - [(1, 11), (2, 22), (3, 33)] - - The caller should ensure that the dimensions of the input are compatible. - """ - # TODO: when 3.9 goes end-of-life, add stric=True to this. - return zip(*it) - - -def matmul(m1, m2): - """Multiply two matrices. - >>> list(matmul([(7, 5), (3, 5)], [(2, 5), (7, 9)])) - [[49, 80], [41, 60]] - - The caller should ensure that the dimensions of the input matrices are - compatible with each other. - """ - n = len(m2[0]) - return batched(starmap(dotproduct, product(m1, transpose(m2))), n) - - -def factor(n): - """Yield the prime factors of n. - >>> list(factor(360)) - [2, 2, 2, 3, 3, 5] - """ - isqrt = getattr(math, 'isqrt', lambda x: int(math.sqrt(x))) - for prime in sieve(isqrt(n) + 1): - while True: - quotient, remainder = divmod(n, prime) - if remainder: - break - yield prime - n = quotient - if n == 1: - return - if n >= 2: - yield n diff --git a/pkg_resources/_vendor/more_itertools/recipes.pyi b/pkg_resources/_vendor/more_itertools/recipes.pyi deleted file mode 100644 index 0267ed569e..0000000000 --- a/pkg_resources/_vendor/more_itertools/recipes.pyi +++ /dev/null @@ -1,119 +0,0 @@ -"""Stubs for more_itertools.recipes""" -from __future__ import annotations - -from typing import ( - Any, - Callable, - Iterable, - Iterator, - overload, - Sequence, - Type, - TypeVar, -) - -# Type and type variable definitions -_T = TypeVar('_T') -_U = TypeVar('_U') - -def take(n: int, iterable: Iterable[_T]) -> list[_T]: ... -def tabulate( - function: Callable[[int], _T], start: int = ... -) -> Iterator[_T]: ... -def tail(n: int, iterable: Iterable[_T]) -> Iterator[_T]: ... -def consume(iterator: Iterable[object], n: int | None = ...) -> None: ... -@overload -def nth(iterable: Iterable[_T], n: int) -> _T | None: ... -@overload -def nth(iterable: Iterable[_T], n: int, default: _U) -> _T | _U: ... -def all_equal(iterable: Iterable[object]) -> bool: ... -def quantify( - iterable: Iterable[_T], pred: Callable[[_T], bool] = ... -) -> int: ... -def pad_none(iterable: Iterable[_T]) -> Iterator[_T | None]: ... -def padnone(iterable: Iterable[_T]) -> Iterator[_T | None]: ... -def ncycles(iterable: Iterable[_T], n: int) -> Iterator[_T]: ... -def dotproduct(vec1: Iterable[object], vec2: Iterable[object]) -> object: ... -def flatten(listOfLists: Iterable[Iterable[_T]]) -> Iterator[_T]: ... -def repeatfunc( - func: Callable[..., _U], times: int | None = ..., *args: Any -) -> Iterator[_U]: ... -def pairwise(iterable: Iterable[_T]) -> Iterator[tuple[_T, _T]]: ... -def grouper( - iterable: Iterable[_T], - n: int, - incomplete: str = ..., - fillvalue: _U = ..., -) -> Iterator[tuple[_T | _U, ...]]: ... -def roundrobin(*iterables: Iterable[_T]) -> Iterator[_T]: ... -def partition( - pred: Callable[[_T], object] | None, iterable: Iterable[_T] -) -> tuple[Iterator[_T], Iterator[_T]]: ... -def powerset(iterable: Iterable[_T]) -> Iterator[tuple[_T, ...]]: ... -def unique_everseen( - iterable: Iterable[_T], key: Callable[[_T], _U] | None = ... -) -> Iterator[_T]: ... -def unique_justseen( - iterable: Iterable[_T], key: Callable[[_T], object] | None = ... -) -> Iterator[_T]: ... -@overload -def iter_except( - func: Callable[[], _T], - exception: Type[BaseException] | tuple[Type[BaseException], ...], - first: None = ..., -) -> Iterator[_T]: ... -@overload -def iter_except( - func: Callable[[], _T], - exception: Type[BaseException] | tuple[Type[BaseException], ...], - first: Callable[[], _U], -) -> Iterator[_T | _U]: ... -@overload -def first_true( - iterable: Iterable[_T], *, pred: Callable[[_T], object] | None = ... -) -> _T | None: ... -@overload -def first_true( - iterable: Iterable[_T], - default: _U, - pred: Callable[[_T], object] | None = ..., -) -> _T | _U: ... -def random_product( - *args: Iterable[_T], repeat: int = ... -) -> tuple[_T, ...]: ... -def random_permutation( - iterable: Iterable[_T], r: int | None = ... -) -> tuple[_T, ...]: ... -def random_combination(iterable: Iterable[_T], r: int) -> tuple[_T, ...]: ... -def random_combination_with_replacement( - iterable: Iterable[_T], r: int -) -> tuple[_T, ...]: ... -def nth_combination( - iterable: Iterable[_T], r: int, index: int -) -> tuple[_T, ...]: ... -def prepend(value: _T, iterator: Iterable[_U]) -> Iterator[_T | _U]: ... -def convolve(signal: Iterable[_T], kernel: Iterable[_T]) -> Iterator[_T]: ... -def before_and_after( - predicate: Callable[[_T], bool], it: Iterable[_T] -) -> tuple[Iterator[_T], Iterator[_T]]: ... -def triplewise(iterable: Iterable[_T]) -> Iterator[tuple[_T, _T, _T]]: ... -def sliding_window( - iterable: Iterable[_T], n: int -) -> Iterator[tuple[_T, ...]]: ... -def subslices(iterable: Iterable[_T]) -> Iterator[list[_T]]: ... -def polynomial_from_roots(roots: Sequence[int]) -> list[int]: ... -def iter_index( - iterable: Iterable[object], - value: Any, - start: int | None = ..., -) -> Iterator[int]: ... -def sieve(n: int) -> Iterator[int]: ... -def batched( - iterable: Iterable[_T], - n: int, -) -> Iterator[list[_T]]: ... -def transpose( - it: Iterable[Iterable[_T]], -) -> tuple[Iterator[_T], ...]: ... -def matmul(m1: Sequence[_T], m2: Sequence[_T]) -> Iterator[list[_T]]: ... -def factor(n: int) -> Iterator[int]: ... diff --git a/pkg_resources/_vendor/packaging-23.1.dist-info/INSTALLER b/pkg_resources/_vendor/packaging-23.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a..0000000000 --- a/pkg_resources/_vendor/packaging-23.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/pkg_resources/_vendor/packaging-23.1.dist-info/RECORD b/pkg_resources/_vendor/packaging-23.1.dist-info/RECORD deleted file mode 100644 index e240a8408d..0000000000 --- a/pkg_resources/_vendor/packaging-23.1.dist-info/RECORD +++ /dev/null @@ -1,37 +0,0 @@ -packaging-23.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -packaging-23.1.dist-info/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 -packaging-23.1.dist-info/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 -packaging-23.1.dist-info/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 -packaging-23.1.dist-info/METADATA,sha256=JnduJDlxs2IVeB-nIqAC3-HyNcPhP_MADd9_k_MjmaI,3082 -packaging-23.1.dist-info/RECORD,, -packaging-23.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -packaging-23.1.dist-info/WHEEL,sha256=rSgq_JpHF9fHR1lx53qwg_1-2LypZE_qmcuXbVUq948,81 -packaging/__init__.py,sha256=kYVZSmXT6CWInT4UJPDtrSQBAZu8fMuFBxpv5GsDTLk,501 -packaging/__pycache__/__init__.cpython-311.pyc,, -packaging/__pycache__/_elffile.cpython-311.pyc,, -packaging/__pycache__/_manylinux.cpython-311.pyc,, -packaging/__pycache__/_musllinux.cpython-311.pyc,, -packaging/__pycache__/_parser.cpython-311.pyc,, -packaging/__pycache__/_structures.cpython-311.pyc,, -packaging/__pycache__/_tokenizer.cpython-311.pyc,, -packaging/__pycache__/markers.cpython-311.pyc,, -packaging/__pycache__/metadata.cpython-311.pyc,, -packaging/__pycache__/requirements.cpython-311.pyc,, -packaging/__pycache__/specifiers.cpython-311.pyc,, -packaging/__pycache__/tags.cpython-311.pyc,, -packaging/__pycache__/utils.cpython-311.pyc,, -packaging/__pycache__/version.cpython-311.pyc,, -packaging/_elffile.py,sha256=hbmK8OD6Z7fY6hwinHEUcD1by7czkGiNYu7ShnFEk2k,3266 -packaging/_manylinux.py,sha256=ESGrDEVmBc8jYTtdZRAWiLk72lOzAKWeezFgoJ_MuBc,8926 -packaging/_musllinux.py,sha256=mvPk7FNjjILKRLIdMxR7IvJ1uggLgCszo-L9rjfpi0M,2524 -packaging/_parser.py,sha256=KJQkBh_Xbfb-qsB560YIEItrTpCZaOh4_YMfBtd5XIY,10194 -packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431 -packaging/_tokenizer.py,sha256=alCtbwXhOFAmFGZ6BQ-wCTSFoRAJ2z-ysIf7__MTJ_k,5292 -packaging/markers.py,sha256=eH-txS2zq1HdNpTd9LcZUcVIwewAiNU0grmq5wjKnOk,8208 -packaging/metadata.py,sha256=PjELMLxKG_iu3HWjKAOdKhuNrHfWgpdTF2Q4nObsZeM,16397 -packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -packaging/requirements.py,sha256=hJzvtJyAvENc_VfwfhnOZV1851-VW8JCGh-R96NE4Pc,3287 -packaging/specifiers.py,sha256=ZOpqL_w_Kj6ZF_OWdliQUzhEyHlDbi6989kr-sF5GHs,39206 -packaging/tags.py,sha256=_1gLX8h1SgpjAdYCP9XqU37zRjXtU5ZliGy3IM-WcSM,18106 -packaging/utils.py,sha256=es0cCezKspzriQ-3V88h3yJzxz028euV2sUwM61kE-o,4355 -packaging/version.py,sha256=2NH3E57hzRhn0BV9boUBvgPsxlTqLJeI0EpYQoNvGi0,16326 diff --git a/pkg_resources/_vendor/packaging/__init__.py b/pkg_resources/_vendor/packaging/__init__.py deleted file mode 100644 index 13cadc7f04..0000000000 --- a/pkg_resources/_vendor/packaging/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# 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__ = "23.1" - -__author__ = "Donald Stufft and individual contributors" -__email__ = "donald@stufft.io" - -__license__ = "BSD-2-Clause or Apache-2.0" -__copyright__ = "2014-2019 %s" % __author__ diff --git a/pkg_resources/_vendor/packaging/_elffile.py b/pkg_resources/_vendor/packaging/_elffile.py deleted file mode 100644 index 6fb19b30bb..0000000000 --- a/pkg_resources/_vendor/packaging/_elffile.py +++ /dev/null @@ -1,108 +0,0 @@ -""" -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. - -Based on: https://gist.github.com/lyssdod/f51579ae8d93c8657a5564aefc2ffbca -ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html -""" - -import enum -import os -import struct -from typing import IO, Optional, Tuple - - -class ELFInvalid(ValueError): - pass - - -class EIClass(enum.IntEnum): - C32 = 1 - C64 = 2 - - -class EIData(enum.IntEnum): - Lsb = 1 - Msb = 2 - - -class EMachine(enum.IntEnum): - I386 = 3 - S390 = 22 - Arm = 40 - X8664 = 62 - AArc64 = 183 - - -class ELFFile: - """ - Representation of an ELF executable. - """ - - def __init__(self, f: IO[bytes]) -> None: - self._f = f - - try: - ident = self._read("16B") - except struct.error: - raise ELFInvalid("unable to parse identification") - magic = bytes(ident[:4]) - if magic != b"\x7fELF": - raise ELFInvalid(f"invalid magic: {magic!r}") - - self.capacity = ident[4] # Format for program header (bitness). - self.encoding = ident[5] # Data structure encoding (endianness). - - try: - # e_fmt: Format for program header. - # p_fmt: Format for section header. - # p_idx: Indexes to find p_type, p_offset, and p_filesz. - e_fmt, self._p_fmt, self._p_idx = { - (1, 1): ("HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)), # 32-bit MSB. - (2, 1): ("HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)), # 64-bit MSB. - }[(self.capacity, self.encoding)] - except KeyError: - raise ELFInvalid( - f"unrecognized capacity ({self.capacity}) or " - f"encoding ({self.encoding})" - ) - - try: - ( - _, - self.machine, # Architecture type. - _, - _, - self._e_phoff, # Offset of program header. - _, - self.flags, # Processor-specific flags. - _, - self._e_phentsize, # Size of section. - self._e_phnum, # Number of sections. - ) = self._read(e_fmt) - except struct.error as e: - raise ELFInvalid("unable to parse machine and section information") from e - - def _read(self, fmt: str) -> Tuple[int, ...]: - return struct.unpack(fmt, self._f.read(struct.calcsize(fmt))) - - @property - def interpreter(self) -> Optional[str]: - """ - 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 diff --git a/pkg_resources/_vendor/packaging/_manylinux.py b/pkg_resources/_vendor/packaging/_manylinux.py deleted file mode 100644 index 449c655be6..0000000000 --- a/pkg_resources/_vendor/packaging/_manylinux.py +++ /dev/null @@ -1,240 +0,0 @@ -import collections -import contextlib -import functools -import os -import re -import sys -import warnings -from typing import Dict, Generator, Iterator, NamedTuple, Optional, Tuple - -from ._elffile import EIClass, EIData, ELFFile, EMachine - -EF_ARM_ABIMASK = 0xFF000000 -EF_ARM_ABI_VER5 = 0x05000000 -EF_ARM_ABI_FLOAT_HARD = 0x00000400 - - -# `os.PathLike` not a generic type until Python 3.9, so sticking with `str` -# as the type for `path` until then. -@contextlib.contextmanager -def _parse_elf(path: str) -> Generator[Optional[ELFFile], 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, arch: str) -> bool: - if arch == "armv7l": - return _is_linux_armhf(executable) - if arch == "i686": - return _is_linux_i686(executable) - return arch in {"x86_64", "aarch64", "ppc64", "ppc64le", "s390x"} - - -# 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() -> Optional[str]: - """ - 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 = getattr(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() -> Optional[str]: - """ - Fallback implementation of glibc_version_string using ctypes. - """ - try: - import ctypes - except ImportError: - return None - - # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen - # manpage says, "If filename is NULL, then the returned handle is for the - # main program". This way we can let the linker do the work to figure out - # which libc our process is actually using. - # - # We must also handle the special case where the executable is not a - # dynamically linked executable. This can occur when using musl libc, - # for example. In this situation, dlopen() will error, leading to an - # OSError. Interestingly, at least in the case of musl, there is no - # errno set on the OSError. The single string argument used to construct - # OSError comes from libc itself and is therefore not portable to - # hard code here. In any case, failure to call dlopen() means we - # can proceed, so we bail on our attempt. - try: - process_namespace = ctypes.CDLL(None) - except OSError: - return None - - try: - gnu_get_libc_version = process_namespace.gnu_get_libc_version - except AttributeError: - # Symbol doesn't exist -> therefore, we are not linked to - # glibc. - return None - - # Call gnu_get_libc_version, which returns a string like "2.5" - gnu_get_libc_version.restype = ctypes.c_char_p - version_str: str = gnu_get_libc_version() - # py2 / py3 compatibility: - if not isinstance(version_str, str): - version_str = version_str.decode("ascii") - - return version_str - - -def _glibc_version_string() -> Optional[str]: - """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) -> Tuple[int, int]: - """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," - f" got: {version_str}", - RuntimeWarning, - ) - return -1, -1 - return int(m.group("major")), int(m.group("minor")) - - -@functools.lru_cache() -def _get_glibc_version() -> Tuple[int, int]: - version_str = _glibc_version_string() - if version_str is None: - return (-1, -1) - return _parse_glibc_version(version_str) - - -# From PEP 513, PEP 600 -def _is_compatible(name: str, arch: str, version: _GLibCVersion) -> bool: - sys_glibc = _get_glibc_version() - if sys_glibc < version: - return False - # Check for presence of _manylinux module. - try: - import _manylinux # noqa - except ImportError: - return True - if hasattr(_manylinux, "manylinux_compatible"): - result = _manylinux.manylinux_compatible(version[0], version[1], arch) - if result is not None: - return bool(result) - return True - if version == _GLibCVersion(2, 5): - if hasattr(_manylinux, "manylinux1_compatible"): - return bool(_manylinux.manylinux1_compatible) - if version == _GLibCVersion(2, 12): - if hasattr(_manylinux, "manylinux2010_compatible"): - return bool(_manylinux.manylinux2010_compatible) - if version == _GLibCVersion(2, 17): - if hasattr(_manylinux, "manylinux2014_compatible"): - return bool(_manylinux.manylinux2014_compatible) - return True - - -_LEGACY_MANYLINUX_MAP = { - # CentOS 7 w/ glibc 2.17 (PEP 599) - (2, 17): "manylinux2014", - # CentOS 6 w/ glibc 2.12 (PEP 571) - (2, 12): "manylinux2010", - # CentOS 5 w/ glibc 2.5 (PEP 513) - (2, 5): "manylinux1", -} - - -def platform_tags(linux: str, arch: str) -> Iterator[str]: - if not _have_compatible_abi(sys.executable, arch): - return - # Oldest glibc to be supported regardless of architecture is (2, 17). - too_old_glibc2 = _GLibCVersion(2, 16) - if arch in {"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 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) - tag = "manylinux_{}_{}".format(*glibc_version) - if _is_compatible(tag, arch, glibc_version): - yield linux.replace("linux", tag) - # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags. - if glibc_version in _LEGACY_MANYLINUX_MAP: - legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version] - if _is_compatible(legacy_tag, arch, glibc_version): - yield linux.replace("linux", legacy_tag) diff --git a/pkg_resources/_vendor/packaging/_musllinux.py b/pkg_resources/_vendor/packaging/_musllinux.py deleted file mode 100644 index 706ba600a9..0000000000 --- a/pkg_resources/_vendor/packaging/_musllinux.py +++ /dev/null @@ -1,80 +0,0 @@ -"""PEP 656 support. - -This module implements logic to detect if the currently running Python is -linked against musl, and what musl version is used. -""" - -import functools -import re -import subprocess -import sys -from typing import Iterator, NamedTuple, Optional - -from ._elffile import ELFFile - - -class _MuslVersion(NamedTuple): - major: int - minor: int - - -def _parse_musl_version(output: str) -> Optional[_MuslVersion]: - 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) -> Optional[_MuslVersion]: - """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], stderr=subprocess.PIPE, universal_newlines=True) - return _parse_musl_version(proc.stderr) - - -def platform_tags(arch: str) -> Iterator[str]: - """Generate musllinux tags compatible to the current platform. - - :param arch: Should 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 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 ") diff --git a/pkg_resources/_vendor/packaging/_parser.py b/pkg_resources/_vendor/packaging/_parser.py deleted file mode 100644 index 5a18b758fe..0000000000 --- a/pkg_resources/_vendor/packaging/_parser.py +++ /dev/null @@ -1,353 +0,0 @@ -"""Handwritten parser of dependency specifiers. - -The docstring for each __parse_* function contains ENBF-inspired grammar representing -the implementation. -""" - -import ast -from typing import Any, List, NamedTuple, Optional, Tuple, Union - -from ._tokenizer import DEFAULT_RULES, Tokenizer - - -class Node: - 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}')>" - - def serialize(self) -> str: - raise NotImplementedError - - -class Variable(Node): - def serialize(self) -> str: - return str(self) - - -class Value(Node): - def serialize(self) -> str: - return f'"{self}"' - - -class Op(Node): - def serialize(self) -> str: - return str(self) - - -MarkerVar = Union[Variable, Value] -MarkerItem = Tuple[MarkerVar, Op, MarkerVar] -# MarkerAtom = Union[MarkerItem, List["MarkerAtom"]] -# MarkerList = List[Union["MarkerList", MarkerAtom, str]] -# mypy does not support recursive type definition -# https://github.com/python/mypy/issues/731 -MarkerAtom = Any -MarkerList = List[Any] - - -class ParsedRequirement(NamedTuple): - name: str - url: str - extras: List[str] - specifier: str - marker: Optional[MarkerList] - - -# -------------------------------------------------------------------------------------- -# 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, Optional[MarkerList]]: - """ - 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, 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, - after=( - "version specifier" - if specifier - else "name and no valid version specifier" - ), - ) - - return (url, specifier, marker) - - -def _parse_requirement_marker( - tokenizer: Tokenizer, *, span_start: int, after: str -) -> MarkerList: - """ - requirement_marker = SEMICOLON marker WS? - """ - - if not tokenizer.check("SEMICOLON"): - tokenizer.raise_syntax_error( - f"Expected end or semicolon (after {after})", - span_start=span_start, - ) - tokenizer.read() - - marker = _parse_marker(tokenizer) - tokenizer.consume("WS") - - return marker - - -def _parse_extras(tokenizer: Tokenizer) -> List[str]: - """ - extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)? - """ - if not tokenizer.check("LEFT_BRACKET", peek=True): - return [] - - with tokenizer.enclosing_tokens( - "LEFT_BRACKET", - "RIGHT_BRACKET", - around="extras", - ): - tokenizer.consume("WS") - extras = _parse_extras_list(tokenizer) - tokenizer.consume("WS") - - return extras - - -def _parse_extras_list(tokenizer: Tokenizer) -> List[str]: - """ - extras_list = identifier (wsp* ',' wsp* identifier)* - """ - extras: List[str] = [] - - if not tokenizer.check("IDENTIFIER"): - return extras - - extras.append(tokenizer.read().text) - - while True: - tokenizer.consume("WS") - if tokenizer.check("IDENTIFIER", peek=True): - tokenizer.raise_syntax_error("Expected comma between extra names") - elif not tokenizer.check("COMMA"): - break - - tokenizer.read() - tokenizer.consume("WS") - - extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma") - extras.append(extra_token.text) - - return extras - - -def _parse_specifier(tokenizer: Tokenizer) -> str: - """ - specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS - | WS? version_many WS? - """ - with tokenizer.enclosing_tokens( - "LEFT_PARENTHESIS", - "RIGHT_PARENTHESIS", - around="version specifier", - ): - tokenizer.consume("WS") - parsed_specifiers = _parse_version_many(tokenizer) - tokenizer.consume("WS") - - return parsed_specifiers - - -def _parse_version_many(tokenizer: Tokenizer) -> str: - """ - version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)? - """ - parsed_specifiers = "" - while tokenizer.check("SPECIFIER"): - span_start = tokenizer.position - parsed_specifiers += tokenizer.read().text - if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True): - tokenizer.raise_syntax_error( - ".* suffix can only be used with `==` or `!=` operators", - span_start=span_start, - span_end=tokenizer.position + 1, - ) - if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True): - tokenizer.raise_syntax_error( - "Local version label can only be used with `==` or `!=` operators", - span_start=span_start, - span_end=tokenizer.position, - ) - tokenizer.consume("WS") - if not tokenizer.check("COMMA"): - break - parsed_specifiers += tokenizer.read().text - tokenizer.consume("WS") - - return parsed_specifiers - - -# -------------------------------------------------------------------------------------- -# Recursive descent parser for marker expression -# -------------------------------------------------------------------------------------- -def parse_marker(source: str) -> MarkerList: - return _parse_marker(Tokenizer(source, rules=DEFAULT_RULES)) - - -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: - """ - marker_var = VARIABLE | QUOTED_STRING - """ - if tokenizer.check("VARIABLE"): - return process_env_var(tokenizer.read().text.replace(".", "_")) - elif tokenizer.check("QUOTED_STRING"): - return process_python_str(tokenizer.read().text) - else: - tokenizer.raise_syntax_error( - message="Expected a marker variable or quoted string" - ) - - -def process_env_var(env_var: str) -> Variable: - if ( - env_var == "platform_python_implementation" - or env_var == "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" - ) diff --git a/pkg_resources/_vendor/packaging/_structures.py b/pkg_resources/_vendor/packaging/_structures.py deleted file mode 100644 index 90a6465f96..0000000000 --- a/pkg_resources/_vendor/packaging/_structures.py +++ /dev/null @@ -1,61 +0,0 @@ -# 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. - - -class InfinityType: - def __repr__(self) -> str: - return "Infinity" - - def __hash__(self) -> int: - return hash(repr(self)) - - def __lt__(self, other: object) -> bool: - return False - - def __le__(self, other: object) -> bool: - return False - - def __eq__(self, other: object) -> bool: - return isinstance(other, self.__class__) - - def __gt__(self, other: object) -> bool: - return True - - def __ge__(self, other: object) -> bool: - return True - - def __neg__(self: object) -> "NegativeInfinityType": - return NegativeInfinity - - -Infinity = InfinityType() - - -class NegativeInfinityType: - def __repr__(self) -> str: - return "-Infinity" - - def __hash__(self) -> int: - return hash(repr(self)) - - def __lt__(self, other: object) -> bool: - return True - - def __le__(self, other: object) -> bool: - return True - - def __eq__(self, other: object) -> bool: - return isinstance(other, self.__class__) - - def __gt__(self, other: object) -> bool: - return False - - def __ge__(self, other: object) -> bool: - return False - - def __neg__(self: object) -> InfinityType: - return Infinity - - -NegativeInfinity = NegativeInfinityType() diff --git a/pkg_resources/_vendor/packaging/_tokenizer.py b/pkg_resources/_vendor/packaging/_tokenizer.py deleted file mode 100644 index dd0d648d49..0000000000 --- a/pkg_resources/_vendor/packaging/_tokenizer.py +++ /dev/null @@ -1,192 +0,0 @@ -import contextlib -import re -from dataclasses import dataclass -from typing import Dict, Iterator, NoReturn, Optional, Tuple, Union - -from .specifiers import Specifier - - -@dataclass -class Token: - name: str - text: str - position: int - - -class ParserSyntaxError(Exception): - """The provided source text could not be parsed correctly.""" - - def __init__( - self, - message: str, - *, - source: str, - span: Tuple[int, int], - ) -> None: - self.span = span - self.message = message - self.source = source - - super().__init__() - - def __str__(self) -> str: - marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^" - return "\n ".join([self.message, self.source, marker]) - - -DEFAULT_RULES: "Dict[str, Union[str, re.Pattern[str]]]" = { - "LEFT_PARENTHESIS": r"\(", - "RIGHT_PARENTHESIS": r"\)", - "LEFT_BRACKET": r"\[", - "RIGHT_BRACKET": r"\]", - "SEMICOLON": r";", - "COMMA": r",", - "QUOTED_STRING": re.compile( - r""" - ( - ('[^']*') - | - ("[^"]*") - ) - """, - re.VERBOSE, - ), - "OP": r"(===|==|~=|!=|<=|>=|<|>)", - "BOOLOP": r"\b(or|and)\b", - "IN": r"\bin\b", - "NOT": 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) - |extra - )\b - """, - re.VERBOSE, - ), - "SPECIFIER": re.compile( - Specifier._operator_regex_str + Specifier._version_regex_str, - re.VERBOSE | re.IGNORECASE, - ), - "AT": r"\@", - "URL": r"[^ \t]+", - "IDENTIFIER": r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b", - "VERSION_PREFIX_TRAIL": r"\.\*", - "VERSION_LOCAL_LABEL_TRAIL": r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*", - "WS": r"[ \t]+", - "END": r"$", -} - - -class Tokenizer: - """Context-sensitive token parsing. - - Provides methods to examine the input stream to check whether the next token - matches. - """ - - def __init__( - self, - source: str, - *, - rules: "Dict[str, Union[str, re.Pattern[str]]]", - ) -> None: - self.source = source - self.rules: Dict[str, re.Pattern[str]] = { - name: re.compile(pattern) for name, pattern in rules.items() - } - self.next_token: Optional[Token] = None - self.position = 0 - - def consume(self, name: str) -> None: - """Move beyond provided token name, if at current position.""" - if self.check(name): - self.read() - - def check(self, name: str, *, peek: bool = False) -> bool: - """Check whether the next token has the provided name. - - By default, if the check succeeds, the token *must* be read before - another check. If `peek` is set to `True`, the token is not loaded and - would need to be checked again. - """ - assert ( - self.next_token is None - ), f"Cannot check for {name!r}, already have {self.next_token!r}" - assert name in self.rules, f"Unknown token name: {name!r}" - - expression = self.rules[name] - - match = expression.match(self.source, self.position) - if match is None: - return False - if not peek: - self.next_token = Token(name, match[0], self.position) - return True - - def expect(self, name: str, *, expected: str) -> Token: - """Expect a certain token name next, failing with a syntax error otherwise. - - The token is *not* read. - """ - if not self.check(name): - raise self.raise_syntax_error(f"Expected {expected}") - return self.read() - - def read(self) -> Token: - """Consume the next token and return it.""" - token = self.next_token - assert token is not None - - self.position += len(token.text) - self.next_token = None - - return token - - def raise_syntax_error( - self, - message: str, - *, - span_start: Optional[int] = None, - span_end: Optional[int] = 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 - ) -> Iterator[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() diff --git a/pkg_resources/_vendor/packaging/markers.py b/pkg_resources/_vendor/packaging/markers.py deleted file mode 100644 index 8b98fca723..0000000000 --- a/pkg_resources/_vendor/packaging/markers.py +++ /dev/null @@ -1,252 +0,0 @@ -# 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 operator -import os -import platform -import sys -from typing import Any, Callable, Dict, List, Optional, Tuple, Union - -from ._parser import ( - MarkerAtom, - MarkerList, - Op, - Value, - Variable, - parse_marker as _parse_marker, -) -from ._tokenizer import ParserSyntaxError -from .specifiers import InvalidSpecifier, Specifier -from .utils import canonicalize_name - -__all__ = [ - "InvalidMarker", - "UndefinedComparison", - "UndefinedEnvironmentName", - "Marker", - "default_environment", -] - -Operator = Callable[[str, str], bool] - - -class InvalidMarker(ValueError): - """ - An invalid marker was found, users should refer to PEP 508. - """ - - -class UndefinedComparison(ValueError): - """ - An invalid operation was attempted on a value that doesn't support it. - """ - - -class UndefinedEnvironmentName(ValueError): - """ - A name was attempted to be used that does not exist inside of the - environment. - """ - - -def _normalize_extra_values(results: Any) -> Any: - """ - Normalize extra values. - """ - if isinstance(results[0], tuple): - lhs, op, rhs = results[0] - if isinstance(lhs, Variable) and lhs.value == "extra": - normalized_extra = canonicalize_name(rhs.value) - rhs = Value(normalized_extra) - elif isinstance(rhs, Variable) and rhs.value == "extra": - normalized_extra = canonicalize_name(lhs.value) - lhs = Value(normalized_extra) - results[0] = lhs, op, rhs - return results - - -def _format_marker( - marker: Union[List[str], MarkerAtom, str], first: Optional[bool] = True -) -> str: - - assert isinstance(marker, (list, tuple, str)) - - # Sometimes we have a structure like [[...]] which is a single item list - # where the single item is itself it's own list. In that case we want skip - # the rest of this function so that we don't get extraneous () on the - # outside. - if ( - isinstance(marker, list) - and len(marker) == 1 - and isinstance(marker[0], (list, tuple)) - ): - return _format_marker(marker[0]) - - if isinstance(marker, list): - inner = (_format_marker(m, first=False) for m in marker) - if first: - return " ".join(inner) - else: - return "(" + " ".join(inner) + ")" - elif isinstance(marker, tuple): - return " ".join([m.serialize() for m in marker]) - else: - return marker - - -_operators: Dict[str, Operator] = { - "in": lambda lhs, rhs: lhs in rhs, - "not in": lambda lhs, rhs: lhs not in rhs, - "<": operator.lt, - "<=": operator.le, - "==": operator.eq, - "!=": operator.ne, - ">=": operator.ge, - ">": operator.gt, -} - - -def _eval_op(lhs: str, op: Op, rhs: str) -> bool: - try: - spec = Specifier("".join([op.serialize(), rhs])) - except InvalidSpecifier: - pass - else: - return spec.contains(lhs, prereleases=True) - - oper: Optional[Operator] = _operators.get(op.serialize()) - if oper is None: - raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.") - - return oper(lhs, rhs) - - -def _normalize(*values: str, key: str) -> Tuple[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": - return tuple(canonicalize_name(v) for v in values) - - # other environment markers don't have such standards - return values - - -def _evaluate_markers(markers: MarkerList, environment: Dict[str, str]) -> bool: - groups: List[List[bool]] = [[]] - - for marker in markers: - assert isinstance(marker, (list, tuple, str)) - - if isinstance(marker, list): - groups[-1].append(_evaluate_markers(marker, environment)) - elif isinstance(marker, tuple): - lhs, op, rhs = marker - - if isinstance(lhs, Variable): - environment_key = lhs.value - lhs_value = environment[environment_key] - rhs_value = rhs.value - else: - lhs_value = lhs.value - environment_key = rhs.value - rhs_value = environment[environment_key] - - lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key) - groups[-1].append(_eval_op(lhs_value, op, rhs_value)) - else: - assert marker in ["and", "or"] - if marker == "or": - groups.append([]) - - return any(all(item) for item in groups) - - -def format_full_version(info: "sys._version_info") -> str: - version = "{0.major}.{0.minor}.{0.micro}".format(info) - kind = info.releaselevel - if kind != "final": - version += kind[0] + str(info.serial) - return version - - -def default_environment() -> Dict[str, str]: - iver = format_full_version(sys.implementation.version) - implementation_name = sys.implementation.name - return { - "implementation_name": implementation_name, - "implementation_version": iver, - "os_name": os.name, - "platform_machine": platform.machine(), - "platform_release": platform.release(), - "platform_system": platform.system(), - "platform_version": platform.version(), - "python_full_version": platform.python_version(), - "platform_python_implementation": platform.python_implementation(), - "python_version": ".".join(platform.python_version_tuple()[:2]), - "sys_platform": sys.platform, - } - - -class Marker: - def __init__(self, marker: str) -> None: - # Note: We create a Marker object without calling this constructor in - # packaging.requirements.Requirement. If any additional logic is - # added here, make sure to mirror/adapt Requirement. - try: - self._markers = _normalize_extra_values(_parse_marker(marker)) - # The attribute `_markers` can be described in terms of a recursive type: - # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]] - # - # For example, the following expression: - # python_version > "3.6" or (python_version == "3.6" and os_name == "unix") - # - # is parsed into: - # [ - # (, ')>, ), - # 'and', - # [ - # (, , ), - # 'or', - # (, , ) - # ] - # ] - except ParserSyntaxError as e: - raise InvalidMarker(str(e)) from e - - def __str__(self) -> str: - return _format_marker(self._markers) - - def __repr__(self) -> str: - return f"" - - def __hash__(self) -> int: - return hash((self.__class__.__name__, str(self))) - - def __eq__(self, other: Any) -> bool: - if not isinstance(other, Marker): - return NotImplemented - - return str(self) == str(other) - - def evaluate(self, environment: Optional[Dict[str, str]] = None) -> bool: - """Evaluate a marker. - - Return the boolean from evaluating the given marker against the - environment. environment is an optional argument to override all or - part of the determined environment. - - The environment is determined from the current Python process. - """ - current_environment = default_environment() - current_environment["extra"] = "" - if environment is not None: - current_environment.update(environment) - # The API used to allow setting extra to None. We need to handle this - # case for backwards compatibility. - if current_environment["extra"] is None: - current_environment["extra"] = "" - - return _evaluate_markers(self._markers, current_environment) diff --git a/pkg_resources/_vendor/packaging/metadata.py b/pkg_resources/_vendor/packaging/metadata.py deleted file mode 100644 index e76a60c395..0000000000 --- a/pkg_resources/_vendor/packaging/metadata.py +++ /dev/null @@ -1,408 +0,0 @@ -import email.feedparser -import email.header -import email.message -import email.parser -import email.policy -import sys -import typing -from typing import Dict, List, Optional, Tuple, Union, cast - -if sys.version_info >= (3, 8): # pragma: no cover - from typing import TypedDict -else: # pragma: no cover - if typing.TYPE_CHECKING: - from typing_extensions import TypedDict - else: - try: - from typing_extensions import TypedDict - except ImportError: - - class TypedDict: - def __init_subclass__(*_args, **_kwargs): - pass - - -# 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. - - Core metadata fields that can be specified multiple times are stored as a - list or dict depending on which is appropriate for the field. Any fields - which hold multiple values in a single field are stored as a list. - - """ - - # Metadata 1.0 - PEP 241 - metadata_version: str - name: str - version: str - platforms: List[str] - summary: str - description: str - keywords: List[str] - home_page: str - author: str - author_email: str - license: str - - # Metadata 1.1 - PEP 314 - supported_platforms: List[str] - download_url: str - classifiers: List[str] - requires: List[str] - provides: List[str] - obsoletes: List[str] - - # Metadata 1.2 - PEP 345 - maintainer: str - maintainer_email: str - requires_dist: List[str] - provides_dist: List[str] - obsoletes_dist: List[str] - requires_python: str - requires_external: List[str] - project_urls: Dict[str, str] - - # Metadata 2.0 - # PEP 426 attempted to completely revamp the metadata format - # but got stuck without ever being able to build consensus on - # it and ultimately ended up withdrawn. - # - # However, a number of tools had started emiting 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 interoptability. - - -_STRING_FIELDS = { - "author", - "author_email", - "description", - "description_content_type", - "download_url", - "home_page", - "license", - "maintainer", - "maintainer_email", - "metadata_version", - "name", - "requires_python", - "summary", - "version", -} - -_LIST_STRING_FIELDS = { - "classifiers", - "dynamic", - "obsoletes", - "obsoletes_dist", - "platforms", - "provides", - "provides_dist", - "provides_extra", - "requires", - "requires_dist", - "requires_external", - "supported_platforms", -} - - -def _parse_keywords(data: str) -> List[str]: - """Split a string of comma-separate keyboards 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 potentional 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 unparseable and add it - # to our list of unparsed fields. - parts = [p.strip() for p in pair.split(",", 1)] - parts.extend([""] * (max(0, 2 - len(parts)))) # Ensure 2 items - - # 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 = parts - if label in urls: - # The label already exists in our set of urls, so this field - # is unparseable, and we can just add the whole thing to our - # unparseable 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: Union[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: str = msg.get_payload() - return payload - # If our source is a bytes, then we're managing the encoding and we need - # to deal with it. - else: - bpayload: bytes = msg.get_payload(decode=True) - try: - return bpayload.decode("utf8", "strict") - except UnicodeDecodeError: - raise ValueError("payload in an invalid encoding") - - -# 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", - "keywords": "keywords", - "license": "license", - "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", -} - - -def parse_email(data: Union[bytes, str]) -> Tuple[RawMetadata, Dict[str, List[str]]]: - """Parse a distribution's 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, Union[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 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.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) - - # 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, Optional[str]]] = [] - for bin, encoding in email.header.decode_header(h): - try: - bin.decode("utf8", "strict") - except UnicodeDecodeError: - # Enable mojibake. - encoding = "latin1" - valid_encoding = False - else: - encoding = "utf8" - chunks.append((bin, 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 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_STRING_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 unparseable 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)) - ) - else: - if payload: - # Check to see if we've already got a description, if so then both - # it, and this body move to unparseable. - 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 diff --git a/pkg_resources/_vendor/packaging/requirements.py b/pkg_resources/_vendor/packaging/requirements.py deleted file mode 100644 index f34bfa85c8..0000000000 --- a/pkg_resources/_vendor/packaging/requirements.py +++ /dev/null @@ -1,95 +0,0 @@ -# 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 urllib.parse -from typing import Any, List, Optional, Set - -from ._parser import parse_requirement as _parse_requirement -from ._tokenizer import ParserSyntaxError -from .markers import Marker, _normalize_extra_values -from .specifiers import SpecifierSet - - -class InvalidRequirement(ValueError): - """ - An invalid requirement was found, users should refer to PEP 508. - """ - - -class Requirement: - """Parse a requirement. - - Parse a given requirement string into its parts, such as name, specifier, - URL, and extras. Raises InvalidRequirement on a badly-formed requirement - string. - """ - - # TODO: Can we test whether something is contained within a requirement? - # If so how do we do that? Do we need to test against the _name_ of - # the thing as well as the version? What about the markers? - # TODO: Can we normalize the name and extra name? - - def __init__(self, requirement_string: str) -> None: - try: - parsed = _parse_requirement(requirement_string) - except ParserSyntaxError as e: - raise InvalidRequirement(str(e)) from e - - self.name: str = parsed.name - if parsed.url: - parsed_url = urllib.parse.urlparse(parsed.url) - if parsed_url.scheme == "file": - if urllib.parse.urlunparse(parsed_url) != parsed.url: - raise InvalidRequirement("Invalid URL given") - elif not (parsed_url.scheme and parsed_url.netloc) or ( - not parsed_url.scheme and not parsed_url.netloc - ): - raise InvalidRequirement(f"Invalid URL: {parsed.url}") - self.url: Optional[str] = parsed.url - else: - self.url = None - self.extras: Set[str] = set(parsed.extras if parsed.extras else []) - self.specifier: SpecifierSet = SpecifierSet(parsed.specifier) - self.marker: Optional[Marker] = None - if parsed.marker is not None: - self.marker = Marker.__new__(Marker) - self.marker._markers = _normalize_extra_values(parsed.marker) - - def __str__(self) -> str: - parts: List[str] = [self.name] - - if self.extras: - formatted_extras = ",".join(sorted(self.extras)) - parts.append(f"[{formatted_extras}]") - - if self.specifier: - parts.append(str(self.specifier)) - - if self.url: - parts.append(f"@ {self.url}") - if self.marker: - parts.append(" ") - - if self.marker: - parts.append(f"; {self.marker}") - - return "".join(parts) - - def __repr__(self) -> str: - return f"" - - def __hash__(self) -> int: - return hash((self.__class__.__name__, str(self))) - - def __eq__(self, other: Any) -> bool: - if not isinstance(other, Requirement): - return NotImplemented - - return ( - self.name == other.name - and self.extras == other.extras - and self.specifier == other.specifier - and self.url == other.url - and self.marker == other.marker - ) diff --git a/pkg_resources/_vendor/packaging/specifiers.py b/pkg_resources/_vendor/packaging/specifiers.py deleted file mode 100644 index ba8fe37b7f..0000000000 --- a/pkg_resources/_vendor/packaging/specifiers.py +++ /dev/null @@ -1,1008 +0,0 @@ -# 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 -""" - -import abc -import itertools -import re -from typing import ( - Callable, - Iterable, - Iterator, - List, - Optional, - Set, - Tuple, - TypeVar, - Union, -) - -from .utils import canonicalize_version -from .version import Version - -UnparsedVersion = Union[Version, str] -UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion) -CallableOperator = Callable[[Version, str], bool] - - -def _coerce_version(version: UnparsedVersion) -> Version: - if not isinstance(version, Version): - version = Version(version) - return version - - -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): - @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) -> Optional[bool]: - """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 - def prereleases(self, value: bool) -> None: - """Setter for :attr:`prereleases`. - - :param value: The value to set. - """ - - @abc.abstractmethod - def contains(self, item: str, prereleases: Optional[bool] = None) -> bool: - """ - Determines if the given item is contained within this specifier. - """ - - @abc.abstractmethod - def filter( - self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None - ) -> Iterator[UnparsedVersionVar]: - """ - Takes an iterable of items and filters them so that only items which - are contained within this specifier are allowed in it. - """ - - -class Specifier(BaseSpecifier): - """This class abstracts handling of version specifiers. - - .. tip:: - - It is generally not required to instantiate this manually. You should instead - prefer to work with :class:`SpecifierSet` instead, which can parse - comma-separated version specifiers (which is what package metadata contains). - """ - - _operator_regex_str = r""" - (?P(~=|==|!=|<=|>=|<|>|===)) - """ - _version_regex_str = r""" - (?P - (?: - # The identity operators allow for an escape hatch that will - # do an exact string match of the version you wish to install. - # This will not be parsed by PEP 440 and we cannot determine - # any semantic meaning from it. This operator is discouraged - # but included entirely as an escape hatch. - (?<====) # Only match for the identity operator - \s* - [^\s;)]* # The arbitrary version can be just about anything, - # we match everything except for whitespace, a - # semi-colon for marker support, and a closing paren - # since versions can be enclosed in them. - ) - | - (?: - # The (non)equality operators allow for wild card and local - # versions to be specified so we have to define these two - # operators separately to enable that. - (?<===|!=) # Only match for equals and not equals - - \s* - v? - (?:[0-9]+!)? # epoch - [0-9]+(?:\.[0-9]+)* # release - - # You cannot use a wild card and a pre-release, post-release, a dev or - # local version together so group them with a | and make them optional. - (?: - \.\* # Wild card syntax of .* - | - (?: # pre release - [-_\.]? - (alpha|beta|preview|pre|a|b|c|rc) - [-_\.]? - [0-9]* - )? - (?: # post release - (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) - )? - (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release - (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local - )? - ) - | - (?: - # The compatible operator requires at least two digits in the - # release segment. - (?<=~=) # Only match for the compatible operator - - \s* - v? - (?:[0-9]+!)? # epoch - [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *) - (?: # pre release - [-_\.]? - (alpha|beta|preview|pre|a|b|c|rc) - [-_\.]? - [0-9]* - )? - (?: # post release - (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) - )? - (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release - ) - | - (?: - # All other operators only allow a sub set of what the - # (non)equality operators do. Specifically they do not allow - # local versions to be specified nor do they allow the prefix - # matching wild cards. - (?=": "greater_than_equal", - "<": "less_than", - ">": "greater_than", - "===": "arbitrary", - } - - def __init__(self, spec: str = "", prereleases: Optional[bool] = None) -> None: - """Initialize a Specifier instance. - - :param spec: - The string representation of a specifier which will be parsed and - normalized before use. - :param prereleases: - This tells the specifier if it should accept prerelease versions if - applicable or not. The default of ``None`` will autodetect it from the - given specifiers. - :raises InvalidSpecifier: - If the given specifier is invalid (i.e. bad syntax). - """ - match = self._regex.search(spec) - if not match: - raise InvalidSpecifier(f"Invalid specifier: '{spec}'") - - self._spec: Tuple[str, str] = ( - match.group("operator").strip(), - match.group("version").strip(), - ) - - # Store whether or not this Specifier should accept prereleases - self._prereleases = prereleases - - # https://github.com/python/mypy/pull/13475#pullrequestreview-1079784515 - @property # type: ignore[override] - def prereleases(self) -> bool: - # 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 - - # Look at all of our specifiers and determine if they are inclusive - # operators, and if they are if they are including an explicit - # prerelease. - operator, version = self._spec - if operator in ["==", ">=", "<=", "~=", "==="]: - # The == specifier can include a trailing .*, if it does we - # want to remove before parsing. - if operator == "==" and version.endswith(".*"): - version = version[:-2] - - # Parse the version, and if it is a pre-release than this - # specifier allows pre-releases. - if Version(version).is_prerelease: - return True - - return False - - @prereleases.setter - def prereleases(self, value: bool) -> None: - self._prereleases = value - - @property - def operator(self) -> str: - """The operator of this specifier. - - >>> Specifier("==1.2.3").operator - '==' - """ - return self._spec[0] - - @property - def version(self) -> str: - """The version of this specifier. - - >>> Specifier("==1.2.3").version - '1.2.3' - """ - return self._spec[1] - - def __repr__(self) -> str: - """A representation of the Specifier that shows all internal state. - - >>> Specifier('>=1.0.0') - =1.0.0')> - >>> Specifier('>=1.0.0', prereleases=False) - =1.0.0', prereleases=False)> - >>> Specifier('>=1.0.0', prereleases=True) - =1.0.0', prereleases=True)> - """ - pre = ( - f", prereleases={self.prereleases!r}" - if self._prereleases is not None - else "" - ) - - return f"<{self.__class__.__name__}({str(self)!r}{pre})>" - - def __str__(self) -> str: - """A string representation of the Specifier that can be round-tripped. - - >>> str(Specifier('>=1.0.0')) - '>=1.0.0' - >>> str(Specifier('>=1.0.0', prereleases=False)) - '>=1.0.0' - """ - return "{}{}".format(*self._spec) - - @property - def _canonical_spec(self) -> Tuple[str, str]: - canonical_version = canonicalize_version( - self._spec[1], - strip_trailing_zero=(self._spec[0] != "~="), - ) - return self._spec[0], canonical_version - - def __hash__(self) -> int: - return hash(self._canonical_spec) - - def __eq__(self, other: object) -> bool: - """Whether or not the two Specifier-like objects are equal. - - :param other: The other object to check against. - - The value of :attr:`prereleases` is ignored. - - >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0") - True - >>> (Specifier("==1.2.3", prereleases=False) == - ... Specifier("==1.2.3", prereleases=True)) - True - >>> Specifier("==1.2.3") == "==1.2.3" - True - >>> Specifier("==1.2.3") == Specifier("==1.2.4") - False - >>> Specifier("==1.2.3") == Specifier("~=1.2.3") - False - """ - if isinstance(other, str): - try: - other = self.__class__(str(other)) - except InvalidSpecifier: - return NotImplemented - elif not isinstance(other, self.__class__): - return NotImplemented - - return self._canonical_spec == other._canonical_spec - - def _get_operator(self, op: str) -> CallableOperator: - operator_callable: CallableOperator = getattr( - self, f"_compare_{self._operators[op]}" - ) - return operator_callable - - def _compare_compatible(self, prospective: Version, spec: str) -> bool: - - # Compatible releases have an equivalent combination of >= and ==. That - # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to - # implement this in terms of the other specifiers instead of - # implementing it ourselves. The only thing we need to do is construct - # the other specifiers. - - # We want everything but the last item in the version, but we want to - # ignore suffix segments. - prefix = ".".join( - list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1] - ) - - # Add the prefix notation to the end of our string - prefix += ".*" - - return self._get_operator(">=")(prospective, spec) and self._get_operator("==")( - prospective, prefix - ) - - def _compare_equal(self, prospective: Version, spec: str) -> bool: - - # We need special logic to handle prefix matching - if spec.endswith(".*"): - # In the case of prefix matching we want to ignore local segment. - normalized_prospective = canonicalize_version( - prospective.public, strip_trailing_zero=False - ) - # Get the normalized version string ignoring the trailing .* - normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False) - # Split the spec out by dots, and pretend that there is an implicit - # dot in between a release segment and a pre-release segment. - split_spec = _version_split(normalized_spec) - - # Split the prospective version out by dots, and pretend that there - # is an implicit dot in between a release segment and a pre-release - # segment. - split_prospective = _version_split(normalized_prospective) - - # 0-pad the prospective version before shortening it to get the correct - # shortened version. - padded_prospective, _ = _pad_version(split_prospective, split_spec) - - # Shorten the prospective version to be the same length as the spec - # so that we can determine if the specifier is a prefix of the - # prospective version or not. - shortened_prospective = padded_prospective[: len(split_spec)] - - return shortened_prospective == split_spec - else: - # Convert our spec string into a Version - spec_version = Version(spec) - - # If the specifier does not have a local segment, then we want to - # act as if the prospective version also does not have a local - # segment. - if not spec_version.local: - prospective = Version(prospective.public) - - return prospective == spec_version - - def _compare_not_equal(self, prospective: Version, spec: str) -> bool: - return not self._compare_equal(prospective, spec) - - def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool: - - # NB: Local version identifiers are NOT permitted in the version - # specifier, so local version labels can be universally removed from - # the prospective version. - return Version(prospective.public) <= Version(spec) - - def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool: - - # NB: Local version identifiers are NOT permitted in the version - # specifier, so local version labels can be universally removed from - # the prospective version. - return Version(prospective.public) >= Version(spec) - - def _compare_less_than(self, prospective: Version, spec_str: str) -> bool: - - # Convert our spec to a Version instance, since we'll want to work with - # it as a version. - spec = Version(spec_str) - - # Check to see if the prospective version is less than the spec - # version. If it's not we can short circuit and just return False now - # instead of doing extra unneeded work. - if not prospective < spec: - return False - - # This special case is here so that, unless the specifier itself - # includes is a pre-release version, that we do not accept pre-release - # versions for the version mentioned in the specifier (e.g. <3.1 should - # not match 3.1.dev0, but should match 3.0.dev0). - if not spec.is_prerelease and prospective.is_prerelease: - if Version(prospective.base_version) == Version(spec.base_version): - return False - - # If we've gotten to here, it means that prospective version is both - # less than the spec version *and* it's not a pre-release of the same - # version in the spec. - return True - - def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool: - - # Convert our spec to a Version instance, since we'll want to work with - # it as a version. - spec = Version(spec_str) - - # Check to see if the prospective version is greater than the spec - # version. If it's not we can short circuit and just return False now - # instead of doing extra unneeded work. - if not prospective > spec: - return False - - # This special case is here so that, unless the specifier itself - # includes is a post-release version, that we do not accept - # post-release versions for the version mentioned in the specifier - # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0). - if not spec.is_postrelease and prospective.is_postrelease: - if Version(prospective.base_version) == Version(spec.base_version): - return False - - # Ensure that we do not allow a local version of the version mentioned - # in the specifier, which is technically greater than, to match. - if prospective.local is not None: - if Version(prospective.base_version) == Version(spec.base_version): - return False - - # If we've gotten to here, it means that prospective version is both - # greater than the spec version *and* it's not a pre-release of the - # same version in the spec. - return True - - def _compare_arbitrary(self, prospective: Version, spec: str) -> bool: - return str(prospective).lower() == str(spec).lower() - - def __contains__(self, item: Union[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") - False - >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True) - True - """ - return self.contains(item) - - def contains( - self, item: UnparsedVersion, prereleases: Optional[bool] = None - ) -> bool: - """Return whether or not the item is contained in this specifier. - - :param item: - The item to check for, which can be a version string or a - :class:`Version` instance. - :param prereleases: - Whether or not to match prereleases with this Specifier. If set to - ``None`` (the default), it uses :attr:`prereleases` to determine - whether or not prereleases are allowed. - - >>> 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") - False - >>> Specifier(">=1.2.3", prereleases=True).contains("1.3.0a1") - True - >>> Specifier(">=1.2.3").contains("1.3.0a1", prereleases=True) - True - """ - - # Determine if prereleases are to be allowed or not. - if prereleases is None: - prereleases = self.prereleases - - # Normalize item to a Version, this allows us to have a shortcut for - # "2.0" in Specifier(">=2") - normalized_item = _coerce_version(item) - - # Determine if we should be supporting prereleases in this specifier - # or not, if we do not support prereleases than we can short circuit - # logic if this version is a prereleases. - if normalized_item.is_prerelease and not prereleases: - return False - - # Actually do the comparison to determine if this item is contained - # within this Specifier or not. - operator_callable: CallableOperator = self._get_operator(self.operator) - return operator_callable(normalized_item, self.version) - - def filter( - self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None - ) -> Iterator[UnparsedVersionVar]: - """Filter items in the given iterable, that match the specifier. - - :param iterable: - An iterable that can contain version strings and :class:`Version` instances. - The items in the iterable will be filtered according to the specifier. - :param prereleases: - Whether or not to allow prereleases in the returned iterator. If set to - ``None`` (the default), it will be intelligently decide whether to allow - prereleases or not (based on the :attr:`prereleases` attribute, and - whether the only versions matching are prereleases). - - This method is smarter than just ``filter(Specifier().contains, [...])`` - because it implements the rule from :pep:`440` that a prerelease item - SHOULD be accepted if no other versions match the given specifier. - - >>> 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'] - """ - - yielded = False - found_prereleases = [] - - kw = {"prereleases": prereleases if prereleases is not None else True} - - # Attempt to iterate over all the values in the iterable and if any of - # them match, yield them. - for version in iterable: - parsed_version = _coerce_version(version) - - if self.contains(parsed_version, **kw): - # If our version is a prerelease, and we were not set to allow - # prereleases, then we'll store it for later in case nothing - # else matches this specifier. - if parsed_version.is_prerelease and not ( - prereleases or self.prereleases - ): - found_prereleases.append(version) - # Either this is not a prerelease, or we should have been - # accepting prereleases from the beginning. - else: - yielded = True - yield version - - # Now that we've iterated over everything, determine if we've yielded - # any values, and if we have not and we have any prereleases stored up - # then we will go ahead and yield the prereleases. - if not yielded and found_prereleases: - for version in found_prereleases: - yield version - - -_prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$") - - -def _version_split(version: str) -> List[str]: - result: List[str] = [] - for item in version.split("."): - match = _prefix_regex.search(item) - if match: - result.extend(match.groups()) - else: - result.append(item) - return result - - -def _is_not_suffix(segment: str) -> bool: - return not any( - segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post") - ) - - -def _pad_version(left: List[str], right: List[str]) -> Tuple[List[str], List[str]]: - left_split, right_split = [], [] - - # Get the release segment of our versions - left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left))) - right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right))) - - # Get the rest of our versions - left_split.append(left[len(left_split[0]) :]) - right_split.append(right[len(right_split[0]) :]) - - # Insert our padding - left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0]))) - right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0]))) - - return (list(itertools.chain(*left_split)), list(itertools.chain(*right_split))) - - -class SpecifierSet(BaseSpecifier): - """This class abstracts handling of a set of version specifiers. - - It can be passed a single specifier (``>=3.0``), a comma-separated list of - specifiers (``>=3.0,!=3.1``), or no specifier at all. - """ - - def __init__( - self, specifiers: str = "", prereleases: Optional[bool] = 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. - :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. - """ - - # Split on `,` to break each individual specifier into it's own item, and - # strip each item to remove leading/trailing whitespace. - split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()] - - # Parsed each individual specifier, attempting first to make it a - # Specifier. - parsed: Set[Specifier] = set() - for specifier in split_specifiers: - parsed.add(Specifier(specifier)) - - # Turn our parsed specifiers into a frozen set and save them for later. - self._specs = frozenset(parsed) - - # Store our prereleases value so we can use it later to determine if - # we accept prereleases or not. - self._prereleases = prereleases - - @property - def prereleases(self) -> Optional[bool]: - # 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. - return any(s.prereleases for s in self._specs) - - @prereleases.setter - def prereleases(self, value: bool) -> None: - self._prereleases = value - - def __repr__(self) -> str: - """A representation of the specifier set that shows all internal state. - - Note that the ordering of the individual specifiers within the set may not - match the input string. - - >>> SpecifierSet('>=1.0.0,!=2.0.0') - =1.0.0')> - >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False) - =1.0.0', prereleases=False)> - >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True) - =1.0.0', prereleases=True)> - """ - pre = ( - f", prereleases={self.prereleases!r}" - if self._prereleases is not None - else "" - ) - - return f"" - - def __str__(self) -> str: - """A string representation of the specifier set that can be round-tripped. - - Note that the ordering of the individual specifiers within the set may not - match the input string. - - >>> str(SpecifierSet(">=1.0.0,!=1.0.1")) - '!=1.0.1,>=1.0.0' - >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False)) - '!=1.0.1,>=1.0.0' - """ - return ",".join(sorted(str(s) for s in self._specs)) - - def __hash__(self) -> int: - return hash(self._specs) - - def __and__(self, other: Union["SpecifierSet", str]) -> "SpecifierSet": - """Return a SpecifierSet which is a combination of the two sets. - - :param other: The other object to combine with. - - >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1' - =1.0.0')> - >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1') - =1.0.0')> - """ - if isinstance(other, str): - other = SpecifierSet(other) - elif not isinstance(other, SpecifierSet): - return NotImplemented - - specifier = SpecifierSet() - specifier._specs = frozenset(self._specs | other._specs) - - if self._prereleases is None and other._prereleases is not None: - specifier._prereleases = other._prereleases - elif self._prereleases is not None and other._prereleases is None: - specifier._prereleases = self._prereleases - elif self._prereleases == other._prereleases: - specifier._prereleases = self._prereleases - else: - raise ValueError( - "Cannot combine SpecifierSets with True and False prerelease " - "overrides." - ) - - return specifier - - def __eq__(self, other: object) -> bool: - """Whether or not the two SpecifierSet-like objects are equal. - - :param other: The other object to check against. - - The value of :attr:`prereleases` is ignored. - - >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1") - True - >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) == - ... SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)) - True - >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1" - True - >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0") - False - >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2") - False - """ - if isinstance(other, (str, Specifier)): - other = SpecifierSet(str(other)) - elif not isinstance(other, SpecifierSet): - return NotImplemented - - return self._specs == other._specs - - def __len__(self) -> int: - """Returns the number of specifiers in this specifier set.""" - return len(self._specs) - - def __iter__(self) -> Iterator[Specifier]: - """ - Returns an iterator over all the underlying :class:`Specifier` instances - in this specifier set. - - >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str) - [, =1.0.0')>] - """ - return iter(self._specs) - - def __contains__(self, item: UnparsedVersion) -> bool: - """Return whether or not the item is contained in this specifier. - - :param item: The item to check for. - - This is used for the ``in`` operator and behaves the same as - :meth:`contains` with no ``prereleases`` argument passed. - - >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1") - True - >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1") - True - >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1") - False - >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1") - False - >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True) - True - """ - return self.contains(item) - - def contains( - self, - item: UnparsedVersion, - prereleases: Optional[bool] = None, - installed: Optional[bool] = None, - ) -> bool: - """Return whether or not the item is contained in this SpecifierSet. - - :param item: - The item to check for, which can be a version string or a - :class:`Version` instance. - :param prereleases: - Whether or not to match prereleases with this SpecifierSet. If set to - ``None`` (the default), it uses :attr:`prereleases` to determine - whether or not prereleases are allowed. - - >>> 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") - False - >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True).contains("1.3.0a1") - True - >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True) - True - """ - # Ensure that our item is a Version instance. - if not isinstance(item, Version): - item = Version(item) - - # 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: - prereleases = self.prereleases - - # We can determine if we're going to allow pre-releases by looking to - # see if any of the underlying items supports them. If none of them do - # and this item is a pre-release then we do not allow it and we can - # short circuit that here. - # Note: This means that 1.0.dev1 would not be contained in something - # like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0 - if not prereleases and item.is_prerelease: - return False - - if installed and item.is_prerelease: - item = Version(item.base_version) - - # We simply dispatch to the underlying specs here to make sure that the - # given version is contained within all of them. - # Note: This use of all() here means that an empty set of specifiers - # will always return True, this is an explicit design decision. - return all(s.contains(item, prereleases=prereleases) for s in self._specs) - - def filter( - self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None - ) -> Iterator[UnparsedVersionVar]: - """Filter items in the given iterable, that match the specifiers in this set. - - :param iterable: - An iterable that can contain version strings and :class:`Version` instances. - The items in the iterable will be filtered according to the specifier. - :param prereleases: - Whether or not to allow prereleases in the returned iterator. If set to - ``None`` (the default), it will be intelligently decide whether to allow - prereleases or not (based on the :attr:`prereleases` attribute, and - whether the only versions matching are prereleases). - - This method is smarter than just ``filter(SpecifierSet(...).contains, [...])`` - because it implements the rule from :pep:`440` that a prerelease item - SHOULD be accepted if no other versions match the given specifier. - - >>> 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"])) - [] - >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) - ['1.3', '1.5a1'] - >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) - ['1.3', '1.5a1'] - - An "empty" SpecifierSet will filter items based on the presence of prerelease - versions in the set. - - >>> list(SpecifierSet("").filter(["1.3", "1.5a1"])) - ['1.3'] - >>> list(SpecifierSet("").filter(["1.5a1"])) - ['1.5a1'] - >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"])) - ['1.3', '1.5a1'] - >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True)) - ['1.3', '1.5a1'] - """ - # Determine if we're forcing a prerelease or not, if we're not forcing - # one for this particular filter call, then we'll use whatever the - # SpecifierSet thinks for whether or not we should support prereleases. - if prereleases is None: - prereleases = self.prereleases - - # If we have any specifiers, then we want to wrap our iterable in the - # filter method for each one, this will act as a logical AND amongst - # each specifier. - if self._specs: - for spec in self._specs: - iterable = spec.filter(iterable, prereleases=bool(prereleases)) - return iter(iterable) - # If we do not have any specifiers, then we need to have a rough filter - # which will filter out any pre-releases, unless there are no final - # releases. - else: - filtered: List[UnparsedVersionVar] = [] - found_prereleases: List[UnparsedVersionVar] = [] - - for item in iterable: - parsed_version = _coerce_version(item) - - # Store any item which is a pre-release for later unless we've - # already found a final version or we are accepting prereleases - if parsed_version.is_prerelease and not prereleases: - if not filtered: - found_prereleases.append(item) - else: - filtered.append(item) - - # If we've found no items except for pre-releases, then we'll go - # ahead and use the pre-releases - if not filtered and found_prereleases and prereleases is None: - return iter(found_prereleases) - - return iter(filtered) diff --git a/pkg_resources/_vendor/packaging/tags.py b/pkg_resources/_vendor/packaging/tags.py deleted file mode 100644 index 76d243414d..0000000000 --- a/pkg_resources/_vendor/packaging/tags.py +++ /dev/null @@ -1,546 +0,0 @@ -# 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 logging -import platform -import subprocess -import sys -import sysconfig -from importlib.machinery import EXTENSION_SUFFIXES -from typing import ( - Dict, - FrozenSet, - Iterable, - Iterator, - List, - Optional, - Sequence, - Tuple, - Union, - cast, -) - -from . import _manylinux, _musllinux - -logger = logging.getLogger(__name__) - -PythonVersion = Sequence[int] -MacVersion = Tuple[int, int] - -INTERPRETER_SHORT_NAMES: Dict[str, str] = { - "python": "py", # Generic. - "cpython": "cp", - "pypy": "pp", - "ironpython": "ip", - "jython": "jy", -} - - -_32_BIT_INTERPRETER = sys.maxsize <= 2**32 - - -class Tag: - """ - A representation of the tag triple for a wheel. - - Instances are considered immutable and thus are hashable. Equality checking - is also supported. - """ - - __slots__ = ["_interpreter", "_abi", "_platform", "_hash"] - - def __init__(self, interpreter: str, abi: str, platform: str) -> None: - self._interpreter = interpreter.lower() - self._abi = abi.lower() - self._platform = platform.lower() - # The __hash__ of every single element in a Set[Tag] will be evaluated each time - # that a set calls its `.disjoint()` method, which may be called hundreds of - # times when scanning a page of links for packages with tags matching that - # Set[Tag]. Pre-computing the value here produces significant speedups for - # downstream consumers. - self._hash = hash((self._interpreter, self._abi, self._platform)) - - @property - def interpreter(self) -> str: - return self._interpreter - - @property - def abi(self) -> str: - return self._abi - - @property - def platform(self) -> str: - return self._platform - - def __eq__(self, other: object) -> bool: - if not isinstance(other, Tag): - return NotImplemented - - return ( - (self._hash == other._hash) # Short-circuit ASAP for perf reasons. - and (self._platform == other._platform) - and (self._abi == other._abi) - and (self._interpreter == other._interpreter) - ) - - def __hash__(self) -> int: - return self._hash - - def __str__(self) -> str: - return f"{self._interpreter}-{self._abi}-{self._platform}" - - def __repr__(self) -> str: - return f"<{self} @ {id(self)}>" - - -def parse_tag(tag: str) -> FrozenSet[Tag]: - """ - Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances. - - Returning a set is required due to the possibility that the tag is a - compressed tag set. - """ - tags = set() - interpreters, abis, platforms = tag.split("-") - for interpreter in interpreters.split("."): - for abi in abis.split("."): - for platform_ in platforms.split("."): - tags.add(Tag(interpreter, abi, platform_)) - return frozenset(tags) - - -def _get_config_var(name: str, warn: bool = False) -> Union[int, str, None]: - value: Union[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 _abi3_applies(python_version: PythonVersion) -> bool: - """ - Determine if the Python version supports abi3. - - PEP 384 was first implemented in Python 3.2. - """ - return len(python_version) > 1 and tuple(python_version) >= (3, 2) - - -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]) - 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, 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}") - abis.insert( - 0, - "cp{version}{debug}{pymalloc}{ucs4}".format( - version=version, debug=debug, pymalloc=pymalloc, ucs4=ucs4 - ), - ) - return abis - - -def cpython_tags( - python_version: Optional[PythonVersion] = None, - abis: Optional[Iterable[str]] = None, - platforms: Optional[Iterable[str]] = None, - *, - warn: bool = False, -) -> Iterator[Tag]: - """ - Yields the tags for a CPython interpreter. - - The tags consist of: - - cp-- - - cp-abi3- - - cp-none- - - cp-abi3- # Older Python versions down to 3.2. - - If python_version only specifies a major version then user-provided ABIs and - the 'none' ABItag will be used. - - If 'abi3' or 'none' are specified in 'abis' then they will be yielded at - their normal position and not at the beginning. - """ - if not python_version: - python_version = sys.version_info[:2] - - interpreter = f"cp{_version_nodot(python_version[:2])}" - - if abis is None: - if len(python_version) > 1: - abis = _cpython_abis(python_version, warn) - else: - abis = [] - abis = list(abis) - # 'abi3' and 'none' are explicitly handled later. - for explicit_abi in ("abi3", "none"): - try: - abis.remove(explicit_abi) - except ValueError: - pass - - platforms = list(platforms or platform_tags()) - for abi in abis: - for platform_ in platforms: - yield Tag(interpreter, abi, platform_) - if _abi3_applies(python_version): - yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms) - yield from (Tag(interpreter, "none", platform_) for platform_ in platforms) - - if _abi3_applies(python_version): - for minor_version in range(python_version[1] - 1, 1, -1): - for platform_ in platforms: - interpreter = "cp{version}".format( - version=_version_nodot((python_version[0], minor_version)) - ) - yield Tag(interpreter, "abi3", platform_) - - -def _generic_abi() -> List[str]: - """ - Return the ABI tag based on EXT_SUFFIX. - """ - # The following are examples of `EXT_SUFFIX`. - # We want to keep the parts which are related to the ABI and remove the - # parts which are related to the platform: - # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310 - # - mac: '.cpython-310-darwin.so' => cp310 - # - win: '.cp310-win_amd64.pyd' => cp310 - # - win: '.pyd' => cp37 (uses _cpython_abis()) - # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73 - # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib' - # => graalpy_38_native - - ext_suffix = _get_config_var("EXT_SUFFIX", warn=True) - if not isinstance(ext_suffix, str) or ext_suffix[0] != ".": - raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')") - parts = ext_suffix.split(".") - if len(parts) < 3: - # CPython3.7 and earlier uses ".pyd" on Windows. - return _cpython_abis(sys.version_info[:2]) - soabi = parts[1] - if soabi.startswith("cpython"): - # non-windows - abi = "cp" + soabi.split("-")[1] - elif soabi.startswith("cp"): - # windows - abi = soabi.split("-")[0] - elif soabi.startswith("pypy"): - abi = "-".join(soabi.split("-")[:2]) - elif soabi.startswith("graalpy"): - abi = "-".join(soabi.split("-")[:3]) - elif soabi: - # pyston, ironpython, others? - abi = soabi - else: - return [] - return [_normalize_string(abi)] - - -def generic_tags( - interpreter: Optional[str] = None, - abis: Optional[Iterable[str]] = None, - platforms: Optional[Iterable[str]] = None, - *, - warn: bool = False, -) -> Iterator[Tag]: - """ - Yields the tags for a generic interpreter. - - The tags consist of: - - -- - - The "none" ABI will be added if it was not explicitly provided. - """ - if not interpreter: - interp_name = interpreter_name() - interp_version = interpreter_version(warn=warn) - interpreter = "".join([interp_name, interp_version]) - if abis is None: - abis = _generic_abi() - else: - abis = list(abis) - platforms = list(platforms or platform_tags()) - if "none" not in abis: - abis.append("none") - for abi in abis: - for platform_ in platforms: - yield Tag(interpreter, abi, platform_) - - -def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]: - """ - Yields Python versions in descending order. - - After the latest version, the major-only version will be yielded, and then - all previous versions of that major version. - """ - if len(py_version) > 1: - yield f"py{_version_nodot(py_version[:2])}" - yield f"py{py_version[0]}" - if len(py_version) > 1: - for minor in range(py_version[1] - 1, -1, -1): - yield f"py{_version_nodot((py_version[0], minor))}" - - -def compatible_tags( - python_version: Optional[PythonVersion] = None, - interpreter: Optional[str] = None, - platforms: Optional[Iterable[str]] = None, -) -> Iterator[Tag]: - """ - Yields the sequence of tags that are compatible with a specific version of Python. - - The tags consist of: - - py*-none- - - -none-any # ... if `interpreter` is provided. - - py*-none-any - """ - if not python_version: - python_version = sys.version_info[:2] - platforms = list(platforms or platform_tags()) - for version in _py_interpreter_range(python_version): - for platform_ in platforms: - yield Tag(version, "none", platform_) - if interpreter: - yield Tag(interpreter, "none", "any") - for version in _py_interpreter_range(python_version): - yield Tag(version, "none", "any") - - -def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str: - if not is_32bit: - return arch - - if arch.startswith("ppc"): - return "ppc" - - return "i386" - - -def _mac_binary_formats(version: MacVersion, cpu_arch: str) -> List[str]: - formats = [cpu_arch] - if cpu_arch == "x86_64": - if version < (10, 4): - return [] - formats.extend(["intel", "fat64", "fat32"]) - - elif cpu_arch == "i386": - if version < (10, 4): - return [] - formats.extend(["intel", "fat32", "fat"]) - - elif cpu_arch == "ppc64": - # TODO: Need to care about 32-bit PPC for ppc64 through 10.2? - if version > (10, 5) or version < (10, 4): - return [] - formats.append("fat64") - - elif cpu_arch == "ppc": - if version > (10, 6): - return [] - formats.extend(["fat32", "fat"]) - - if cpu_arch in {"arm64", "x86_64"}: - formats.append("universal2") - - if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}: - formats.append("universal") - - return formats - - -def mac_platforms( - version: Optional[MacVersion] = None, arch: Optional[str] = None -) -> Iterator[str]: - """ - Yields the platform tags for a macOS system. - - The `version` parameter is a two-item tuple specifying the macOS version to - generate platform tags for. The `arch` parameter is the CPU architecture to - generate platform tags for. Both parameters default to the appropriate value - for the current system. - """ - version_str, _, cpu_arch = platform.mac_ver() - if version is None: - version = cast("MacVersion", 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, - universal_newlines=True, - ).stdout - version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2]))) - else: - version = version - if arch is None: - arch = _mac_arch(cpu_arch) - else: - arch = arch - - if (10, 0) <= version and 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. - for minor_version in range(version[1], -1, -1): - compat_version = 10, minor_version - binary_formats = _mac_binary_formats(compat_version, arch) - for binary_format in binary_formats: - yield "macosx_{major}_{minor}_{binary_format}".format( - major=10, minor=minor_version, binary_format=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. - for major_version in range(version[0], 10, -1): - compat_version = major_version, 0 - binary_formats = _mac_binary_formats(compat_version, arch) - for binary_format in binary_formats: - yield "macosx_{major}_{minor}_{binary_format}".format( - major=major_version, minor=0, binary_format=binary_format - ) - - if version >= (11, 0): - # Mac OS 11 on x86_64 is compatible with binaries from previous releases. - # Arm64 support was introduced in 11.0, so no Arm binaries from previous - # releases exist. - # - # However, the "universal2" binary format can have a - # macOS version earlier than 11.0 when the x86_64 part of the binary supports - # that version of macOS. - if arch == "x86_64": - for minor_version in range(16, 3, -1): - compat_version = 10, minor_version - binary_formats = _mac_binary_formats(compat_version, arch) - for binary_format in binary_formats: - yield "macosx_{major}_{minor}_{binary_format}".format( - major=compat_version[0], - minor=compat_version[1], - binary_format=binary_format, - ) - else: - for minor_version in range(16, 3, -1): - compat_version = 10, minor_version - binary_format = "universal2" - yield "macosx_{major}_{minor}_{binary_format}".format( - major=compat_version[0], - minor=compat_version[1], - binary_format=binary_format, - ) - - -def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]: - linux = _normalize_string(sysconfig.get_platform()) - if is_32bit: - if linux == "linux_x86_64": - linux = "linux_i686" - elif linux == "linux_aarch64": - linux = "linux_armv7l" - _, arch = linux.split("_", 1) - yield from _manylinux.platform_tags(linux, arch) - yield from _musllinux.platform_tags(arch) - yield linux - - -def _generic_platforms() -> Iterator[str]: - yield _normalize_string(sysconfig.get_platform()) - - -def platform_tags() -> Iterator[str]: - """ - Provides the platform tags for this installation. - """ - if platform.system() == "Darwin": - return mac_platforms() - elif platform.system() == "Linux": - return _linux_platforms() - else: - return _generic_platforms() - - -def interpreter_name() -> str: - """ - Returns the name of the running interpreter. - - Some implementations have a reserved, two-letter abbreviation which will - be returned when appropriate. - """ - name = sys.implementation.name - return INTERPRETER_SHORT_NAMES.get(name) or name - - -def interpreter_version(*, warn: bool = False) -> str: - """ - Returns the version of the running interpreter. - """ - version = _get_config_var("py_version_nodot", warn=warn) - if version: - version = str(version) - else: - version = _version_nodot(sys.version_info[:2]) - return version - - -def _version_nodot(version: PythonVersion) -> str: - return "".join(map(str, version)) - - -def sys_tags(*, warn: bool = False) -> Iterator[Tag]: - """ - Returns the sequence of tag triples for the running interpreter. - - The order of the sequence corresponds to priority order for the - interpreter, from most to least important. - """ - - interp_name = interpreter_name() - if interp_name == "cp": - yield from cpython_tags(warn=warn) - else: - yield from generic_tags() - - if interp_name == "pp": - interp = "pp3" - elif interp_name == "cp": - interp = "cp" + interpreter_version(warn=warn) - else: - interp = None - yield from compatible_tags(interpreter=interp) diff --git a/pkg_resources/_vendor/packaging/utils.py b/pkg_resources/_vendor/packaging/utils.py deleted file mode 100644 index 33c613b749..0000000000 --- a/pkg_resources/_vendor/packaging/utils.py +++ /dev/null @@ -1,141 +0,0 @@ -# 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 re -from typing import FrozenSet, NewType, Tuple, Union, cast - -from .tags import Tag, parse_tag -from .version import InvalidVersion, Version - -BuildTag = Union[Tuple[()], Tuple[int, str]] -NormalizedName = NewType("NormalizedName", str) - - -class InvalidWheelFilename(ValueError): - """ - An invalid wheel filename was found, users should refer to PEP 427. - """ - - -class InvalidSdistFilename(ValueError): - """ - An invalid sdist filename was found, users should refer to the packaging user guide. - """ - - -_canonicalize_regex = re.compile(r"[-_.]+") -# PEP 427: The build number must start with a digit. -_build_tag_regex = re.compile(r"(\d+)(.*)") - - -def canonicalize_name(name: str) -> NormalizedName: - # This is taken from PEP 503. - value = _canonicalize_regex.sub("-", name).lower() - return cast(NormalizedName, value) - - -def canonicalize_version( - version: Union[Version, str], *, strip_trailing_zero: bool = True -) -> str: - """ - This is very similar to Version.__str__, but has one subtle difference - with the way it handles the release segment. - """ - if isinstance(version, str): - try: - parsed = Version(version) - except InvalidVersion: - # Legacy versions cannot be normalized - return version - else: - parsed = version - - parts = [] - - # Epoch - if parsed.epoch != 0: - parts.append(f"{parsed.epoch}!") - - # Release segment - release_segment = ".".join(str(x) for x in parsed.release) - if strip_trailing_zero: - # NB: This strips trailing '.0's to normalize - release_segment = re.sub(r"(\.0)+$", "", release_segment) - parts.append(release_segment) - - # Pre-release - if parsed.pre is not None: - parts.append("".join(str(x) for x in parsed.pre)) - - # Post-release - if parsed.post is not None: - parts.append(f".post{parsed.post}") - - # Development release - if parsed.dev is not None: - parts.append(f".dev{parsed.dev}") - - # Local version segment - if parsed.local is not None: - parts.append(f"+{parsed.local}") - - return "".join(parts) - - -def parse_wheel_filename( - filename: str, -) -> Tuple[NormalizedName, Version, BuildTag, FrozenSet[Tag]]: - if not filename.endswith(".whl"): - raise InvalidWheelFilename( - f"Invalid wheel filename (extension must be '.whl'): {filename}" - ) - - filename = filename[:-4] - dashes = filename.count("-") - if dashes not in (4, 5): - raise InvalidWheelFilename( - f"Invalid wheel filename (wrong number of parts): {filename}" - ) - - parts = filename.split("-", dashes - 2) - name_part = parts[0] - # See PEP 427 for the rules on escaping the project name - if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None: - raise InvalidWheelFilename(f"Invalid project name: {filename}") - name = canonicalize_name(name_part) - version = Version(parts[1]) - 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}'" - ) - build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2))) - else: - build = () - tags = parse_tag(parts[-1]) - return (name, version, build, tags) - - -def parse_sdist_filename(filename: str) -> Tuple[NormalizedName, Version]: - if filename.endswith(".tar.gz"): - file_stem = filename[: -len(".tar.gz")] - elif filename.endswith(".zip"): - file_stem = filename[: -len(".zip")] - else: - raise InvalidSdistFilename( - f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):" - f" {filename}" - ) - - # 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}") - - name = canonicalize_name(name_part) - version = Version(version_part) - return (name, version) diff --git a/pkg_resources/_vendor/packaging/version.py b/pkg_resources/_vendor/packaging/version.py deleted file mode 100644 index b30e8cbf84..0000000000 --- a/pkg_resources/_vendor/packaging/version.py +++ /dev/null @@ -1,564 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. -""" -.. testsetup:: - - from packaging.version import parse, Version -""" - -import collections -import itertools -import re -from typing import Any, Callable, Optional, SupportsInt, Tuple, Union - -from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType - -__all__ = ["VERSION_PATTERN", "parse", "Version", "InvalidVersion"] - -InfiniteTypes = Union[InfinityType, NegativeInfinityType] -PrePostDevType = Union[InfiniteTypes, Tuple[str, int]] -SubLocalType = Union[InfiniteTypes, int, str] -LocalType = Union[ - NegativeInfinityType, - Tuple[ - Union[ - SubLocalType, - Tuple[SubLocalType, str], - Tuple[NegativeInfinityType, SubLocalType], - ], - ..., - ], -] -CmpKey = Tuple[ - int, Tuple[int, ...], PrePostDevType, PrePostDevType, PrePostDevType, LocalType -] -VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool] - -_Version = collections.namedtuple( - "_Version", ["epoch", "release", "dev", "pre", "post", "local"] -) - - -def parse(version: str) -> "Version": - """Parse the given version string. - - >>> parse('1.0.dev1') - - - :param version: The version string to parse. - :raises InvalidVersion: When the version string is not a valid version. - """ - return Version(version) - - -class InvalidVersion(ValueError): - """Raised when a version string is not a valid version. - - >>> Version("invalid") - Traceback (most recent call last): - ... - packaging.version.InvalidVersion: Invalid version: 'invalid' - """ - - -class _BaseVersion: - _key: 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 -_VERSION_PATTERN = r""" - v? - (?: - (?:(?P[0-9]+)!)? # epoch - (?P[0-9]+(?:\.[0-9]+)*) # release segment - (?P
                                          # pre-release
-            [-_\.]?
-            (?P(a|b|c|rc|alpha|beta|pre|preview))
-            [-_\.]?
-            (?P[0-9]+)?
-        )?
-        (?P                                         # post release
-            (?:-(?P[0-9]+))
-            |
-            (?:
-                [-_\.]?
-                (?Ppost|rev|r)
-                [-_\.]?
-                (?P[0-9]+)?
-            )
-        )?
-        (?P                                          # dev release
-            [-_\.]?
-            (?Pdev)
-            [-_\.]?
-            (?P[0-9]+)?
-        )?
-    )
-    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
-"""
-
-VERSION_PATTERN = _VERSION_PATTERN
-"""
-A string containing the regular expression used to match a valid version.
-
-The pattern is not anchored at either end, and is intended for embedding in larger
-expressions (for example, matching a version number as part of a file name). The
-regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
-flags set.
-
-:meta hide-value:
-"""
-
-
-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
-    """
-
-    _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
-    _key: CmpKey
-
-    def __init__(self, version: str) -> None:
-        """Initialize a Version object.
-
-        :param version:
-            The string representation of a version which will be parsed and normalized
-            before use.
-        :raises InvalidVersion:
-            If the ``version`` does not conform to PEP 440 in any way then this
-            exception will be raised.
-        """
-
-        # Validate the version and parse it into pieces
-        match = self._regex.search(version)
-        if not match:
-            raise InvalidVersion(f"Invalid version: '{version}'")
-
-        # Store the parsed out pieces of the version
-        self._version = _Version(
-            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
-            release=tuple(int(i) for i in match.group("release").split(".")),
-            pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
-            post=_parse_letter_version(
-                match.group("post_l"), match.group("post_n1") or match.group("post_n2")
-            ),
-            dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
-            local=_parse_local_version(match.group("local")),
-        )
-
-        # Generate a key which will be used for sorting
-        self._key = _cmpkey(
-            self._version.epoch,
-            self._version.release,
-            self._version.pre,
-            self._version.post,
-            self._version.dev,
-            self._version.local,
-        )
-
-    def __repr__(self) -> str:
-        """A representation of the Version that shows all internal state.
-
-        >>> Version('1.0.0')
-        
-        """
-        return f""
-
-    def __str__(self) -> str:
-        """A string representation of the version that can be rounded-tripped.
-
-        >>> str(Version("1.0a5"))
-        '1.0a5'
-        """
-        parts = []
-
-        # Epoch
-        if self.epoch != 0:
-            parts.append(f"{self.epoch}!")
-
-        # Release segment
-        parts.append(".".join(str(x) for x in self.release))
-
-        # Pre-release
-        if self.pre is not None:
-            parts.append("".join(str(x) for x in self.pre))
-
-        # Post-release
-        if self.post is not None:
-            parts.append(f".post{self.post}")
-
-        # Development release
-        if self.dev is not None:
-            parts.append(f".dev{self.dev}")
-
-        # Local version segment
-        if self.local is not None:
-            parts.append(f"+{self.local}")
-
-        return "".join(parts)
-
-    @property
-    def epoch(self) -> int:
-        """The epoch of the version.
-
-        >>> Version("2.0.0").epoch
-        0
-        >>> Version("1!2.0.0").epoch
-        1
-        """
-        _epoch: int = self._version.epoch
-        return _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.
-        """
-        _release: Tuple[int, ...] = self._version.release
-        return _release
-
-    @property
-    def pre(self) -> Optional[Tuple[str, int]]:
-        """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)
-        """
-        _pre: Optional[Tuple[str, int]] = self._version.pre
-        return _pre
-
-    @property
-    def post(self) -> Optional[int]:
-        """The post-release number of the version.
-
-        >>> print(Version("1.2.3").post)
-        None
-        >>> Version("1.2.3.post1").post
-        1
-        """
-        return self._version.post[1] if self._version.post else None
-
-    @property
-    def dev(self) -> Optional[int]:
-        """The development number of the version.
-
-        >>> print(Version("1.2.3").dev)
-        None
-        >>> Version("1.2.3.dev1").dev
-        1
-        """
-        return self._version.dev[1] if self._version.dev else None
-
-    @property
-    def local(self) -> Optional[str]:
-        """The local version segment of the version.
-
-        >>> print(Version("1.2.3").local)
-        None
-        >>> Version("1.2.3+abc").local
-        'abc'
-        """
-        if self._version.local:
-            return ".".join(str(x) for x in self._version.local)
-        else:
-            return None
-
-    @property
-    def public(self) -> str:
-        """The public portion of the version.
-
-        >>> Version("1.2.3").public
-        '1.2.3'
-        >>> Version("1.2.3+abc").public
-        '1.2.3'
-        >>> Version("1.2.3+abc.dev1").public
-        '1.2.3'
-        """
-        return str(self).split("+", 1)[0]
-
-    @property
-    def base_version(self) -> str:
-        """The "base version" of the version.
-
-        >>> Version("1.2.3").base_version
-        '1.2.3'
-        >>> Version("1.2.3+abc").base_version
-        '1.2.3'
-        >>> Version("1!1.2.3+abc.dev1").base_version
-        '1!1.2.3'
-
-        The "base version" is the public version of the project without any pre or post
-        release markers.
-        """
-        parts = []
-
-        # Epoch
-        if self.epoch != 0:
-            parts.append(f"{self.epoch}!")
-
-        # Release segment
-        parts.append(".".join(str(x) for x in self.release))
-
-        return "".join(parts)
-
-    @property
-    def is_prerelease(self) -> bool:
-        """Whether this version is a pre-release.
-
-        >>> Version("1.2.3").is_prerelease
-        False
-        >>> Version("1.2.3a1").is_prerelease
-        True
-        >>> Version("1.2.3b1").is_prerelease
-        True
-        >>> Version("1.2.3rc1").is_prerelease
-        True
-        >>> Version("1.2.3dev1").is_prerelease
-        True
-        """
-        return self.dev is not None or self.pre is not None
-
-    @property
-    def is_postrelease(self) -> bool:
-        """Whether this version is a post-release.
-
-        >>> Version("1.2.3").is_postrelease
-        False
-        >>> Version("1.2.3.post1").is_postrelease
-        True
-        """
-        return self.post is not None
-
-    @property
-    def is_devrelease(self) -> bool:
-        """Whether this version is a development release.
-
-        >>> Version("1.2.3").is_devrelease
-        False
-        >>> Version("1.2.3.dev1").is_devrelease
-        True
-        """
-        return self.dev is not None
-
-    @property
-    def major(self) -> int:
-        """The first item of :attr:`release` or ``0`` if unavailable.
-
-        >>> Version("1.2.3").major
-        1
-        """
-        return self.release[0] if len(self.release) >= 1 else 0
-
-    @property
-    def minor(self) -> int:
-        """The second item of :attr:`release` or ``0`` if unavailable.
-
-        >>> Version("1.2.3").minor
-        2
-        >>> Version("1").minor
-        0
-        """
-        return self.release[1] if len(self.release) >= 2 else 0
-
-    @property
-    def micro(self) -> int:
-        """The third item of :attr:`release` or ``0`` if unavailable.
-
-        >>> Version("1.2.3").micro
-        3
-        >>> Version("1").micro
-        0
-        """
-        return self.release[2] if len(self.release) >= 3 else 0
-
-
-def _parse_letter_version(
-    letter: str, number: Union[str, bytes, SupportsInt]
-) -> Optional[Tuple[str, int]]:
-
-    if letter:
-        # We consider there to be an implicit 0 in a pre-release if there is
-        # not a numeral associated with it.
-        if number is None:
-            number = 0
-
-        # 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.
-        if letter == "alpha":
-            letter = "a"
-        elif letter == "beta":
-            letter = "b"
-        elif letter in ["c", "pre", "preview"]:
-            letter = "rc"
-        elif letter in ["rev", "r"]:
-            letter = "post"
-
-        return letter, int(number)
-    if not letter and 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)
-        letter = "post"
-
-        return letter, int(number)
-
-    return None
-
-
-_local_version_separators = re.compile(r"[\._-]")
-
-
-def _parse_local_version(local: str) -> Optional[LocalType]:
-    """
-    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
-    """
-    if local is not None:
-        return tuple(
-            part.lower() if not part.isdigit() else int(part)
-            for part in _local_version_separators.split(local)
-        )
-    return None
-
-
-def _cmpkey(
-    epoch: int,
-    release: Tuple[int, ...],
-    pre: Optional[Tuple[str, int]],
-    post: Optional[Tuple[str, int]],
-    dev: Optional[Tuple[str, int]],
-    local: Optional[Tuple[SubLocalType]],
-) -> CmpKey:
-
-    # When we compare a release version, we want to compare it with all of the
-    # trailing zeros removed. So we'll use a reverse the list, drop all the now
-    # leading zeros until we come to something non zero, then take the rest
-    # re-reverse it back into the correct order and make it a tuple and use
-    # that for our sorting key.
-    _release = tuple(
-        reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
-    )
-
-    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
-    # We'll do this by abusing the pre segment, but we _only_ want to do this
-    # if there is not a pre or a post segment. If we have one of those then
-    # the normal sorting rules will handle this case correctly.
-    if pre is None and post is None and dev is not None:
-        _pre: PrePostDevType = NegativeInfinity
-    # Versions without a pre-release (except as noted above) should sort after
-    # those with one.
-    elif pre is None:
-        _pre = Infinity
-    else:
-        _pre = pre
-
-    # Versions without a post segment should sort before those with one.
-    if post is None:
-        _post: PrePostDevType = NegativeInfinity
-
-    else:
-        _post = post
-
-    # Versions without a development segment should sort after those with one.
-    if dev is None:
-        _dev: PrePostDevType = Infinity
-
-    else:
-        _dev = dev
-
-    if local is None:
-        # Versions without a local segment should sort before those with one.
-        _local: LocalType = NegativeInfinity
-    else:
-        # Versions with a local segment need that segment parsed to implement
-        # the sorting rules in PEP440.
-        # - Alpha numeric segments sort before numeric segments
-        # - Alpha numeric segments sort lexicographically
-        # - Numeric segments sort numerically
-        # - Shorter versions sort before longer versions when the prefixes
-        #   match exactly
-        _local = tuple(
-            (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
-        )
-
-    return epoch, _release, _pre, _post, _dev, _local
diff --git a/pkg_resources/_vendor/platformdirs-2.6.2.dist-info/INSTALLER b/pkg_resources/_vendor/platformdirs-2.6.2.dist-info/INSTALLER
deleted file mode 100644
index a1b589e38a..0000000000
--- a/pkg_resources/_vendor/platformdirs-2.6.2.dist-info/INSTALLER
+++ /dev/null
@@ -1 +0,0 @@
-pip
diff --git a/pkg_resources/_vendor/platformdirs-2.6.2.dist-info/RECORD b/pkg_resources/_vendor/platformdirs-2.6.2.dist-info/RECORD
deleted file mode 100644
index 843a5baf9d..0000000000
--- a/pkg_resources/_vendor/platformdirs-2.6.2.dist-info/RECORD
+++ /dev/null
@@ -1,23 +0,0 @@
-platformdirs-2.6.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-platformdirs-2.6.2.dist-info/METADATA,sha256=rDoFsb9-2tVym02IIeYCoKgGaCpY2v8xw8WWXywxhIM,9502
-platformdirs-2.6.2.dist-info/RECORD,,
-platformdirs-2.6.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-platformdirs-2.6.2.dist-info/WHEEL,sha256=NaLmgHHW_f9jTvv_wRh9vcK7c7EK9o5fwsIXMOzoGgM,87
-platformdirs-2.6.2.dist-info/licenses/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089
-platformdirs/__init__.py,sha256=td0a-fHENmnG8ess2WRoysKv9ud5j6TQ-p_iUM_uE18,12864
-platformdirs/__main__.py,sha256=VsC0t5m-6f0YVr96PVks93G3EDF8MSNY4KpUMvPahDA,1164
-platformdirs/__pycache__/__init__.cpython-311.pyc,,
-platformdirs/__pycache__/__main__.cpython-311.pyc,,
-platformdirs/__pycache__/android.cpython-311.pyc,,
-platformdirs/__pycache__/api.cpython-311.pyc,,
-platformdirs/__pycache__/macos.cpython-311.pyc,,
-platformdirs/__pycache__/unix.cpython-311.pyc,,
-platformdirs/__pycache__/version.cpython-311.pyc,,
-platformdirs/__pycache__/windows.cpython-311.pyc,,
-platformdirs/android.py,sha256=GKizhyS7ESRiU67u8UnBJLm46goau9937EchXWbPBlk,4068
-platformdirs/api.py,sha256=MXKHXOL3eh_-trSok-JUTjAR_zjmmKF3rjREVABjP8s,4910
-platformdirs/macos.py,sha256=-3UXQewbT0yMhMdkzRXfXGAntmLIH7Qt4a9Hlf8I5_Y,2655
-platformdirs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-platformdirs/unix.py,sha256=P-WQjSSieE38DXjMDa1t4XHnKJQ5idEaKT0PyXwm8KQ,6911
-platformdirs/version.py,sha256=qaN-fw_htIgKUVXoAuAEVgKxQu3tZ9qE2eiKkWIS7LA,160
-platformdirs/windows.py,sha256=LOrXLgI0CjQldDo2zhOZYGYZ6g4e_cJOCB_pF9aMRWQ,6596
diff --git a/pkg_resources/_vendor/platformdirs/__init__.py b/pkg_resources/_vendor/platformdirs/__init__.py
deleted file mode 100644
index aef2821b83..0000000000
--- a/pkg_resources/_vendor/platformdirs/__init__.py
+++ /dev/null
@@ -1,342 +0,0 @@
-"""
-Utilities for determining application-specific dirs. See  for details and
-usage.
-"""
-from __future__ import annotations
-
-import os
-import sys
-from pathlib import Path
-
-if sys.version_info >= (3, 8):  # pragma: no cover (py38+)
-    from typing import Literal
-else:  # pragma: no cover (py38+)
-    from ..typing_extensions import Literal
-
-from .api import PlatformDirsABC
-from .version import __version__
-from .version import __version_tuple__ as __version_info__
-
-
-def _set_platform_dir_class() -> type[PlatformDirsABC]:
-    if sys.platform == "win32":
-        from .windows import Windows as Result
-    elif sys.platform == "darwin":
-        from .macos import MacOS as Result
-    else:
-        from .unix import Unix as Result
-
-    if os.getenv("ANDROID_DATA") == "/data" and os.getenv("ANDROID_ROOT") == "/system":
-
-        if os.getenv("SHELL") or os.getenv("PREFIX"):
-            return Result
-
-        from .android import _android_folder
-
-        if _android_folder() is not None:
-            from .android import Android
-
-            return Android  # return to avoid redefinition of result
-
-    return Result
-
-
-PlatformDirs = _set_platform_dir_class()  #: Currently active platform
-AppDirs = PlatformDirs  #: Backwards compatibility with appdirs
-
-
-def user_data_dir(
-    appname: str | None = None,
-    appauthor: str | None | Literal[False] = None,
-    version: str | None = None,
-    roaming: bool = False,
-) -> str:
-    """
-    :param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param roaming: See `roaming `.
-    :returns: data directory tied to the user
-    """
-    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_data_dir
-
-
-def site_data_dir(
-    appname: str | None = None,
-    appauthor: str | None | Literal[False] = None,
-    version: str | None = None,
-    multipath: bool = False,
-) -> str:
-    """
-    :param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param multipath: See `roaming `.
-    :returns: data directory shared by users
-    """
-    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, multipath=multipath).site_data_dir
-
-
-def user_config_dir(
-    appname: str | None = None,
-    appauthor: str | None | Literal[False] = None,
-    version: str | None = None,
-    roaming: bool = False,
-) -> str:
-    """
-    :param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param roaming: See `roaming `.
-    :returns: config directory tied to the user
-    """
-    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_config_dir
-
-
-def site_config_dir(
-    appname: str | None = None,
-    appauthor: str | None | Literal[False] = None,
-    version: str | None = None,
-    multipath: bool = False,
-) -> str:
-    """
-    :param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param multipath: See `roaming `.
-    :returns: config directory shared by the users
-    """
-    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, multipath=multipath).site_config_dir
-
-
-def user_cache_dir(
-    appname: str | None = None,
-    appauthor: str | None | Literal[False] = None,
-    version: str | None = None,
-    opinion: bool = True,
-) -> str:
-    """
-    :param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `roaming `.
-    :returns: cache directory tied to the user
-    """
-    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_cache_dir
-
-
-def user_state_dir(
-    appname: str | None = None,
-    appauthor: str | None | Literal[False] = None,
-    version: str | None = None,
-    roaming: bool = False,
-) -> str:
-    """
-    :param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param roaming: See `roaming `.
-    :returns: state directory tied to the user
-    """
-    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_state_dir
-
-
-def user_log_dir(
-    appname: str | None = None,
-    appauthor: str | None | Literal[False] = None,
-    version: str | None = None,
-    opinion: bool = True,
-) -> str:
-    """
-    :param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `roaming `.
-    :returns: log directory tied to the user
-    """
-    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_log_dir
-
-
-def user_documents_dir() -> str:
-    """
-    :returns: documents directory tied to the user
-    """
-    return PlatformDirs().user_documents_dir
-
-
-def user_runtime_dir(
-    appname: str | None = None,
-    appauthor: str | None | Literal[False] = None,
-    version: str | None = None,
-    opinion: bool = True,
-) -> str:
-    """
-    :param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `opinion `.
-    :returns: runtime directory tied to the user
-    """
-    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_runtime_dir
-
-
-def user_data_path(
-    appname: str | None = None,
-    appauthor: str | None | Literal[False] = None,
-    version: str | None = None,
-    roaming: bool = False,
-) -> Path:
-    """
-    :param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param roaming: See `roaming `.
-    :returns: data path tied to the user
-    """
-    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_data_path
-
-
-def site_data_path(
-    appname: str | None = None,
-    appauthor: str | None | Literal[False] = None,
-    version: str | None = None,
-    multipath: bool = False,
-) -> Path:
-    """
-    :param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param multipath: See `multipath `.
-    :returns: data path shared by users
-    """
-    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, multipath=multipath).site_data_path
-
-
-def user_config_path(
-    appname: str | None = None,
-    appauthor: str | None | Literal[False] = None,
-    version: str | None = None,
-    roaming: bool = False,
-) -> Path:
-    """
-    :param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param roaming: See `roaming `.
-    :returns: config path tied to the user
-    """
-    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_config_path
-
-
-def site_config_path(
-    appname: str | None = None,
-    appauthor: str | None | Literal[False] = None,
-    version: str | None = None,
-    multipath: bool = False,
-) -> Path:
-    """
-    :param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param multipath: See `roaming `.
-    :returns: config path shared by the users
-    """
-    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, multipath=multipath).site_config_path
-
-
-def user_cache_path(
-    appname: str | None = None,
-    appauthor: str | None | Literal[False] = None,
-    version: str | None = None,
-    opinion: bool = True,
-) -> Path:
-    """
-    :param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `roaming `.
-    :returns: cache path tied to the user
-    """
-    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_cache_path
-
-
-def user_state_path(
-    appname: str | None = None,
-    appauthor: str | None | Literal[False] = None,
-    version: str | None = None,
-    roaming: bool = False,
-) -> Path:
-    """
-    :param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param roaming: See `roaming `.
-    :returns: state path tied to the user
-    """
-    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_state_path
-
-
-def user_log_path(
-    appname: str | None = None,
-    appauthor: str | None | Literal[False] = None,
-    version: str | None = None,
-    opinion: bool = True,
-) -> Path:
-    """
-    :param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `roaming `.
-    :returns: log path tied to the user
-    """
-    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_log_path
-
-
-def user_documents_path() -> Path:
-    """
-    :returns: documents path tied to the user
-    """
-    return PlatformDirs().user_documents_path
-
-
-def user_runtime_path(
-    appname: str | None = None,
-    appauthor: str | None | Literal[False] = None,
-    version: str | None = None,
-    opinion: bool = True,
-) -> Path:
-    """
-    :param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `opinion `.
-    :returns: runtime path tied to the user
-    """
-    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_runtime_path
-
-
-__all__ = [
-    "__version__",
-    "__version_info__",
-    "PlatformDirs",
-    "AppDirs",
-    "PlatformDirsABC",
-    "user_data_dir",
-    "user_config_dir",
-    "user_cache_dir",
-    "user_state_dir",
-    "user_log_dir",
-    "user_documents_dir",
-    "user_runtime_dir",
-    "site_data_dir",
-    "site_config_dir",
-    "user_data_path",
-    "user_config_path",
-    "user_cache_path",
-    "user_state_path",
-    "user_log_path",
-    "user_documents_path",
-    "user_runtime_path",
-    "site_data_path",
-    "site_config_path",
-]
diff --git a/pkg_resources/_vendor/platformdirs/__main__.py b/pkg_resources/_vendor/platformdirs/__main__.py
deleted file mode 100644
index 0fc1edd59c..0000000000
--- a/pkg_resources/_vendor/platformdirs/__main__.py
+++ /dev/null
@@ -1,46 +0,0 @@
-from __future__ import annotations
-
-from platformdirs import PlatformDirs, __version__
-
-PROPS = (
-    "user_data_dir",
-    "user_config_dir",
-    "user_cache_dir",
-    "user_state_dir",
-    "user_log_dir",
-    "user_documents_dir",
-    "user_runtime_dir",
-    "site_data_dir",
-    "site_config_dir",
-)
-
-
-def main() -> None:
-    app_name = "MyApp"
-    app_author = "MyCompany"
-
-    print(f"-- platformdirs {__version__} --")
-
-    print("-- app dirs (with optional 'version')")
-    dirs = PlatformDirs(app_name, app_author, version="1.0")
-    for prop in PROPS:
-        print(f"{prop}: {getattr(dirs, prop)}")
-
-    print("\n-- app dirs (without optional 'version')")
-    dirs = PlatformDirs(app_name, app_author)
-    for prop in PROPS:
-        print(f"{prop}: {getattr(dirs, prop)}")
-
-    print("\n-- app dirs (without optional 'appauthor')")
-    dirs = PlatformDirs(app_name)
-    for prop in PROPS:
-        print(f"{prop}: {getattr(dirs, prop)}")
-
-    print("\n-- app dirs (with disabled 'appauthor')")
-    dirs = PlatformDirs(app_name, appauthor=False)
-    for prop in PROPS:
-        print(f"{prop}: {getattr(dirs, prop)}")
-
-
-if __name__ == "__main__":
-    main()
diff --git a/pkg_resources/_vendor/platformdirs/android.py b/pkg_resources/_vendor/platformdirs/android.py
deleted file mode 100644
index eda8093512..0000000000
--- a/pkg_resources/_vendor/platformdirs/android.py
+++ /dev/null
@@ -1,120 +0,0 @@
-from __future__ import annotations
-
-import os
-import re
-import sys
-from functools import lru_cache
-from typing import cast
-
-from .api import PlatformDirsABC
-
-
-class Android(PlatformDirsABC):
-    """
-    Follows the guidance `from here `_. Makes use of the
-    `appname ` and
-    `version `.
-    """
-
-    @property
-    def user_data_dir(self) -> str:
-        """:return: data directory tied to the user, e.g. ``/data/user///files/``"""
-        return self._append_app_name_and_version(cast(str, _android_folder()), "files")
-
-    @property
-    def site_data_dir(self) -> str:
-        """:return: data directory shared by users, same as `user_data_dir`"""
-        return self.user_data_dir
-
-    @property
-    def user_config_dir(self) -> str:
-        """
-        :return: config directory tied to the user, e.g. ``/data/user///shared_prefs/``
-        """
-        return self._append_app_name_and_version(cast(str, _android_folder()), "shared_prefs")
-
-    @property
-    def site_config_dir(self) -> str:
-        """:return: config directory shared by the users, same as `user_config_dir`"""
-        return self.user_config_dir
-
-    @property
-    def user_cache_dir(self) -> str:
-        """:return: cache directory tied to the user, e.g. e.g. ``/data/user///cache/``"""
-        return self._append_app_name_and_version(cast(str, _android_folder()), "cache")
-
-    @property
-    def user_state_dir(self) -> str:
-        """:return: state directory tied to the user, same as `user_data_dir`"""
-        return self.user_data_dir
-
-    @property
-    def user_log_dir(self) -> str:
-        """
-        :return: log directory tied to the user, same as `user_cache_dir` if not opinionated else ``log`` in it,
-          e.g. ``/data/user///cache//log``
-        """
-        path = self.user_cache_dir
-        if self.opinion:
-            path = os.path.join(path, "log")
-        return path
-
-    @property
-    def user_documents_dir(self) -> str:
-        """
-        :return: documents directory tied to the user e.g. ``/storage/emulated/0/Documents``
-        """
-        return _android_documents_folder()
-
-    @property
-    def user_runtime_dir(self) -> str:
-        """
-        :return: runtime directory tied to the user, same as `user_cache_dir` if not opinionated else ``tmp`` in it,
-          e.g. ``/data/user///cache//tmp``
-        """
-        path = self.user_cache_dir
-        if self.opinion:
-            path = os.path.join(path, "tmp")
-        return path
-
-
-@lru_cache(maxsize=1)
-def _android_folder() -> str | None:
-    """:return: base folder for the Android OS or None if cannot be found"""
-    try:
-        # First try to get path to android app via pyjnius
-        from jnius import autoclass
-
-        Context = autoclass("android.content.Context")  # noqa: N806
-        result: str | None = Context.getFilesDir().getParentFile().getAbsolutePath()
-    except Exception:
-        # if fails find an android folder looking path on the sys.path
-        pattern = re.compile(r"/data/(data|user/\d+)/(.+)/files")
-        for path in sys.path:
-            if pattern.match(path):
-                result = path.split("/files")[0]
-                break
-        else:
-            result = None
-    return result
-
-
-@lru_cache(maxsize=1)
-def _android_documents_folder() -> str:
-    """:return: documents folder for the Android OS"""
-    # Get directories with pyjnius
-    try:
-        from jnius import autoclass
-
-        Context = autoclass("android.content.Context")  # noqa: N806
-        Environment = autoclass("android.os.Environment")  # noqa: N806
-        documents_dir: str = Context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath()
-    except Exception:
-        documents_dir = "/storage/emulated/0/Documents"
-
-    return documents_dir
-
-
-__all__ = [
-    "Android",
-]
diff --git a/pkg_resources/_vendor/platformdirs/api.py b/pkg_resources/_vendor/platformdirs/api.py
deleted file mode 100644
index 6f6e2c2c69..0000000000
--- a/pkg_resources/_vendor/platformdirs/api.py
+++ /dev/null
@@ -1,156 +0,0 @@
-from __future__ import annotations
-
-import os
-import sys
-from abc import ABC, abstractmethod
-from pathlib import Path
-
-if sys.version_info >= (3, 8):  # pragma: no branch
-    from typing import Literal  # pragma: no cover
-
-
-class PlatformDirsABC(ABC):
-    """
-    Abstract base class for platform directories.
-    """
-
-    def __init__(
-        self,
-        appname: str | None = None,
-        appauthor: str | None | Literal[False] = None,
-        version: str | None = None,
-        roaming: bool = False,
-        multipath: bool = False,
-        opinion: bool = True,
-    ):
-        """
-        Create a new platform directory.
-
-        :param appname: See `appname`.
-        :param appauthor: See `appauthor`.
-        :param version: See `version`.
-        :param roaming: See `roaming`.
-        :param multipath: See `multipath`.
-        :param opinion: See `opinion`.
-        """
-        self.appname = appname  #: The name of application.
-        self.appauthor = appauthor
-        """
-        The name of the app author or distributing body for this application. Typically, it is the owning company name.
-        Defaults to `appname`. You may pass ``False`` to disable it.
-        """
-        self.version = version
-        """
-        An optional version path element to append to the path. You might want to use this if you want multiple versions
-        of your app to be able to run independently. If used, this would typically be ``.``.
-        """
-        self.roaming = roaming
-        """
-        Whether to use the roaming appdata directory on Windows. That means that for users on a Windows network setup
-        for roaming profiles, this user data will be synced on login (see
-        `here `_).
-        """
-        self.multipath = multipath
-        """
-        An optional parameter only applicable to Unix/Linux which indicates that the entire list of data dirs should be
-        returned. By default, the first item would only be returned.
-        """
-        self.opinion = opinion  #: A flag to indicating to use opinionated values.
-
-    def _append_app_name_and_version(self, *base: str) -> str:
-        params = list(base[1:])
-        if self.appname:
-            params.append(self.appname)
-            if self.version:
-                params.append(self.version)
-        return os.path.join(base[0], *params)
-
-    @property
-    @abstractmethod
-    def user_data_dir(self) -> str:
-        """:return: data directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def site_data_dir(self) -> str:
-        """:return: data directory shared by users"""
-
-    @property
-    @abstractmethod
-    def user_config_dir(self) -> str:
-        """:return: config directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def site_config_dir(self) -> str:
-        """:return: config directory shared by the users"""
-
-    @property
-    @abstractmethod
-    def user_cache_dir(self) -> str:
-        """:return: cache directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def user_state_dir(self) -> str:
-        """:return: state directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def user_log_dir(self) -> str:
-        """:return: log directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def user_documents_dir(self) -> str:
-        """:return: documents directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def user_runtime_dir(self) -> str:
-        """:return: runtime directory tied to the user"""
-
-    @property
-    def user_data_path(self) -> Path:
-        """:return: data path tied to the user"""
-        return Path(self.user_data_dir)
-
-    @property
-    def site_data_path(self) -> Path:
-        """:return: data path shared by users"""
-        return Path(self.site_data_dir)
-
-    @property
-    def user_config_path(self) -> Path:
-        """:return: config path tied to the user"""
-        return Path(self.user_config_dir)
-
-    @property
-    def site_config_path(self) -> Path:
-        """:return: config path shared by the users"""
-        return Path(self.site_config_dir)
-
-    @property
-    def user_cache_path(self) -> Path:
-        """:return: cache path tied to the user"""
-        return Path(self.user_cache_dir)
-
-    @property
-    def user_state_path(self) -> Path:
-        """:return: state path tied to the user"""
-        return Path(self.user_state_dir)
-
-    @property
-    def user_log_path(self) -> Path:
-        """:return: log path tied to the user"""
-        return Path(self.user_log_dir)
-
-    @property
-    def user_documents_path(self) -> Path:
-        """:return: documents path tied to the user"""
-        return Path(self.user_documents_dir)
-
-    @property
-    def user_runtime_path(self) -> Path:
-        """:return: runtime path tied to the user"""
-        return Path(self.user_runtime_dir)
diff --git a/pkg_resources/_vendor/platformdirs/macos.py b/pkg_resources/_vendor/platformdirs/macos.py
deleted file mode 100644
index a01337c776..0000000000
--- a/pkg_resources/_vendor/platformdirs/macos.py
+++ /dev/null
@@ -1,64 +0,0 @@
-from __future__ import annotations
-
-import os
-
-from .api import PlatformDirsABC
-
-
-class MacOS(PlatformDirsABC):
-    """
-    Platform directories for the macOS operating system. Follows the guidance from `Apple documentation
-    `_.
-    Makes use of the `appname ` and
-    `version `.
-    """
-
-    @property
-    def user_data_dir(self) -> str:
-        """:return: data directory tied to the user, e.g. ``~/Library/Application Support/$appname/$version``"""
-        return self._append_app_name_and_version(os.path.expanduser("~/Library/Application Support/"))
-
-    @property
-    def site_data_dir(self) -> str:
-        """:return: data directory shared by users, e.g. ``/Library/Application Support/$appname/$version``"""
-        return self._append_app_name_and_version("/Library/Application Support")
-
-    @property
-    def user_config_dir(self) -> str:
-        """:return: config directory tied to the user, e.g. ``~/Library/Preferences/$appname/$version``"""
-        return self._append_app_name_and_version(os.path.expanduser("~/Library/Preferences/"))
-
-    @property
-    def site_config_dir(self) -> str:
-        """:return: config directory shared by the users, e.g. ``/Library/Preferences/$appname``"""
-        return self._append_app_name_and_version("/Library/Preferences")
-
-    @property
-    def user_cache_dir(self) -> str:
-        """:return: cache directory tied to the user, e.g. ``~/Library/Caches/$appname/$version``"""
-        return self._append_app_name_and_version(os.path.expanduser("~/Library/Caches"))
-
-    @property
-    def user_state_dir(self) -> str:
-        """:return: state directory tied to the user, same as `user_data_dir`"""
-        return self.user_data_dir
-
-    @property
-    def user_log_dir(self) -> str:
-        """:return: log directory tied to the user, e.g. ``~/Library/Logs/$appname/$version``"""
-        return self._append_app_name_and_version(os.path.expanduser("~/Library/Logs"))
-
-    @property
-    def user_documents_dir(self) -> str:
-        """:return: documents directory tied to the user, e.g. ``~/Documents``"""
-        return os.path.expanduser("~/Documents")
-
-    @property
-    def user_runtime_dir(self) -> str:
-        """:return: runtime directory tied to the user, e.g. ``~/Library/Caches/TemporaryItems/$appname/$version``"""
-        return self._append_app_name_and_version(os.path.expanduser("~/Library/Caches/TemporaryItems"))
-
-
-__all__ = [
-    "MacOS",
-]
diff --git a/pkg_resources/_vendor/platformdirs/py.typed b/pkg_resources/_vendor/platformdirs/py.typed
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/pkg_resources/_vendor/platformdirs/unix.py b/pkg_resources/_vendor/platformdirs/unix.py
deleted file mode 100644
index 9aca5a0305..0000000000
--- a/pkg_resources/_vendor/platformdirs/unix.py
+++ /dev/null
@@ -1,181 +0,0 @@
-from __future__ import annotations
-
-import os
-import sys
-from configparser import ConfigParser
-from pathlib import Path
-
-from .api import PlatformDirsABC
-
-if sys.platform.startswith("linux"):  # pragma: no branch # no op check, only to please the type checker
-    from os import getuid
-else:
-
-    def getuid() -> int:
-        raise RuntimeError("should only be used on Linux")
-
-
-class Unix(PlatformDirsABC):
-    """
-    On Unix/Linux, we follow the
-    `XDG Basedir Spec `_. The spec allows
-    overriding directories with environment variables. The examples show are the default values, alongside the name of
-    the environment variable that overrides them. Makes use of the
-    `appname `,
-    `version `,
-    `multipath `,
-    `opinion `.
-    """
-
-    @property
-    def user_data_dir(self) -> str:
-        """
-        :return: data directory tied to the user, e.g. ``~/.local/share/$appname/$version`` or
-         ``$XDG_DATA_HOME/$appname/$version``
-        """
-        path = os.environ.get("XDG_DATA_HOME", "")
-        if not path.strip():
-            path = os.path.expanduser("~/.local/share")
-        return self._append_app_name_and_version(path)
-
-    @property
-    def site_data_dir(self) -> str:
-        """
-        :return: data directories shared by users (if `multipath ` is
-         enabled and ``XDG_DATA_DIR`` is set and a multi path the response is also a multi path separated by the OS
-         path separator), e.g. ``/usr/local/share/$appname/$version`` or ``/usr/share/$appname/$version``
-        """
-        # XDG default for $XDG_DATA_DIRS; only first, if multipath is False
-        path = os.environ.get("XDG_DATA_DIRS", "")
-        if not path.strip():
-            path = f"/usr/local/share{os.pathsep}/usr/share"
-        return self._with_multi_path(path)
-
-    def _with_multi_path(self, path: str) -> str:
-        path_list = path.split(os.pathsep)
-        if not self.multipath:
-            path_list = path_list[0:1]
-        path_list = [self._append_app_name_and_version(os.path.expanduser(p)) for p in path_list]
-        return os.pathsep.join(path_list)
-
-    @property
-    def user_config_dir(self) -> str:
-        """
-        :return: config directory tied to the user, e.g. ``~/.config/$appname/$version`` or
-         ``$XDG_CONFIG_HOME/$appname/$version``
-        """
-        path = os.environ.get("XDG_CONFIG_HOME", "")
-        if not path.strip():
-            path = os.path.expanduser("~/.config")
-        return self._append_app_name_and_version(path)
-
-    @property
-    def site_config_dir(self) -> str:
-        """
-        :return: config directories shared by users (if `multipath `
-         is enabled and ``XDG_DATA_DIR`` is set and a multi path the response is also a multi path separated by the OS
-         path separator), e.g. ``/etc/xdg/$appname/$version``
-        """
-        # XDG default for $XDG_CONFIG_DIRS only first, if multipath is False
-        path = os.environ.get("XDG_CONFIG_DIRS", "")
-        if not path.strip():
-            path = "/etc/xdg"
-        return self._with_multi_path(path)
-
-    @property
-    def user_cache_dir(self) -> str:
-        """
-        :return: cache directory tied to the user, e.g. ``~/.cache/$appname/$version`` or
-         ``~/$XDG_CACHE_HOME/$appname/$version``
-        """
-        path = os.environ.get("XDG_CACHE_HOME", "")
-        if not path.strip():
-            path = os.path.expanduser("~/.cache")
-        return self._append_app_name_and_version(path)
-
-    @property
-    def user_state_dir(self) -> str:
-        """
-        :return: state directory tied to the user, e.g. ``~/.local/state/$appname/$version`` or
-         ``$XDG_STATE_HOME/$appname/$version``
-        """
-        path = os.environ.get("XDG_STATE_HOME", "")
-        if not path.strip():
-            path = os.path.expanduser("~/.local/state")
-        return self._append_app_name_and_version(path)
-
-    @property
-    def user_log_dir(self) -> str:
-        """
-        :return: log directory tied to the user, same as `user_state_dir` if not opinionated else ``log`` in it
-        """
-        path = self.user_state_dir
-        if self.opinion:
-            path = os.path.join(path, "log")
-        return path
-
-    @property
-    def user_documents_dir(self) -> str:
-        """
-        :return: documents directory tied to the user, e.g. ``~/Documents``
-        """
-        documents_dir = _get_user_dirs_folder("XDG_DOCUMENTS_DIR")
-        if documents_dir is None:
-            documents_dir = os.environ.get("XDG_DOCUMENTS_DIR", "").strip()
-            if not documents_dir:
-                documents_dir = os.path.expanduser("~/Documents")
-
-        return documents_dir
-
-    @property
-    def user_runtime_dir(self) -> str:
-        """
-        :return: runtime directory tied to the user, e.g. ``/run/user/$(id -u)/$appname/$version`` or
-         ``$XDG_RUNTIME_DIR/$appname/$version``
-        """
-        path = os.environ.get("XDG_RUNTIME_DIR", "")
-        if not path.strip():
-            path = f"/run/user/{getuid()}"
-        return self._append_app_name_and_version(path)
-
-    @property
-    def site_data_path(self) -> Path:
-        """:return: data path shared by users. Only return first item, even if ``multipath`` is set to ``True``"""
-        return self._first_item_as_path_if_multipath(self.site_data_dir)
-
-    @property
-    def site_config_path(self) -> Path:
-        """:return: config path shared by the users. Only return first item, even if ``multipath`` is set to ``True``"""
-        return self._first_item_as_path_if_multipath(self.site_config_dir)
-
-    def _first_item_as_path_if_multipath(self, directory: str) -> Path:
-        if self.multipath:
-            # If multipath is True, the first path is returned.
-            directory = directory.split(os.pathsep)[0]
-        return Path(directory)
-
-
-def _get_user_dirs_folder(key: str) -> str | None:
-    """Return directory from user-dirs.dirs config file. See https://freedesktop.org/wiki/Software/xdg-user-dirs/"""
-    user_dirs_config_path = os.path.join(Unix().user_config_dir, "user-dirs.dirs")
-    if os.path.exists(user_dirs_config_path):
-        parser = ConfigParser()
-
-        with open(user_dirs_config_path) as stream:
-            # Add fake section header, so ConfigParser doesn't complain
-            parser.read_string(f"[top]\n{stream.read()}")
-
-        if key not in parser["top"]:
-            return None
-
-        path = parser["top"][key].strip('"')
-        # Handle relative home paths
-        path = path.replace("$HOME", os.path.expanduser("~"))
-        return path
-
-    return None
-
-
-__all__ = [
-    "Unix",
-]
diff --git a/pkg_resources/_vendor/platformdirs/version.py b/pkg_resources/_vendor/platformdirs/version.py
deleted file mode 100644
index 9f6eb98e8f..0000000000
--- a/pkg_resources/_vendor/platformdirs/version.py
+++ /dev/null
@@ -1,4 +0,0 @@
-# file generated by setuptools_scm
-# don't change, don't track in version control
-__version__ = version = '2.6.2'
-__version_tuple__ = version_tuple = (2, 6, 2)
diff --git a/pkg_resources/_vendor/platformdirs/windows.py b/pkg_resources/_vendor/platformdirs/windows.py
deleted file mode 100644
index d5c27b3414..0000000000
--- a/pkg_resources/_vendor/platformdirs/windows.py
+++ /dev/null
@@ -1,184 +0,0 @@
-from __future__ import annotations
-
-import ctypes
-import os
-import sys
-from functools import lru_cache
-from typing import Callable
-
-from .api import PlatformDirsABC
-
-
-class Windows(PlatformDirsABC):
-    """`MSDN on where to store app data files
-    `_.
-    Makes use of the
-    `appname `,
-    `appauthor `,
-    `version `,
-    `roaming `,
-    `opinion `."""
-
-    @property
-    def user_data_dir(self) -> str:
-        """
-        :return: data directory tied to the user, e.g.
-         ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname`` (not roaming) or
-         ``%USERPROFILE%\\AppData\\Roaming\\$appauthor\\$appname`` (roaming)
-        """
-        const = "CSIDL_APPDATA" if self.roaming else "CSIDL_LOCAL_APPDATA"
-        path = os.path.normpath(get_win_folder(const))
-        return self._append_parts(path)
-
-    def _append_parts(self, path: str, *, opinion_value: str | None = None) -> str:
-        params = []
-        if self.appname:
-            if self.appauthor is not False:
-                author = self.appauthor or self.appname
-                params.append(author)
-            params.append(self.appname)
-            if opinion_value is not None and self.opinion:
-                params.append(opinion_value)
-            if self.version:
-                params.append(self.version)
-        return os.path.join(path, *params)
-
-    @property
-    def site_data_dir(self) -> str:
-        """:return: data directory shared by users, e.g. ``C:\\ProgramData\\$appauthor\\$appname``"""
-        path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
-        return self._append_parts(path)
-
-    @property
-    def user_config_dir(self) -> str:
-        """:return: config directory tied to the user, same as `user_data_dir`"""
-        return self.user_data_dir
-
-    @property
-    def site_config_dir(self) -> str:
-        """:return: config directory shared by the users, same as `site_data_dir`"""
-        return self.site_data_dir
-
-    @property
-    def user_cache_dir(self) -> str:
-        """
-        :return: cache directory tied to the user (if opinionated with ``Cache`` folder within ``$appname``) e.g.
-         ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname\\Cache\\$version``
-        """
-        path = os.path.normpath(get_win_folder("CSIDL_LOCAL_APPDATA"))
-        return self._append_parts(path, opinion_value="Cache")
-
-    @property
-    def user_state_dir(self) -> str:
-        """:return: state directory tied to the user, same as `user_data_dir`"""
-        return self.user_data_dir
-
-    @property
-    def user_log_dir(self) -> str:
-        """
-        :return: log directory tied to the user, same as `user_data_dir` if not opinionated else ``Logs`` in it
-        """
-        path = self.user_data_dir
-        if self.opinion:
-            path = os.path.join(path, "Logs")
-        return path
-
-    @property
-    def user_documents_dir(self) -> str:
-        """
-        :return: documents directory tied to the user e.g. ``%USERPROFILE%\\Documents``
-        """
-        return os.path.normpath(get_win_folder("CSIDL_PERSONAL"))
-
-    @property
-    def user_runtime_dir(self) -> str:
-        """
-        :return: runtime directory tied to the user, e.g.
-         ``%USERPROFILE%\\AppData\\Local\\Temp\\$appauthor\\$appname``
-        """
-        path = os.path.normpath(os.path.join(get_win_folder("CSIDL_LOCAL_APPDATA"), "Temp"))
-        return self._append_parts(path)
-
-
-def get_win_folder_from_env_vars(csidl_name: str) -> str:
-    """Get folder from environment variables."""
-    if csidl_name == "CSIDL_PERSONAL":  # does not have an environment name
-        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Documents")
-
-    env_var_name = {
-        "CSIDL_APPDATA": "APPDATA",
-        "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE",
-        "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA",
-    }.get(csidl_name)
-    if env_var_name is None:
-        raise ValueError(f"Unknown CSIDL name: {csidl_name}")
-    result = os.environ.get(env_var_name)
-    if result is None:
-        raise ValueError(f"Unset environment variable: {env_var_name}")
-    return result
-
-
-def get_win_folder_from_registry(csidl_name: str) -> str:
-    """Get folder from the registry.
-
-    This is a fallback technique at best. I'm not sure if using the
-    registry for this guarantees us the correct answer for all CSIDL_*
-    names.
-    """
-    shell_folder_name = {
-        "CSIDL_APPDATA": "AppData",
-        "CSIDL_COMMON_APPDATA": "Common AppData",
-        "CSIDL_LOCAL_APPDATA": "Local AppData",
-        "CSIDL_PERSONAL": "Personal",
-    }.get(csidl_name)
-    if shell_folder_name is None:
-        raise ValueError(f"Unknown CSIDL name: {csidl_name}")
-    if sys.platform != "win32":  # only needed for mypy type checker to know that this code runs only on Windows
-        raise NotImplementedError
-    import winreg
-
-    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
-    directory, _ = winreg.QueryValueEx(key, shell_folder_name)
-    return str(directory)
-
-
-def get_win_folder_via_ctypes(csidl_name: str) -> str:
-    """Get folder with ctypes."""
-    csidl_const = {
-        "CSIDL_APPDATA": 26,
-        "CSIDL_COMMON_APPDATA": 35,
-        "CSIDL_LOCAL_APPDATA": 28,
-        "CSIDL_PERSONAL": 5,
-    }.get(csidl_name)
-    if csidl_const is None:
-        raise ValueError(f"Unknown CSIDL name: {csidl_name}")
-
-    buf = ctypes.create_unicode_buffer(1024)
-    windll = getattr(ctypes, "windll")  # noqa: B009 # using getattr to avoid false positive with mypy type checker
-    windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
-
-    # Downgrade to short path name if it has highbit chars.
-    if any(ord(c) > 255 for c in buf):
-        buf2 = ctypes.create_unicode_buffer(1024)
-        if windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
-            buf = buf2
-
-    return buf.value
-
-
-def _pick_get_win_folder() -> Callable[[str], str]:
-    if hasattr(ctypes, "windll"):
-        return get_win_folder_via_ctypes
-    try:
-        import winreg  # noqa: F401
-    except ImportError:
-        return get_win_folder_from_env_vars
-    else:
-        return get_win_folder_from_registry
-
-
-get_win_folder = lru_cache(maxsize=None)(_pick_get_win_folder())
-
-__all__ = [
-    "Windows",
-]
diff --git a/pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/INSTALLER b/pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/INSTALLER
deleted file mode 100644
index a1b589e38a..0000000000
--- a/pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/INSTALLER
+++ /dev/null
@@ -1 +0,0 @@
-pip
diff --git a/pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/LICENSE b/pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/LICENSE
deleted file mode 100644
index 1df6b3b8de..0000000000
--- a/pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/LICENSE
+++ /dev/null
@@ -1,254 +0,0 @@
-A. HISTORY OF THE SOFTWARE
-==========================
-
-Python was created in the early 1990s by Guido van Rossum at Stichting
-Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
-as a successor of a language called ABC.  Guido remains Python's
-principal author, although it includes many contributions from others.
-
-In 1995, Guido continued his work on Python at the Corporation for
-National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
-in Reston, Virginia where he released several versions of the
-software.
-
-In May 2000, Guido and the Python core development team moved to
-BeOpen.com to form the BeOpen PythonLabs team.  In October of the same
-year, the PythonLabs team moved to Digital Creations, which became
-Zope Corporation.  In 2001, the Python Software Foundation (PSF, see
-https://www.python.org/psf/) was formed, a non-profit organization
-created specifically to own Python-related Intellectual Property.
-Zope Corporation was a sponsoring member of the PSF.
-
-All Python releases are Open Source (see http://www.opensource.org for
-the Open Source Definition).  Historically, most, but not all, Python
-releases have also been GPL-compatible; the table below summarizes
-the various releases.
-
-    Release         Derived     Year        Owner       GPL-
-                    from                                compatible? (1)
-
-    0.9.0 thru 1.2              1991-1995   CWI         yes
-    1.3 thru 1.5.2  1.2         1995-1999   CNRI        yes
-    1.6             1.5.2       2000        CNRI        no
-    2.0             1.6         2000        BeOpen.com  no
-    1.6.1           1.6         2001        CNRI        yes (2)
-    2.1             2.0+1.6.1   2001        PSF         no
-    2.0.1           2.0+1.6.1   2001        PSF         yes
-    2.1.1           2.1+2.0.1   2001        PSF         yes
-    2.1.2           2.1.1       2002        PSF         yes
-    2.1.3           2.1.2       2002        PSF         yes
-    2.2 and above   2.1.1       2001-now    PSF         yes
-
-Footnotes:
-
-(1) GPL-compatible doesn't mean that we're distributing Python under
-    the GPL.  All Python licenses, unlike the GPL, let you distribute
-    a modified version without making your changes open source.  The
-    GPL-compatible licenses make it possible to combine Python with
-    other software that is released under the GPL; the others don't.
-
-(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
-    because its license has a choice of law clause.  According to
-    CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
-    is "not incompatible" with the GPL.
-
-Thanks to the many outside volunteers who have worked under Guido's
-direction to make these releases possible.
-
-
-B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
-===============================================================
-
-PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
---------------------------------------------
-
-1. This LICENSE AGREEMENT is between the Python Software Foundation
-("PSF"), and the Individual or Organization ("Licensee") accessing and
-otherwise using this software ("Python") in source or binary form and
-its associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement, PSF hereby
-grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
-analyze, test, perform and/or display publicly, prepare derivative works,
-distribute, and otherwise use Python alone or in any derivative version,
-provided, however, that PSF's License Agreement and PSF's notice of copyright,
-i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
-2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Python Software Foundation;
-All Rights Reserved" are retained in Python alone or in any derivative version
-prepared by Licensee.
-
-3. In the event Licensee prepares a derivative work that is based on
-or incorporates Python or any part thereof, and wants to make
-the derivative work available to others as provided herein, then
-Licensee hereby agrees to include in any such work a brief summary of
-the changes made to Python.
-
-4. PSF is making Python available to Licensee on an "AS IS"
-basis.  PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
-IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
-DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
-INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
-FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
-A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
-OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-7. Nothing in this License Agreement shall be deemed to create any
-relationship of agency, partnership, or joint venture between PSF and
-Licensee.  This License Agreement does not grant permission to use PSF
-trademarks or trade name in a trademark sense to endorse or promote
-products or services of Licensee, or any third party.
-
-8. By copying, installing or otherwise using Python, Licensee
-agrees to be bound by the terms and conditions of this License
-Agreement.
-
-
-BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
--------------------------------------------
-
-BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
-
-1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
-office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
-Individual or Organization ("Licensee") accessing and otherwise using
-this software in source or binary form and its associated
-documentation ("the Software").
-
-2. Subject to the terms and conditions of this BeOpen Python License
-Agreement, BeOpen hereby grants Licensee a non-exclusive,
-royalty-free, world-wide license to reproduce, analyze, test, perform
-and/or display publicly, prepare derivative works, distribute, and
-otherwise use the Software alone or in any derivative version,
-provided, however, that the BeOpen Python License is retained in the
-Software, alone or in any derivative version prepared by Licensee.
-
-3. BeOpen is making the Software available to Licensee on an "AS IS"
-basis.  BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
-IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
-DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
-INFRINGE ANY THIRD PARTY RIGHTS.
-
-4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
-SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
-AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
-DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-5. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-6. This License Agreement shall be governed by and interpreted in all
-respects by the law of the State of California, excluding conflict of
-law provisions.  Nothing in this License Agreement shall be deemed to
-create any relationship of agency, partnership, or joint venture
-between BeOpen and Licensee.  This License Agreement does not grant
-permission to use BeOpen trademarks or trade names in a trademark
-sense to endorse or promote products or services of Licensee, or any
-third party.  As an exception, the "BeOpen Python" logos available at
-http://www.pythonlabs.com/logos.html may be used according to the
-permissions granted on that web page.
-
-7. By copying, installing or otherwise using the software, Licensee
-agrees to be bound by the terms and conditions of this License
-Agreement.
-
-
-CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
----------------------------------------
-
-1. This LICENSE AGREEMENT is between the Corporation for National
-Research Initiatives, having an office at 1895 Preston White Drive,
-Reston, VA 20191 ("CNRI"), and the Individual or Organization
-("Licensee") accessing and otherwise using Python 1.6.1 software in
-source or binary form and its associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement, CNRI
-hereby grants Licensee a nonexclusive, royalty-free, world-wide
-license to reproduce, analyze, test, perform and/or display publicly,
-prepare derivative works, distribute, and otherwise use Python 1.6.1
-alone or in any derivative version, provided, however, that CNRI's
-License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
-1995-2001 Corporation for National Research Initiatives; All Rights
-Reserved" are retained in Python 1.6.1 alone or in any derivative
-version prepared by Licensee.  Alternately, in lieu of CNRI's License
-Agreement, Licensee may substitute the following text (omitting the
-quotes): "Python 1.6.1 is made available subject to the terms and
-conditions in CNRI's License Agreement.  This Agreement together with
-Python 1.6.1 may be located on the internet using the following
-unique, persistent identifier (known as a handle): 1895.22/1013.  This
-Agreement may also be obtained from a proxy server on the internet
-using the following URL: http://hdl.handle.net/1895.22/1013".
-
-3. In the event Licensee prepares a derivative work that is based on
-or incorporates Python 1.6.1 or any part thereof, and wants to make
-the derivative work available to others as provided herein, then
-Licensee hereby agrees to include in any such work a brief summary of
-the changes made to Python 1.6.1.
-
-4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
-basis.  CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
-IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
-DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
-INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
-1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
-A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
-OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-7. This License Agreement shall be governed by the federal
-intellectual property law of the United States, including without
-limitation the federal copyright law, and, to the extent such
-U.S. federal law does not apply, by the law of the Commonwealth of
-Virginia, excluding Virginia's conflict of law provisions.
-Notwithstanding the foregoing, with regard to derivative works based
-on Python 1.6.1 that incorporate non-separable material that was
-previously distributed under the GNU General Public License (GPL), the
-law of the Commonwealth of Virginia shall govern this License
-Agreement only as to issues arising under or with respect to
-Paragraphs 4, 5, and 7 of this License Agreement.  Nothing in this
-License Agreement shall be deemed to create any relationship of
-agency, partnership, or joint venture between CNRI and Licensee.  This
-License Agreement does not grant permission to use CNRI trademarks or
-trade name in a trademark sense to endorse or promote products or
-services of Licensee, or any third party.
-
-8. By clicking on the "ACCEPT" button where indicated, or by copying,
-installing or otherwise using Python 1.6.1, Licensee agrees to be
-bound by the terms and conditions of this License Agreement.
-
-        ACCEPT
-
-
-CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
---------------------------------------------------
-
-Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
-The Netherlands.  All rights reserved.
-
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose and without fee is hereby granted,
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in
-supporting documentation, and that the name of Stichting Mathematisch
-Centrum or CWI not be used in advertising or publicity pertaining to
-distribution of the software without specific, written prior
-permission.
-
-STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
-THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
-FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
-OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/METADATA b/pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/METADATA
deleted file mode 100644
index 1ed963a12c..0000000000
--- a/pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/METADATA
+++ /dev/null
@@ -1,189 +0,0 @@
-Metadata-Version: 2.1
-Name: typing_extensions
-Version: 4.4.0
-Summary: Backported and Experimental Type Hints for Python 3.7+
-Keywords: annotations,backport,checker,checking,function,hinting,hints,type,typechecking,typehinting,typehints,typing
-Author-email: "Guido van Rossum, Jukka Lehtosalo, Łukasz Langa, Michael Lee" 
-Requires-Python: >=3.7
-Description-Content-Type: text/markdown
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Environment :: Console
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: Python Software Foundation License
-Classifier: Operating System :: OS Independent
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3 :: Only
-Classifier: Programming Language :: Python :: 3.7
-Classifier: Programming Language :: Python :: 3.8
-Classifier: Programming Language :: Python :: 3.9
-Classifier: Programming Language :: Python :: 3.10
-Classifier: Topic :: Software Development
-Project-URL: Bug Tracker, https://github.com/python/typing_extensions/issues
-Project-URL: Changes, https://github.com/python/typing_extensions/blob/main/CHANGELOG.md
-Project-URL: Documentation, https://typing.readthedocs.io/
-Project-URL: Home, https://github.com/python/typing_extensions
-Project-URL: Q & A, https://github.com/python/typing/discussions
-Project-URL: Repository, https://github.com/python/typing_extensions
-
-# Typing Extensions
-
-[![Chat at https://gitter.im/python/typing](https://badges.gitter.im/python/typing.svg)](https://gitter.im/python/typing)
-
-## Overview
-
-The `typing_extensions` module serves two related purposes:
-
-- Enable use of new type system features on older Python versions. For example,
-  `typing.TypeGuard` is new in Python 3.10, but `typing_extensions` allows
-  users on previous Python versions to use it too.
-- Enable experimentation with new type system PEPs before they are accepted and
-  added to the `typing` module.
-
-New features may be added to `typing_extensions` as soon as they are specified
-in a PEP that has been added to the [python/peps](https://github.com/python/peps)
-repository. If the PEP is accepted, the feature will then be added to `typing`
-for the next CPython release. No typing PEP has been rejected so far, so we
-haven't yet figured out how to deal with that possibility.
-
-Starting with version 4.0.0, `typing_extensions` uses
-[Semantic Versioning](https://semver.org/). The
-major version is incremented for all backwards-incompatible changes.
-Therefore, it's safe to depend
-on `typing_extensions` like this: `typing_extensions >=x.y, <(x+1)`,
-where `x.y` is the first version that includes all features you need.
-
-`typing_extensions` supports Python versions 3.7 and higher. In the future,
-support for older Python versions will be dropped some time after that version
-reaches end of life.
-
-## Included items
-
-This module currently contains the following:
-
-- Experimental features
-
-  - `override` (see PEP 698)
-  - The `default=` argument to `TypeVar`, `ParamSpec`, and `TypeVarTuple` (see PEP 696)
-  - The `infer_variance=` argument to `TypeVar` (see PEP 695)
-
-- In `typing` since Python 3.11
-
-  - `assert_never`
-  - `assert_type`
-  - `clear_overloads`
-  - `@dataclass_transform()` (see PEP 681)
-  - `get_overloads`
-  - `LiteralString` (see PEP 675)
-  - `Never`
-  - `NotRequired` (see PEP 655)
-  - `reveal_type`
-  - `Required` (see PEP 655)
-  - `Self` (see PEP 673)
-  - `TypeVarTuple` (see PEP 646; the `typing_extensions` version supports the `default=` argument from PEP 696)
-  - `Unpack` (see PEP 646)
-
-- In `typing` since Python 3.10
-
-  - `Concatenate` (see PEP 612)
-  - `ParamSpec` (see PEP 612; the `typing_extensions` version supports the `default=` argument from PEP 696)
-  - `ParamSpecArgs` (see PEP 612)
-  - `ParamSpecKwargs` (see PEP 612)
-  - `TypeAlias` (see PEP 613)
-  - `TypeGuard` (see PEP 647)
-  - `is_typeddict`
-
-- In `typing` since Python 3.9
-
-  - `Annotated` (see PEP 593)
-
-- In `typing` since Python 3.8
-
-  - `final` (see PEP 591)
-  - `Final` (see PEP 591)
-  - `Literal` (see PEP 586)
-  - `Protocol` (see PEP 544)
-  - `runtime_checkable` (see PEP 544)
-  - `TypedDict` (see PEP 589)
-  - `get_origin` (`typing_extensions` provides this function only in Python 3.7+)
-  - `get_args` (`typing_extensions` provides this function only in Python 3.7+)
-
-- In `typing` since Python 3.7
-
-  - `OrderedDict`
-
-- In `typing` since Python 3.5 or 3.6 (see [the typing documentation](https://docs.python.org/3.10/library/typing.html) for details)
-
-  - `AsyncContextManager`
-  - `AsyncGenerator`
-  - `AsyncIterable`
-  - `AsyncIterator`
-  - `Awaitable`
-  - `ChainMap`
-  - `ClassVar` (see PEP 526)
-  - `ContextManager`
-  - `Coroutine`
-  - `Counter`
-  - `DefaultDict`
-  - `Deque`
-  - `NewType`
-  - `NoReturn`
-  - `overload`
-  - `Text`
-  - `Type`
-  - `TYPE_CHECKING`
-  - `get_type_hints`
-
-- The following have always been present in `typing`, but the `typing_extensions` versions provide
-  additional features:
-
-  - `Any` (supports inheritance since Python 3.11)
-  - `NamedTuple` (supports multiple inheritance with `Generic` since Python 3.11)
-  - `TypeVar` (see PEPs 695 and 696)
-
-# Other Notes and Limitations
-
-Certain objects were changed after they were added to `typing`, and
-`typing_extensions` provides a backport even on newer Python versions:
-
-- `TypedDict` does not store runtime information
-  about which (if any) keys are non-required in Python 3.8, and does not
-  honor the `total` keyword with old-style `TypedDict()` in Python
-  3.9.0 and 3.9.1. `TypedDict` also does not support multiple inheritance
-  with `typing.Generic` on Python <3.11.
-- `get_origin` and `get_args` lack support for `Annotated` in
-  Python 3.8 and lack support for `ParamSpecArgs` and `ParamSpecKwargs`
-  in 3.9.
-- `@final` was changed in Python 3.11 to set the `.__final__` attribute.
-- `@overload` was changed in Python 3.11 to make function overloads
-  introspectable at runtime. In order to access overloads with
-  `typing_extensions.get_overloads()`, you must use
-  `@typing_extensions.overload`.
-- `NamedTuple` was changed in Python 3.11 to allow for multiple inheritance
-  with `typing.Generic`.
-- Since Python 3.11, it has been possible to inherit from `Any` at
-  runtime. `typing_extensions.Any` also provides this capability.
-- `TypeVar` gains two additional parameters, `default=` and `infer_variance=`,
-  in the draft PEPs 695 and 696, which are being considered for inclusion
-  in Python 3.12.
-
-There are a few types whose interface was modified between different
-versions of typing. For example, `typing.Sequence` was modified to
-subclass `typing.Reversible` as of Python 3.5.3.
-
-These changes are _not_ backported to prevent subtle compatibility
-issues when mixing the differing implementations of modified classes.
-
-Certain types have incorrect runtime behavior due to limitations of older
-versions of the typing module:
-
-- `ParamSpec` and `Concatenate` will not work with `get_args` and
-  `get_origin`. Certain PEP 612 special cases in user-defined
-  `Generic`s are also not available.
-
-These types are only guaranteed to work for static type checking.
-
-## Running tests
-
-To run tests, navigate into the appropriate source directory and run
-`test_typing_extensions.py`.
-
diff --git a/pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/RECORD b/pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/RECORD
deleted file mode 100644
index b9e1bb0391..0000000000
--- a/pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/RECORD
+++ /dev/null
@@ -1,8 +0,0 @@
-__pycache__/typing_extensions.cpython-311.pyc,,
-typing_extensions-4.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-typing_extensions-4.4.0.dist-info/LICENSE,sha256=x6-2XnVXB7n7kEhziaF20-09ADHVExr95FwjcV_16JE,12787
-typing_extensions-4.4.0.dist-info/METADATA,sha256=1zSh1eMLnLkLMMC6aZSGRKx3eRnivEGDFWGSVD1zqhA,7249
-typing_extensions-4.4.0.dist-info/RECORD,,
-typing_extensions-4.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-typing_extensions-4.4.0.dist-info/WHEEL,sha256=4TfKIB_xu-04bc2iKz6_zFt-gEFEEDU_31HGhqzOCE8,81
-typing_extensions.py,sha256=ipqWiq5AHzrwczt6c26AP05Llh6a5_GaXRpOBqbogHA,80078
diff --git a/pkg_resources/_vendor/typing_extensions.py b/pkg_resources/_vendor/typing_extensions.py
deleted file mode 100644
index ef42417c20..0000000000
--- a/pkg_resources/_vendor/typing_extensions.py
+++ /dev/null
@@ -1,2209 +0,0 @@
-import abc
-import collections
-import collections.abc
-import functools
-import operator
-import sys
-import types as _types
-import typing
-
-
-__all__ = [
-    # Super-special typing primitives.
-    'Any',
-    'ClassVar',
-    'Concatenate',
-    'Final',
-    'LiteralString',
-    'ParamSpec',
-    'ParamSpecArgs',
-    'ParamSpecKwargs',
-    'Self',
-    'Type',
-    'TypeVar',
-    'TypeVarTuple',
-    'Unpack',
-
-    # ABCs (from collections.abc).
-    'Awaitable',
-    'AsyncIterator',
-    'AsyncIterable',
-    'Coroutine',
-    'AsyncGenerator',
-    'AsyncContextManager',
-    'ChainMap',
-
-    # Concrete collection types.
-    'ContextManager',
-    'Counter',
-    'Deque',
-    'DefaultDict',
-    'NamedTuple',
-    'OrderedDict',
-    'TypedDict',
-
-    # Structural checks, a.k.a. protocols.
-    'SupportsIndex',
-
-    # One-off things.
-    'Annotated',
-    'assert_never',
-    'assert_type',
-    'clear_overloads',
-    'dataclass_transform',
-    'get_overloads',
-    'final',
-    'get_args',
-    'get_origin',
-    'get_type_hints',
-    'IntVar',
-    'is_typeddict',
-    'Literal',
-    'NewType',
-    'overload',
-    'override',
-    'Protocol',
-    'reveal_type',
-    'runtime',
-    'runtime_checkable',
-    'Text',
-    'TypeAlias',
-    'TypeGuard',
-    'TYPE_CHECKING',
-    'Never',
-    'NoReturn',
-    'Required',
-    'NotRequired',
-]
-
-# for backward compatibility
-PEP_560 = True
-GenericMeta = type
-
-# The functions below are modified copies of typing internal helpers.
-# They are needed by _ProtocolMeta and they provide support for PEP 646.
-
-_marker = object()
-
-
-def _check_generic(cls, parameters, elen=_marker):
-    """Check correct count for parameters of a generic cls (internal helper).
-    This gives a nice error message in case of count mismatch.
-    """
-    if not elen:
-        raise TypeError(f"{cls} is not a generic class")
-    if elen is _marker:
-        if not hasattr(cls, "__parameters__") or not cls.__parameters__:
-            raise TypeError(f"{cls} is not a generic class")
-        elen = len(cls.__parameters__)
-    alen = len(parameters)
-    if alen != elen:
-        if hasattr(cls, "__parameters__"):
-            parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
-            num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters)
-            if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples):
-                return
-        raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
-                        f" actual {alen}, expected {elen}")
-
-
-if sys.version_info >= (3, 10):
-    def _should_collect_from_parameters(t):
-        return isinstance(
-            t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType)
-        )
-elif sys.version_info >= (3, 9):
-    def _should_collect_from_parameters(t):
-        return isinstance(t, (typing._GenericAlias, _types.GenericAlias))
-else:
-    def _should_collect_from_parameters(t):
-        return isinstance(t, typing._GenericAlias) and not t._special
-
-
-def _collect_type_vars(types, typevar_types=None):
-    """Collect all type variable contained in types in order of
-    first appearance (lexicographic order). For example::
-
-        _collect_type_vars((T, List[S, T])) == (T, S)
-    """
-    if typevar_types is None:
-        typevar_types = typing.TypeVar
-    tvars = []
-    for t in types:
-        if (
-            isinstance(t, typevar_types) and
-            t not in tvars and
-            not _is_unpack(t)
-        ):
-            tvars.append(t)
-        if _should_collect_from_parameters(t):
-            tvars.extend([t for t in t.__parameters__ if t not in tvars])
-    return tuple(tvars)
-
-
-NoReturn = typing.NoReturn
-
-# Some unconstrained type variables.  These are used by the container types.
-# (These are not for export.)
-T = typing.TypeVar('T')  # Any type.
-KT = typing.TypeVar('KT')  # Key type.
-VT = typing.TypeVar('VT')  # Value type.
-T_co = typing.TypeVar('T_co', covariant=True)  # Any type covariant containers.
-T_contra = typing.TypeVar('T_contra', contravariant=True)  # Ditto contravariant.
-
-
-if sys.version_info >= (3, 11):
-    from typing import Any
-else:
-
-    class _AnyMeta(type):
-        def __instancecheck__(self, obj):
-            if self is Any:
-                raise TypeError("typing_extensions.Any cannot be used with isinstance()")
-            return super().__instancecheck__(obj)
-
-        def __repr__(self):
-            if self is Any:
-                return "typing_extensions.Any"
-            return super().__repr__()
-
-    class Any(metaclass=_AnyMeta):
-        """Special type indicating an unconstrained type.
-        - Any is compatible with every type.
-        - Any assumed to have all methods.
-        - All values assumed to be instances of Any.
-        Note that all the above statements are true from the point of view of
-        static type checkers. At runtime, Any should not be used with instance
-        checks.
-        """
-        def __new__(cls, *args, **kwargs):
-            if cls is Any:
-                raise TypeError("Any cannot be instantiated")
-            return super().__new__(cls, *args, **kwargs)
-
-
-ClassVar = typing.ClassVar
-
-# On older versions of typing there is an internal class named "Final".
-# 3.8+
-if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7):
-    Final = typing.Final
-# 3.7
-else:
-    class _FinalForm(typing._SpecialForm, _root=True):
-
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-        def __getitem__(self, parameters):
-            item = typing._type_check(parameters,
-                                      f'{self._name} accepts only a single type.')
-            return typing._GenericAlias(self, (item,))
-
-    Final = _FinalForm('Final',
-                       doc="""A special typing construct to indicate that a name
-                       cannot be re-assigned or overridden in a subclass.
-                       For example:
-
-                           MAX_SIZE: Final = 9000
-                           MAX_SIZE += 1  # Error reported by type checker
-
-                           class Connection:
-                               TIMEOUT: Final[int] = 10
-                           class FastConnector(Connection):
-                               TIMEOUT = 1  # Error reported by type checker
-
-                       There is no runtime checking of these properties.""")
-
-if sys.version_info >= (3, 11):
-    final = typing.final
-else:
-    # @final exists in 3.8+, but we backport it for all versions
-    # before 3.11 to keep support for the __final__ attribute.
-    # See https://bugs.python.org/issue46342
-    def final(f):
-        """This decorator can be used to indicate to type checkers that
-        the decorated method cannot be overridden, and decorated class
-        cannot be subclassed. For example:
-
-            class Base:
-                @final
-                def done(self) -> None:
-                    ...
-            class Sub(Base):
-                def done(self) -> None:  # Error reported by type checker
-                    ...
-            @final
-            class Leaf:
-                ...
-            class Other(Leaf):  # Error reported by type checker
-                ...
-
-        There is no runtime checking of these properties. The decorator
-        sets the ``__final__`` attribute to ``True`` on the decorated object
-        to allow runtime introspection.
-        """
-        try:
-            f.__final__ = True
-        except (AttributeError, TypeError):
-            # Skip the attribute silently if it is not writable.
-            # AttributeError happens if the object has __slots__ or a
-            # read-only property, TypeError if it's a builtin class.
-            pass
-        return f
-
-
-def IntVar(name):
-    return typing.TypeVar(name)
-
-
-# 3.8+:
-if hasattr(typing, 'Literal'):
-    Literal = typing.Literal
-# 3.7:
-else:
-    class _LiteralForm(typing._SpecialForm, _root=True):
-
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-        def __getitem__(self, parameters):
-            return typing._GenericAlias(self, parameters)
-
-    Literal = _LiteralForm('Literal',
-                           doc="""A type that can be used to indicate to type checkers
-                           that the corresponding value has a value literally equivalent
-                           to the provided parameter. For example:
-
-                               var: Literal[4] = 4
-
-                           The type checker understands that 'var' is literally equal to
-                           the value 4 and no other value.
-
-                           Literal[...] cannot be subclassed. There is no runtime
-                           checking verifying that the parameter is actually a value
-                           instead of a type.""")
-
-
-_overload_dummy = typing._overload_dummy  # noqa
-
-
-if hasattr(typing, "get_overloads"):  # 3.11+
-    overload = typing.overload
-    get_overloads = typing.get_overloads
-    clear_overloads = typing.clear_overloads
-else:
-    # {module: {qualname: {firstlineno: func}}}
-    _overload_registry = collections.defaultdict(
-        functools.partial(collections.defaultdict, dict)
-    )
-
-    def overload(func):
-        """Decorator for overloaded functions/methods.
-
-        In a stub file, place two or more stub definitions for the same
-        function in a row, each decorated with @overload.  For example:
-
-        @overload
-        def utf8(value: None) -> None: ...
-        @overload
-        def utf8(value: bytes) -> bytes: ...
-        @overload
-        def utf8(value: str) -> bytes: ...
-
-        In a non-stub file (i.e. a regular .py file), do the same but
-        follow it with an implementation.  The implementation should *not*
-        be decorated with @overload.  For example:
-
-        @overload
-        def utf8(value: None) -> None: ...
-        @overload
-        def utf8(value: bytes) -> bytes: ...
-        @overload
-        def utf8(value: str) -> bytes: ...
-        def utf8(value):
-            # implementation goes here
-
-        The overloads for a function can be retrieved at runtime using the
-        get_overloads() function.
-        """
-        # classmethod and staticmethod
-        f = getattr(func, "__func__", func)
-        try:
-            _overload_registry[f.__module__][f.__qualname__][
-                f.__code__.co_firstlineno
-            ] = func
-        except AttributeError:
-            # Not a normal function; ignore.
-            pass
-        return _overload_dummy
-
-    def get_overloads(func):
-        """Return all defined overloads for *func* as a sequence."""
-        # classmethod and staticmethod
-        f = getattr(func, "__func__", func)
-        if f.__module__ not in _overload_registry:
-            return []
-        mod_dict = _overload_registry[f.__module__]
-        if f.__qualname__ not in mod_dict:
-            return []
-        return list(mod_dict[f.__qualname__].values())
-
-    def clear_overloads():
-        """Clear all overloads in the registry."""
-        _overload_registry.clear()
-
-
-# This is not a real generic class.  Don't use outside annotations.
-Type = typing.Type
-
-# Various ABCs mimicking those in collections.abc.
-# A few are simply re-exported for completeness.
-
-
-Awaitable = typing.Awaitable
-Coroutine = typing.Coroutine
-AsyncIterable = typing.AsyncIterable
-AsyncIterator = typing.AsyncIterator
-Deque = typing.Deque
-ContextManager = typing.ContextManager
-AsyncContextManager = typing.AsyncContextManager
-DefaultDict = typing.DefaultDict
-
-# 3.7.2+
-if hasattr(typing, 'OrderedDict'):
-    OrderedDict = typing.OrderedDict
-# 3.7.0-3.7.2
-else:
-    OrderedDict = typing._alias(collections.OrderedDict, (KT, VT))
-
-Counter = typing.Counter
-ChainMap = typing.ChainMap
-AsyncGenerator = typing.AsyncGenerator
-NewType = typing.NewType
-Text = typing.Text
-TYPE_CHECKING = typing.TYPE_CHECKING
-
-
-_PROTO_WHITELIST = ['Callable', 'Awaitable',
-                    'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator',
-                    'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
-                    'ContextManager', 'AsyncContextManager']
-
-
-def _get_protocol_attrs(cls):
-    attrs = set()
-    for base in cls.__mro__[:-1]:  # without object
-        if base.__name__ in ('Protocol', 'Generic'):
-            continue
-        annotations = getattr(base, '__annotations__', {})
-        for attr in list(base.__dict__.keys()) + list(annotations.keys()):
-            if (not attr.startswith('_abc_') and attr not in (
-                    '__abstractmethods__', '__annotations__', '__weakref__',
-                    '_is_protocol', '_is_runtime_protocol', '__dict__',
-                    '__args__', '__slots__',
-                    '__next_in_mro__', '__parameters__', '__origin__',
-                    '__orig_bases__', '__extra__', '__tree_hash__',
-                    '__doc__', '__subclasshook__', '__init__', '__new__',
-                    '__module__', '_MutableMapping__marker', '_gorg')):
-                attrs.add(attr)
-    return attrs
-
-
-def _is_callable_members_only(cls):
-    return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))
-
-
-def _maybe_adjust_parameters(cls):
-    """Helper function used in Protocol.__init_subclass__ and _TypedDictMeta.__new__.
-
-    The contents of this function are very similar
-    to logic found in typing.Generic.__init_subclass__
-    on the CPython main branch.
-    """
-    tvars = []
-    if '__orig_bases__' in cls.__dict__:
-        tvars = typing._collect_type_vars(cls.__orig_bases__)
-        # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn].
-        # If found, tvars must be a subset of it.
-        # If not found, tvars is it.
-        # Also check for and reject plain Generic,
-        # and reject multiple Generic[...] and/or Protocol[...].
-        gvars = None
-        for base in cls.__orig_bases__:
-            if (isinstance(base, typing._GenericAlias) and
-                    base.__origin__ in (typing.Generic, Protocol)):
-                # for error messages
-                the_base = base.__origin__.__name__
-                if gvars is not None:
-                    raise TypeError(
-                        "Cannot inherit from Generic[...]"
-                        " and/or Protocol[...] multiple types.")
-                gvars = base.__parameters__
-        if gvars is None:
-            gvars = tvars
-        else:
-            tvarset = set(tvars)
-            gvarset = set(gvars)
-            if not tvarset <= gvarset:
-                s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
-                s_args = ', '.join(str(g) for g in gvars)
-                raise TypeError(f"Some type variables ({s_vars}) are"
-                                f" not listed in {the_base}[{s_args}]")
-            tvars = gvars
-    cls.__parameters__ = tuple(tvars)
-
-
-# 3.8+
-if hasattr(typing, 'Protocol'):
-    Protocol = typing.Protocol
-# 3.7
-else:
-
-    def _no_init(self, *args, **kwargs):
-        if type(self)._is_protocol:
-            raise TypeError('Protocols cannot be instantiated')
-
-    class _ProtocolMeta(abc.ABCMeta):  # noqa: B024
-        # This metaclass is a bit unfortunate and exists only because of the lack
-        # of __instancehook__.
-        def __instancecheck__(cls, instance):
-            # We need this method for situations where attributes are
-            # assigned in __init__.
-            if ((not getattr(cls, '_is_protocol', False) or
-                 _is_callable_members_only(cls)) and
-                    issubclass(instance.__class__, cls)):
-                return True
-            if cls._is_protocol:
-                if all(hasattr(instance, attr) and
-                       (not callable(getattr(cls, attr, None)) or
-                        getattr(instance, attr) is not None)
-                       for attr in _get_protocol_attrs(cls)):
-                    return True
-            return super().__instancecheck__(instance)
-
-    class Protocol(metaclass=_ProtocolMeta):
-        # There is quite a lot of overlapping code with typing.Generic.
-        # Unfortunately it is hard to avoid this while these live in two different
-        # modules. The duplicated code will be removed when Protocol is moved to typing.
-        """Base class for protocol classes. Protocol classes are defined as::
-
-            class Proto(Protocol):
-                def meth(self) -> int:
-                    ...
-
-        Such classes are primarily used with static type checkers that recognize
-        structural subtyping (static duck-typing), for example::
-
-            class C:
-                def meth(self) -> int:
-                    return 0
-
-            def func(x: Proto) -> int:
-                return x.meth()
-
-            func(C())  # Passes static type check
-
-        See PEP 544 for details. Protocol classes decorated with
-        @typing_extensions.runtime act as simple-minded runtime protocol that checks
-        only the presence of given attributes, ignoring their type signatures.
-
-        Protocol classes can be generic, they are defined as::
-
-            class GenProto(Protocol[T]):
-                def meth(self) -> T:
-                    ...
-        """
-        __slots__ = ()
-        _is_protocol = True
-
-        def __new__(cls, *args, **kwds):
-            if cls is Protocol:
-                raise TypeError("Type Protocol cannot be instantiated; "
-                                "it can only be used as a base class")
-            return super().__new__(cls)
-
-        @typing._tp_cache
-        def __class_getitem__(cls, params):
-            if not isinstance(params, tuple):
-                params = (params,)
-            if not params and cls is not typing.Tuple:
-                raise TypeError(
-                    f"Parameter list to {cls.__qualname__}[...] cannot be empty")
-            msg = "Parameters to generic types must be types."
-            params = tuple(typing._type_check(p, msg) for p in params)  # noqa
-            if cls is Protocol:
-                # Generic can only be subscripted with unique type variables.
-                if not all(isinstance(p, typing.TypeVar) for p in params):
-                    i = 0
-                    while isinstance(params[i], typing.TypeVar):
-                        i += 1
-                    raise TypeError(
-                        "Parameters to Protocol[...] must all be type variables."
-                        f" Parameter {i + 1} is {params[i]}")
-                if len(set(params)) != len(params):
-                    raise TypeError(
-                        "Parameters to Protocol[...] must all be unique")
-            else:
-                # Subscripting a regular Generic subclass.
-                _check_generic(cls, params, len(cls.__parameters__))
-            return typing._GenericAlias(cls, params)
-
-        def __init_subclass__(cls, *args, **kwargs):
-            if '__orig_bases__' in cls.__dict__:
-                error = typing.Generic in cls.__orig_bases__
-            else:
-                error = typing.Generic in cls.__bases__
-            if error:
-                raise TypeError("Cannot inherit from plain Generic")
-            _maybe_adjust_parameters(cls)
-
-            # Determine if this is a protocol or a concrete subclass.
-            if not cls.__dict__.get('_is_protocol', None):
-                cls._is_protocol = any(b is Protocol for b in cls.__bases__)
-
-            # Set (or override) the protocol subclass hook.
-            def _proto_hook(other):
-                if not cls.__dict__.get('_is_protocol', None):
-                    return NotImplemented
-                if not getattr(cls, '_is_runtime_protocol', False):
-                    if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
-                        return NotImplemented
-                    raise TypeError("Instance and class checks can only be used with"
-                                    " @runtime protocols")
-                if not _is_callable_members_only(cls):
-                    if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
-                        return NotImplemented
-                    raise TypeError("Protocols with non-method members"
-                                    " don't support issubclass()")
-                if not isinstance(other, type):
-                    # Same error as for issubclass(1, int)
-                    raise TypeError('issubclass() arg 1 must be a class')
-                for attr in _get_protocol_attrs(cls):
-                    for base in other.__mro__:
-                        if attr in base.__dict__:
-                            if base.__dict__[attr] is None:
-                                return NotImplemented
-                            break
-                        annotations = getattr(base, '__annotations__', {})
-                        if (isinstance(annotations, typing.Mapping) and
-                                attr in annotations and
-                                isinstance(other, _ProtocolMeta) and
-                                other._is_protocol):
-                            break
-                    else:
-                        return NotImplemented
-                return True
-            if '__subclasshook__' not in cls.__dict__:
-                cls.__subclasshook__ = _proto_hook
-
-            # We have nothing more to do for non-protocols.
-            if not cls._is_protocol:
-                return
-
-            # Check consistency of bases.
-            for base in cls.__bases__:
-                if not (base in (object, typing.Generic) or
-                        base.__module__ == 'collections.abc' and
-                        base.__name__ in _PROTO_WHITELIST or
-                        isinstance(base, _ProtocolMeta) and base._is_protocol):
-                    raise TypeError('Protocols can only inherit from other'
-                                    f' protocols, got {repr(base)}')
-            cls.__init__ = _no_init
-
-
-# 3.8+
-if hasattr(typing, 'runtime_checkable'):
-    runtime_checkable = typing.runtime_checkable
-# 3.7
-else:
-    def runtime_checkable(cls):
-        """Mark a protocol class as a runtime protocol, so that it
-        can be used with isinstance() and issubclass(). Raise TypeError
-        if applied to a non-protocol class.
-
-        This allows a simple-minded structural check very similar to the
-        one-offs in collections.abc such as Hashable.
-        """
-        if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol:
-            raise TypeError('@runtime_checkable can be only applied to protocol classes,'
-                            f' got {cls!r}')
-        cls._is_runtime_protocol = True
-        return cls
-
-
-# Exists for backwards compatibility.
-runtime = runtime_checkable
-
-
-# 3.8+
-if hasattr(typing, 'SupportsIndex'):
-    SupportsIndex = typing.SupportsIndex
-# 3.7
-else:
-    @runtime_checkable
-    class SupportsIndex(Protocol):
-        __slots__ = ()
-
-        @abc.abstractmethod
-        def __index__(self) -> int:
-            pass
-
-
-if hasattr(typing, "Required"):
-    # The standard library TypedDict in Python 3.8 does not store runtime information
-    # about which (if any) keys are optional.  See https://bugs.python.org/issue38834
-    # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
-    # keyword with old-style TypedDict().  See https://bugs.python.org/issue42059
-    # The standard library TypedDict below Python 3.11 does not store runtime
-    # information about optional and required keys when using Required or NotRequired.
-    # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.
-    TypedDict = typing.TypedDict
-    _TypedDictMeta = typing._TypedDictMeta
-    is_typeddict = typing.is_typeddict
-else:
-    def _check_fails(cls, other):
-        try:
-            if sys._getframe(1).f_globals['__name__'] not in ['abc',
-                                                              'functools',
-                                                              'typing']:
-                # Typed dicts are only for static structural subtyping.
-                raise TypeError('TypedDict does not support instance and class checks')
-        except (AttributeError, ValueError):
-            pass
-        return False
-
-    def _dict_new(*args, **kwargs):
-        if not args:
-            raise TypeError('TypedDict.__new__(): not enough arguments')
-        _, args = args[0], args[1:]  # allow the "cls" keyword be passed
-        return dict(*args, **kwargs)
-
-    _dict_new.__text_signature__ = '($cls, _typename, _fields=None, /, **kwargs)'
-
-    def _typeddict_new(*args, total=True, **kwargs):
-        if not args:
-            raise TypeError('TypedDict.__new__(): not enough arguments')
-        _, args = args[0], args[1:]  # allow the "cls" keyword be passed
-        if args:
-            typename, args = args[0], args[1:]  # allow the "_typename" keyword be passed
-        elif '_typename' in kwargs:
-            typename = kwargs.pop('_typename')
-            import warnings
-            warnings.warn("Passing '_typename' as keyword argument is deprecated",
-                          DeprecationWarning, stacklevel=2)
-        else:
-            raise TypeError("TypedDict.__new__() missing 1 required positional "
-                            "argument: '_typename'")
-        if args:
-            try:
-                fields, = args  # allow the "_fields" keyword be passed
-            except ValueError:
-                raise TypeError('TypedDict.__new__() takes from 2 to 3 '
-                                f'positional arguments but {len(args) + 2} '
-                                'were given')
-        elif '_fields' in kwargs and len(kwargs) == 1:
-            fields = kwargs.pop('_fields')
-            import warnings
-            warnings.warn("Passing '_fields' as keyword argument is deprecated",
-                          DeprecationWarning, stacklevel=2)
-        else:
-            fields = None
-
-        if fields is None:
-            fields = kwargs
-        elif kwargs:
-            raise TypeError("TypedDict takes either a dict or keyword arguments,"
-                            " but not both")
-
-        ns = {'__annotations__': dict(fields)}
-        try:
-            # Setting correct module is necessary to make typed dict classes pickleable.
-            ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
-        except (AttributeError, ValueError):
-            pass
-
-        return _TypedDictMeta(typename, (), ns, total=total)
-
-    _typeddict_new.__text_signature__ = ('($cls, _typename, _fields=None,'
-                                         ' /, *, total=True, **kwargs)')
-
-    class _TypedDictMeta(type):
-        def __init__(cls, name, bases, ns, total=True):
-            super().__init__(name, bases, ns)
-
-        def __new__(cls, name, bases, ns, total=True):
-            # Create new typed dict class object.
-            # This method is called directly when TypedDict is subclassed,
-            # or via _typeddict_new when TypedDict is instantiated. This way
-            # TypedDict supports all three syntaxes described in its docstring.
-            # Subclasses and instances of TypedDict return actual dictionaries
-            # via _dict_new.
-            ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new
-            # Don't insert typing.Generic into __bases__ here,
-            # or Generic.__init_subclass__ will raise TypeError
-            # in the super().__new__() call.
-            # Instead, monkey-patch __bases__ onto the class after it's been created.
-            tp_dict = super().__new__(cls, name, (dict,), ns)
-
-            if any(issubclass(base, typing.Generic) for base in bases):
-                tp_dict.__bases__ = (typing.Generic, dict)
-                _maybe_adjust_parameters(tp_dict)
-
-            annotations = {}
-            own_annotations = ns.get('__annotations__', {})
-            msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
-            own_annotations = {
-                n: typing._type_check(tp, msg) for n, tp in own_annotations.items()
-            }
-            required_keys = set()
-            optional_keys = set()
-
-            for base in bases:
-                annotations.update(base.__dict__.get('__annotations__', {}))
-                required_keys.update(base.__dict__.get('__required_keys__', ()))
-                optional_keys.update(base.__dict__.get('__optional_keys__', ()))
-
-            annotations.update(own_annotations)
-            for annotation_key, annotation_type in own_annotations.items():
-                annotation_origin = get_origin(annotation_type)
-                if annotation_origin is Annotated:
-                    annotation_args = get_args(annotation_type)
-                    if annotation_args:
-                        annotation_type = annotation_args[0]
-                        annotation_origin = get_origin(annotation_type)
-
-                if annotation_origin is Required:
-                    required_keys.add(annotation_key)
-                elif annotation_origin is NotRequired:
-                    optional_keys.add(annotation_key)
-                elif total:
-                    required_keys.add(annotation_key)
-                else:
-                    optional_keys.add(annotation_key)
-
-            tp_dict.__annotations__ = annotations
-            tp_dict.__required_keys__ = frozenset(required_keys)
-            tp_dict.__optional_keys__ = frozenset(optional_keys)
-            if not hasattr(tp_dict, '__total__'):
-                tp_dict.__total__ = total
-            return tp_dict
-
-        __instancecheck__ = __subclasscheck__ = _check_fails
-
-    TypedDict = _TypedDictMeta('TypedDict', (dict,), {})
-    TypedDict.__module__ = __name__
-    TypedDict.__doc__ = \
-        """A simple typed name space. At runtime it is equivalent to a plain dict.
-
-        TypedDict creates a dictionary type that expects all of its
-        instances to have a certain set of keys, with each key
-        associated with a value of a consistent type. This expectation
-        is not checked at runtime but is only enforced by type checkers.
-        Usage::
-
-            class Point2D(TypedDict):
-                x: int
-                y: int
-                label: str
-
-            a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
-            b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check
-
-            assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
-
-        The type info can be accessed via the Point2D.__annotations__ dict, and
-        the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
-        TypedDict supports two additional equivalent forms::
-
-            Point2D = TypedDict('Point2D', x=int, y=int, label=str)
-            Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
-
-        The class syntax is only supported in Python 3.6+, while two other
-        syntax forms work for Python 2.7 and 3.2+
-        """
-
-    if hasattr(typing, "_TypedDictMeta"):
-        _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)
-    else:
-        _TYPEDDICT_TYPES = (_TypedDictMeta,)
-
-    def is_typeddict(tp):
-        """Check if an annotation is a TypedDict class
-
-        For example::
-            class Film(TypedDict):
-                title: str
-                year: int
-
-            is_typeddict(Film)  # => True
-            is_typeddict(Union[list, str])  # => False
-        """
-        return isinstance(tp, tuple(_TYPEDDICT_TYPES))
-
-
-if hasattr(typing, "assert_type"):
-    assert_type = typing.assert_type
-
-else:
-    def assert_type(__val, __typ):
-        """Assert (to the type checker) that the value is of the given type.
-
-        When the type checker encounters a call to assert_type(), it
-        emits an error if the value is not of the specified type::
-
-            def greet(name: str) -> None:
-                assert_type(name, str)  # ok
-                assert_type(name, int)  # type checker error
-
-        At runtime this returns the first argument unchanged and otherwise
-        does nothing.
-        """
-        return __val
-
-
-if hasattr(typing, "Required"):
-    get_type_hints = typing.get_type_hints
-else:
-    import functools
-    import types
-
-    # replaces _strip_annotations()
-    def _strip_extras(t):
-        """Strips Annotated, Required and NotRequired from a given type."""
-        if isinstance(t, _AnnotatedAlias):
-            return _strip_extras(t.__origin__)
-        if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired):
-            return _strip_extras(t.__args__[0])
-        if isinstance(t, typing._GenericAlias):
-            stripped_args = tuple(_strip_extras(a) for a in t.__args__)
-            if stripped_args == t.__args__:
-                return t
-            return t.copy_with(stripped_args)
-        if hasattr(types, "GenericAlias") and isinstance(t, types.GenericAlias):
-            stripped_args = tuple(_strip_extras(a) for a in t.__args__)
-            if stripped_args == t.__args__:
-                return t
-            return types.GenericAlias(t.__origin__, stripped_args)
-        if hasattr(types, "UnionType") and isinstance(t, types.UnionType):
-            stripped_args = tuple(_strip_extras(a) for a in t.__args__)
-            if stripped_args == t.__args__:
-                return t
-            return functools.reduce(operator.or_, stripped_args)
-
-        return t
-
-    def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
-        """Return type hints for an object.
-
-        This is often the same as obj.__annotations__, but it handles
-        forward references encoded as string literals, adds Optional[t] if a
-        default value equal to None is set and recursively replaces all
-        'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
-        (unless 'include_extras=True').
-
-        The argument may be a module, class, method, or function. The annotations
-        are returned as a dictionary. For classes, annotations include also
-        inherited members.
-
-        TypeError is raised if the argument is not of a type that can contain
-        annotations, and an empty dictionary is returned if no annotations are
-        present.
-
-        BEWARE -- the behavior of globalns and localns is counterintuitive
-        (unless you are familiar with how eval() and exec() work).  The
-        search order is locals first, then globals.
-
-        - If no dict arguments are passed, an attempt is made to use the
-          globals from obj (or the respective module's globals for classes),
-          and these are also used as the locals.  If the object does not appear
-          to have globals, an empty dictionary is used.
-
-        - If one dict argument is passed, it is used for both globals and
-          locals.
-
-        - If two dict arguments are passed, they specify globals and
-          locals, respectively.
-        """
-        if hasattr(typing, "Annotated"):
-            hint = typing.get_type_hints(
-                obj, globalns=globalns, localns=localns, include_extras=True
-            )
-        else:
-            hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
-        if include_extras:
-            return hint
-        return {k: _strip_extras(t) for k, t in hint.items()}
-
-
-# Python 3.9+ has PEP 593 (Annotated)
-if hasattr(typing, 'Annotated'):
-    Annotated = typing.Annotated
-    # Not exported and not a public API, but needed for get_origin() and get_args()
-    # to work.
-    _AnnotatedAlias = typing._AnnotatedAlias
-# 3.7-3.8
-else:
-    class _AnnotatedAlias(typing._GenericAlias, _root=True):
-        """Runtime representation of an annotated type.
-
-        At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
-        with extra annotations. The alias behaves like a normal typing alias,
-        instantiating is the same as instantiating the underlying type, binding
-        it to types is also the same.
-        """
-        def __init__(self, origin, metadata):
-            if isinstance(origin, _AnnotatedAlias):
-                metadata = origin.__metadata__ + metadata
-                origin = origin.__origin__
-            super().__init__(origin, origin)
-            self.__metadata__ = metadata
-
-        def copy_with(self, params):
-            assert len(params) == 1
-            new_type = params[0]
-            return _AnnotatedAlias(new_type, self.__metadata__)
-
-        def __repr__(self):
-            return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
-                    f"{', '.join(repr(a) for a in self.__metadata__)}]")
-
-        def __reduce__(self):
-            return operator.getitem, (
-                Annotated, (self.__origin__,) + self.__metadata__
-            )
-
-        def __eq__(self, other):
-            if not isinstance(other, _AnnotatedAlias):
-                return NotImplemented
-            if self.__origin__ != other.__origin__:
-                return False
-            return self.__metadata__ == other.__metadata__
-
-        def __hash__(self):
-            return hash((self.__origin__, self.__metadata__))
-
-    class Annotated:
-        """Add context specific metadata to a type.
-
-        Example: Annotated[int, runtime_check.Unsigned] indicates to the
-        hypothetical runtime_check module that this type is an unsigned int.
-        Every other consumer of this type can ignore this metadata and treat
-        this type as int.
-
-        The first argument to Annotated must be a valid type (and will be in
-        the __origin__ field), the remaining arguments are kept as a tuple in
-        the __extra__ field.
-
-        Details:
-
-        - It's an error to call `Annotated` with less than two arguments.
-        - Nested Annotated are flattened::
-
-            Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
-
-        - Instantiating an annotated type is equivalent to instantiating the
-        underlying type::
-
-            Annotated[C, Ann1](5) == C(5)
-
-        - Annotated can be used as a generic type alias::
-
-            Optimized = Annotated[T, runtime.Optimize()]
-            Optimized[int] == Annotated[int, runtime.Optimize()]
-
-            OptimizedList = Annotated[List[T], runtime.Optimize()]
-            OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
-        """
-
-        __slots__ = ()
-
-        def __new__(cls, *args, **kwargs):
-            raise TypeError("Type Annotated cannot be instantiated.")
-
-        @typing._tp_cache
-        def __class_getitem__(cls, params):
-            if not isinstance(params, tuple) or len(params) < 2:
-                raise TypeError("Annotated[...] should be used "
-                                "with at least two arguments (a type and an "
-                                "annotation).")
-            allowed_special_forms = (ClassVar, Final)
-            if get_origin(params[0]) in allowed_special_forms:
-                origin = params[0]
-            else:
-                msg = "Annotated[t, ...]: t must be a type."
-                origin = typing._type_check(params[0], msg)
-            metadata = tuple(params[1:])
-            return _AnnotatedAlias(origin, metadata)
-
-        def __init_subclass__(cls, *args, **kwargs):
-            raise TypeError(
-                f"Cannot subclass {cls.__module__}.Annotated"
-            )
-
-# Python 3.8 has get_origin() and get_args() but those implementations aren't
-# Annotated-aware, so we can't use those. Python 3.9's versions don't support
-# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
-if sys.version_info[:2] >= (3, 10):
-    get_origin = typing.get_origin
-    get_args = typing.get_args
-# 3.7-3.9
-else:
-    try:
-        # 3.9+
-        from typing import _BaseGenericAlias
-    except ImportError:
-        _BaseGenericAlias = typing._GenericAlias
-    try:
-        # 3.9+
-        from typing import GenericAlias as _typing_GenericAlias
-    except ImportError:
-        _typing_GenericAlias = typing._GenericAlias
-
-    def get_origin(tp):
-        """Get the unsubscripted version of a type.
-
-        This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
-        and Annotated. Return None for unsupported types. Examples::
-
-            get_origin(Literal[42]) is Literal
-            get_origin(int) is None
-            get_origin(ClassVar[int]) is ClassVar
-            get_origin(Generic) is Generic
-            get_origin(Generic[T]) is Generic
-            get_origin(Union[T, int]) is Union
-            get_origin(List[Tuple[T, T]][int]) == list
-            get_origin(P.args) is P
-        """
-        if isinstance(tp, _AnnotatedAlias):
-            return Annotated
-        if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias,
-                           ParamSpecArgs, ParamSpecKwargs)):
-            return tp.__origin__
-        if tp is typing.Generic:
-            return typing.Generic
-        return None
-
-    def get_args(tp):
-        """Get type arguments with all substitutions performed.
-
-        For unions, basic simplifications used by Union constructor are performed.
-        Examples::
-            get_args(Dict[str, int]) == (str, int)
-            get_args(int) == ()
-            get_args(Union[int, Union[T, int], str][int]) == (int, str)
-            get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
-            get_args(Callable[[], T][int]) == ([], int)
-        """
-        if isinstance(tp, _AnnotatedAlias):
-            return (tp.__origin__,) + tp.__metadata__
-        if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):
-            if getattr(tp, "_special", False):
-                return ()
-            res = tp.__args__
-            if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
-                res = (list(res[:-1]), res[-1])
-            return res
-        return ()
-
-
-# 3.10+
-if hasattr(typing, 'TypeAlias'):
-    TypeAlias = typing.TypeAlias
-# 3.9
-elif sys.version_info[:2] >= (3, 9):
-    class _TypeAliasForm(typing._SpecialForm, _root=True):
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-    @_TypeAliasForm
-    def TypeAlias(self, parameters):
-        """Special marker indicating that an assignment should
-        be recognized as a proper type alias definition by type
-        checkers.
-
-        For example::
-
-            Predicate: TypeAlias = Callable[..., bool]
-
-        It's invalid when used anywhere except as in the example above.
-        """
-        raise TypeError(f"{self} is not subscriptable")
-# 3.7-3.8
-else:
-    class _TypeAliasForm(typing._SpecialForm, _root=True):
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-    TypeAlias = _TypeAliasForm('TypeAlias',
-                               doc="""Special marker indicating that an assignment should
-                               be recognized as a proper type alias definition by type
-                               checkers.
-
-                               For example::
-
-                                   Predicate: TypeAlias = Callable[..., bool]
-
-                               It's invalid when used anywhere except as in the example
-                               above.""")
-
-
-class _DefaultMixin:
-    """Mixin for TypeVarLike defaults."""
-
-    __slots__ = ()
-
-    def __init__(self, default):
-        if isinstance(default, (tuple, list)):
-            self.__default__ = tuple((typing._type_check(d, "Default must be a type")
-                                      for d in default))
-        elif default:
-            self.__default__ = typing._type_check(default, "Default must be a type")
-        else:
-            self.__default__ = None
-
-
-# Add default and infer_variance parameters from PEP 696 and 695
-class TypeVar(typing.TypeVar, _DefaultMixin, _root=True):
-    """Type variable."""
-
-    __module__ = 'typing'
-
-    def __init__(self, name, *constraints, bound=None,
-                 covariant=False, contravariant=False,
-                 default=None, infer_variance=False):
-        super().__init__(name, *constraints, bound=bound, covariant=covariant,
-                         contravariant=contravariant)
-        _DefaultMixin.__init__(self, default)
-        self.__infer_variance__ = infer_variance
-
-        # for pickling:
-        try:
-            def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
-        except (AttributeError, ValueError):
-            def_mod = None
-        if def_mod != 'typing_extensions':
-            self.__module__ = def_mod
-
-
-# Python 3.10+ has PEP 612
-if hasattr(typing, 'ParamSpecArgs'):
-    ParamSpecArgs = typing.ParamSpecArgs
-    ParamSpecKwargs = typing.ParamSpecKwargs
-# 3.7-3.9
-else:
-    class _Immutable:
-        """Mixin to indicate that object should not be copied."""
-        __slots__ = ()
-
-        def __copy__(self):
-            return self
-
-        def __deepcopy__(self, memo):
-            return self
-
-    class ParamSpecArgs(_Immutable):
-        """The args for a ParamSpec object.
-
-        Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
-
-        ParamSpecArgs objects have a reference back to their ParamSpec:
-
-        P.args.__origin__ is P
-
-        This type is meant for runtime introspection and has no special meaning to
-        static type checkers.
-        """
-        def __init__(self, origin):
-            self.__origin__ = origin
-
-        def __repr__(self):
-            return f"{self.__origin__.__name__}.args"
-
-        def __eq__(self, other):
-            if not isinstance(other, ParamSpecArgs):
-                return NotImplemented
-            return self.__origin__ == other.__origin__
-
-    class ParamSpecKwargs(_Immutable):
-        """The kwargs for a ParamSpec object.
-
-        Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
-
-        ParamSpecKwargs objects have a reference back to their ParamSpec:
-
-        P.kwargs.__origin__ is P
-
-        This type is meant for runtime introspection and has no special meaning to
-        static type checkers.
-        """
-        def __init__(self, origin):
-            self.__origin__ = origin
-
-        def __repr__(self):
-            return f"{self.__origin__.__name__}.kwargs"
-
-        def __eq__(self, other):
-            if not isinstance(other, ParamSpecKwargs):
-                return NotImplemented
-            return self.__origin__ == other.__origin__
-
-# 3.10+
-if hasattr(typing, 'ParamSpec'):
-
-    # Add default Parameter - PEP 696
-    class ParamSpec(typing.ParamSpec, _DefaultMixin, _root=True):
-        """Parameter specification variable."""
-
-        __module__ = 'typing'
-
-        def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
-                     default=None):
-            super().__init__(name, bound=bound, covariant=covariant,
-                             contravariant=contravariant)
-            _DefaultMixin.__init__(self, default)
-
-            # for pickling:
-            try:
-                def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
-            except (AttributeError, ValueError):
-                def_mod = None
-            if def_mod != 'typing_extensions':
-                self.__module__ = def_mod
-
-# 3.7-3.9
-else:
-
-    # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
-    class ParamSpec(list, _DefaultMixin):
-        """Parameter specification variable.
-
-        Usage::
-
-           P = ParamSpec('P')
-
-        Parameter specification variables exist primarily for the benefit of static
-        type checkers.  They are used to forward the parameter types of one
-        callable to another callable, a pattern commonly found in higher order
-        functions and decorators.  They are only valid when used in ``Concatenate``,
-        or s the first argument to ``Callable``. In Python 3.10 and higher,
-        they are also supported in user-defined Generics at runtime.
-        See class Generic for more information on generic types.  An
-        example for annotating a decorator::
-
-           T = TypeVar('T')
-           P = ParamSpec('P')
-
-           def add_logging(f: Callable[P, T]) -> Callable[P, T]:
-               '''A type-safe decorator to add logging to a function.'''
-               def inner(*args: P.args, **kwargs: P.kwargs) -> T:
-                   logging.info(f'{f.__name__} was called')
-                   return f(*args, **kwargs)
-               return inner
-
-           @add_logging
-           def add_two(x: float, y: float) -> float:
-               '''Add two numbers together.'''
-               return x + y
-
-        Parameter specification variables defined with covariant=True or
-        contravariant=True can be used to declare covariant or contravariant
-        generic types.  These keyword arguments are valid, but their actual semantics
-        are yet to be decided.  See PEP 612 for details.
-
-        Parameter specification variables can be introspected. e.g.:
-
-           P.__name__ == 'T'
-           P.__bound__ == None
-           P.__covariant__ == False
-           P.__contravariant__ == False
-
-        Note that only parameter specification variables defined in global scope can
-        be pickled.
-        """
-
-        # Trick Generic __parameters__.
-        __class__ = typing.TypeVar
-
-        @property
-        def args(self):
-            return ParamSpecArgs(self)
-
-        @property
-        def kwargs(self):
-            return ParamSpecKwargs(self)
-
-        def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
-                     default=None):
-            super().__init__([self])
-            self.__name__ = name
-            self.__covariant__ = bool(covariant)
-            self.__contravariant__ = bool(contravariant)
-            if bound:
-                self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
-            else:
-                self.__bound__ = None
-            _DefaultMixin.__init__(self, default)
-
-            # for pickling:
-            try:
-                def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
-            except (AttributeError, ValueError):
-                def_mod = None
-            if def_mod != 'typing_extensions':
-                self.__module__ = def_mod
-
-        def __repr__(self):
-            if self.__covariant__:
-                prefix = '+'
-            elif self.__contravariant__:
-                prefix = '-'
-            else:
-                prefix = '~'
-            return prefix + self.__name__
-
-        def __hash__(self):
-            return object.__hash__(self)
-
-        def __eq__(self, other):
-            return self is other
-
-        def __reduce__(self):
-            return self.__name__
-
-        # Hack to get typing._type_check to pass.
-        def __call__(self, *args, **kwargs):
-            pass
-
-
-# 3.7-3.9
-if not hasattr(typing, 'Concatenate'):
-    # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
-    class _ConcatenateGenericAlias(list):
-
-        # Trick Generic into looking into this for __parameters__.
-        __class__ = typing._GenericAlias
-
-        # Flag in 3.8.
-        _special = False
-
-        def __init__(self, origin, args):
-            super().__init__(args)
-            self.__origin__ = origin
-            self.__args__ = args
-
-        def __repr__(self):
-            _type_repr = typing._type_repr
-            return (f'{_type_repr(self.__origin__)}'
-                    f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
-
-        def __hash__(self):
-            return hash((self.__origin__, self.__args__))
-
-        # Hack to get typing._type_check to pass in Generic.
-        def __call__(self, *args, **kwargs):
-            pass
-
-        @property
-        def __parameters__(self):
-            return tuple(
-                tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
-            )
-
-
-# 3.7-3.9
-@typing._tp_cache
-def _concatenate_getitem(self, parameters):
-    if parameters == ():
-        raise TypeError("Cannot take a Concatenate of no types.")
-    if not isinstance(parameters, tuple):
-        parameters = (parameters,)
-    if not isinstance(parameters[-1], ParamSpec):
-        raise TypeError("The last parameter to Concatenate should be a "
-                        "ParamSpec variable.")
-    msg = "Concatenate[arg, ...]: each arg must be a type."
-    parameters = tuple(typing._type_check(p, msg) for p in parameters)
-    return _ConcatenateGenericAlias(self, parameters)
-
-
-# 3.10+
-if hasattr(typing, 'Concatenate'):
-    Concatenate = typing.Concatenate
-    _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa
-# 3.9
-elif sys.version_info[:2] >= (3, 9):
-    @_TypeAliasForm
-    def Concatenate(self, parameters):
-        """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
-        higher order function which adds, removes or transforms parameters of a
-        callable.
-
-        For example::
-
-           Callable[Concatenate[int, P], int]
-
-        See PEP 612 for detailed information.
-        """
-        return _concatenate_getitem(self, parameters)
-# 3.7-8
-else:
-    class _ConcatenateForm(typing._SpecialForm, _root=True):
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-        def __getitem__(self, parameters):
-            return _concatenate_getitem(self, parameters)
-
-    Concatenate = _ConcatenateForm(
-        'Concatenate',
-        doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
-        higher order function which adds, removes or transforms parameters of a
-        callable.
-
-        For example::
-
-           Callable[Concatenate[int, P], int]
-
-        See PEP 612 for detailed information.
-        """)
-
-# 3.10+
-if hasattr(typing, 'TypeGuard'):
-    TypeGuard = typing.TypeGuard
-# 3.9
-elif sys.version_info[:2] >= (3, 9):
-    class _TypeGuardForm(typing._SpecialForm, _root=True):
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-    @_TypeGuardForm
-    def TypeGuard(self, parameters):
-        """Special typing form used to annotate the return type of a user-defined
-        type guard function.  ``TypeGuard`` only accepts a single type argument.
-        At runtime, functions marked this way should return a boolean.
-
-        ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
-        type checkers to determine a more precise type of an expression within a
-        program's code flow.  Usually type narrowing is done by analyzing
-        conditional code flow and applying the narrowing to a block of code.  The
-        conditional expression here is sometimes referred to as a "type guard".
-
-        Sometimes it would be convenient to use a user-defined boolean function
-        as a type guard.  Such a function should use ``TypeGuard[...]`` as its
-        return type to alert static type checkers to this intention.
-
-        Using  ``-> TypeGuard`` tells the static type checker that for a given
-        function:
-
-        1. The return value is a boolean.
-        2. If the return value is ``True``, the type of its argument
-        is the type inside ``TypeGuard``.
-
-        For example::
-
-            def is_str(val: Union[str, float]):
-                # "isinstance" type guard
-                if isinstance(val, str):
-                    # Type of ``val`` is narrowed to ``str``
-                    ...
-                else:
-                    # Else, type of ``val`` is narrowed to ``float``.
-                    ...
-
-        Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
-        form of ``TypeA`` (it can even be a wider form) and this may lead to
-        type-unsafe results.  The main reason is to allow for things like
-        narrowing ``List[object]`` to ``List[str]`` even though the latter is not
-        a subtype of the former, since ``List`` is invariant.  The responsibility of
-        writing type-safe type guards is left to the user.
-
-        ``TypeGuard`` also works with type variables.  For more information, see
-        PEP 647 (User-Defined Type Guards).
-        """
-        item = typing._type_check(parameters, f'{self} accepts only a single type.')
-        return typing._GenericAlias(self, (item,))
-# 3.7-3.8
-else:
-    class _TypeGuardForm(typing._SpecialForm, _root=True):
-
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-        def __getitem__(self, parameters):
-            item = typing._type_check(parameters,
-                                      f'{self._name} accepts only a single type')
-            return typing._GenericAlias(self, (item,))
-
-    TypeGuard = _TypeGuardForm(
-        'TypeGuard',
-        doc="""Special typing form used to annotate the return type of a user-defined
-        type guard function.  ``TypeGuard`` only accepts a single type argument.
-        At runtime, functions marked this way should return a boolean.
-
-        ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
-        type checkers to determine a more precise type of an expression within a
-        program's code flow.  Usually type narrowing is done by analyzing
-        conditional code flow and applying the narrowing to a block of code.  The
-        conditional expression here is sometimes referred to as a "type guard".
-
-        Sometimes it would be convenient to use a user-defined boolean function
-        as a type guard.  Such a function should use ``TypeGuard[...]`` as its
-        return type to alert static type checkers to this intention.
-
-        Using  ``-> TypeGuard`` tells the static type checker that for a given
-        function:
-
-        1. The return value is a boolean.
-        2. If the return value is ``True``, the type of its argument
-        is the type inside ``TypeGuard``.
-
-        For example::
-
-            def is_str(val: Union[str, float]):
-                # "isinstance" type guard
-                if isinstance(val, str):
-                    # Type of ``val`` is narrowed to ``str``
-                    ...
-                else:
-                    # Else, type of ``val`` is narrowed to ``float``.
-                    ...
-
-        Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
-        form of ``TypeA`` (it can even be a wider form) and this may lead to
-        type-unsafe results.  The main reason is to allow for things like
-        narrowing ``List[object]`` to ``List[str]`` even though the latter is not
-        a subtype of the former, since ``List`` is invariant.  The responsibility of
-        writing type-safe type guards is left to the user.
-
-        ``TypeGuard`` also works with type variables.  For more information, see
-        PEP 647 (User-Defined Type Guards).
-        """)
-
-
-# Vendored from cpython typing._SpecialFrom
-class _SpecialForm(typing._Final, _root=True):
-    __slots__ = ('_name', '__doc__', '_getitem')
-
-    def __init__(self, getitem):
-        self._getitem = getitem
-        self._name = getitem.__name__
-        self.__doc__ = getitem.__doc__
-
-    def __getattr__(self, item):
-        if item in {'__name__', '__qualname__'}:
-            return self._name
-
-        raise AttributeError(item)
-
-    def __mro_entries__(self, bases):
-        raise TypeError(f"Cannot subclass {self!r}")
-
-    def __repr__(self):
-        return f'typing_extensions.{self._name}'
-
-    def __reduce__(self):
-        return self._name
-
-    def __call__(self, *args, **kwds):
-        raise TypeError(f"Cannot instantiate {self!r}")
-
-    def __or__(self, other):
-        return typing.Union[self, other]
-
-    def __ror__(self, other):
-        return typing.Union[other, self]
-
-    def __instancecheck__(self, obj):
-        raise TypeError(f"{self} cannot be used with isinstance()")
-
-    def __subclasscheck__(self, cls):
-        raise TypeError(f"{self} cannot be used with issubclass()")
-
-    @typing._tp_cache
-    def __getitem__(self, parameters):
-        return self._getitem(self, parameters)
-
-
-if hasattr(typing, "LiteralString"):
-    LiteralString = typing.LiteralString
-else:
-    @_SpecialForm
-    def LiteralString(self, params):
-        """Represents an arbitrary literal string.
-
-        Example::
-
-          from typing_extensions import LiteralString
-
-          def query(sql: LiteralString) -> ...:
-              ...
-
-          query("SELECT * FROM table")  # ok
-          query(f"SELECT * FROM {input()}")  # not ok
-
-        See PEP 675 for details.
-
-        """
-        raise TypeError(f"{self} is not subscriptable")
-
-
-if hasattr(typing, "Self"):
-    Self = typing.Self
-else:
-    @_SpecialForm
-    def Self(self, params):
-        """Used to spell the type of "self" in classes.
-
-        Example::
-
-          from typing import Self
-
-          class ReturnsSelf:
-              def parse(self, data: bytes) -> Self:
-                  ...
-                  return self
-
-        """
-
-        raise TypeError(f"{self} is not subscriptable")
-
-
-if hasattr(typing, "Never"):
-    Never = typing.Never
-else:
-    @_SpecialForm
-    def Never(self, params):
-        """The bottom type, a type that has no members.
-
-        This can be used to define a function that should never be
-        called, or a function that never returns::
-
-            from typing_extensions import Never
-
-            def never_call_me(arg: Never) -> None:
-                pass
-
-            def int_or_str(arg: int | str) -> None:
-                never_call_me(arg)  # type checker error
-                match arg:
-                    case int():
-                        print("It's an int")
-                    case str():
-                        print("It's a str")
-                    case _:
-                        never_call_me(arg)  # ok, arg is of type Never
-
-        """
-
-        raise TypeError(f"{self} is not subscriptable")
-
-
-if hasattr(typing, 'Required'):
-    Required = typing.Required
-    NotRequired = typing.NotRequired
-elif sys.version_info[:2] >= (3, 9):
-    class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-    @_ExtensionsSpecialForm
-    def Required(self, parameters):
-        """A special typing construct to mark a key of a total=False TypedDict
-        as required. For example:
-
-            class Movie(TypedDict, total=False):
-                title: Required[str]
-                year: int
-
-            m = Movie(
-                title='The Matrix',  # typechecker error if key is omitted
-                year=1999,
-            )
-
-        There is no runtime checking that a required key is actually provided
-        when instantiating a related TypedDict.
-        """
-        item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
-        return typing._GenericAlias(self, (item,))
-
-    @_ExtensionsSpecialForm
-    def NotRequired(self, parameters):
-        """A special typing construct to mark a key of a TypedDict as
-        potentially missing. For example:
-
-            class Movie(TypedDict):
-                title: str
-                year: NotRequired[int]
-
-            m = Movie(
-                title='The Matrix',  # typechecker error if key is omitted
-                year=1999,
-            )
-        """
-        item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
-        return typing._GenericAlias(self, (item,))
-
-else:
-    class _RequiredForm(typing._SpecialForm, _root=True):
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-        def __getitem__(self, parameters):
-            item = typing._type_check(parameters,
-                                      f'{self._name} accepts only a single type.')
-            return typing._GenericAlias(self, (item,))
-
-    Required = _RequiredForm(
-        'Required',
-        doc="""A special typing construct to mark a key of a total=False TypedDict
-        as required. For example:
-
-            class Movie(TypedDict, total=False):
-                title: Required[str]
-                year: int
-
-            m = Movie(
-                title='The Matrix',  # typechecker error if key is omitted
-                year=1999,
-            )
-
-        There is no runtime checking that a required key is actually provided
-        when instantiating a related TypedDict.
-        """)
-    NotRequired = _RequiredForm(
-        'NotRequired',
-        doc="""A special typing construct to mark a key of a TypedDict as
-        potentially missing. For example:
-
-            class Movie(TypedDict):
-                title: str
-                year: NotRequired[int]
-
-            m = Movie(
-                title='The Matrix',  # typechecker error if key is omitted
-                year=1999,
-            )
-        """)
-
-
-if hasattr(typing, "Unpack"):  # 3.11+
-    Unpack = typing.Unpack
-elif sys.version_info[:2] >= (3, 9):
-    class _UnpackSpecialForm(typing._SpecialForm, _root=True):
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-    class _UnpackAlias(typing._GenericAlias, _root=True):
-        __class__ = typing.TypeVar
-
-    @_UnpackSpecialForm
-    def Unpack(self, parameters):
-        """A special typing construct to unpack a variadic type. For example:
-
-            Shape = TypeVarTuple('Shape')
-            Batch = NewType('Batch', int)
-
-            def add_batch_axis(
-                x: Array[Unpack[Shape]]
-            ) -> Array[Batch, Unpack[Shape]]: ...
-
-        """
-        item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
-        return _UnpackAlias(self, (item,))
-
-    def _is_unpack(obj):
-        return isinstance(obj, _UnpackAlias)
-
-else:
-    class _UnpackAlias(typing._GenericAlias, _root=True):
-        __class__ = typing.TypeVar
-
-    class _UnpackForm(typing._SpecialForm, _root=True):
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-        def __getitem__(self, parameters):
-            item = typing._type_check(parameters,
-                                      f'{self._name} accepts only a single type.')
-            return _UnpackAlias(self, (item,))
-
-    Unpack = _UnpackForm(
-        'Unpack',
-        doc="""A special typing construct to unpack a variadic type. For example:
-
-            Shape = TypeVarTuple('Shape')
-            Batch = NewType('Batch', int)
-
-            def add_batch_axis(
-                x: Array[Unpack[Shape]]
-            ) -> Array[Batch, Unpack[Shape]]: ...
-
-        """)
-
-    def _is_unpack(obj):
-        return isinstance(obj, _UnpackAlias)
-
-
-if hasattr(typing, "TypeVarTuple"):  # 3.11+
-
-    # Add default Parameter - PEP 696
-    class TypeVarTuple(typing.TypeVarTuple, _DefaultMixin, _root=True):
-        """Type variable tuple."""
-
-        def __init__(self, name, *, default=None):
-            super().__init__(name)
-            _DefaultMixin.__init__(self, default)
-
-            # for pickling:
-            try:
-                def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
-            except (AttributeError, ValueError):
-                def_mod = None
-            if def_mod != 'typing_extensions':
-                self.__module__ = def_mod
-
-else:
-    class TypeVarTuple(_DefaultMixin):
-        """Type variable tuple.
-
-        Usage::
-
-            Ts = TypeVarTuple('Ts')
-
-        In the same way that a normal type variable is a stand-in for a single
-        type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
-        type such as ``Tuple[int, str]``.
-
-        Type variable tuples can be used in ``Generic`` declarations.
-        Consider the following example::
-
-            class Array(Generic[*Ts]): ...
-
-        The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
-        where ``T1`` and ``T2`` are type variables. To use these type variables
-        as type parameters of ``Array``, we must *unpack* the type variable tuple using
-        the star operator: ``*Ts``. The signature of ``Array`` then behaves
-        as if we had simply written ``class Array(Generic[T1, T2]): ...``.
-        In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
-        us to parameterise the class with an *arbitrary* number of type parameters.
-
-        Type variable tuples can be used anywhere a normal ``TypeVar`` can.
-        This includes class definitions, as shown above, as well as function
-        signatures and variable annotations::
-
-            class Array(Generic[*Ts]):
-
-                def __init__(self, shape: Tuple[*Ts]):
-                    self._shape: Tuple[*Ts] = shape
-
-                def get_shape(self) -> Tuple[*Ts]:
-                    return self._shape
-
-            shape = (Height(480), Width(640))
-            x: Array[Height, Width] = Array(shape)
-            y = abs(x)  # Inferred type is Array[Height, Width]
-            z = x + x   #        ...    is Array[Height, Width]
-            x.get_shape()  #     ...    is tuple[Height, Width]
-
-        """
-
-        # Trick Generic __parameters__.
-        __class__ = typing.TypeVar
-
-        def __iter__(self):
-            yield self.__unpacked__
-
-        def __init__(self, name, *, default=None):
-            self.__name__ = name
-            _DefaultMixin.__init__(self, default)
-
-            # for pickling:
-            try:
-                def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
-            except (AttributeError, ValueError):
-                def_mod = None
-            if def_mod != 'typing_extensions':
-                self.__module__ = def_mod
-
-            self.__unpacked__ = Unpack[self]
-
-        def __repr__(self):
-            return self.__name__
-
-        def __hash__(self):
-            return object.__hash__(self)
-
-        def __eq__(self, other):
-            return self is other
-
-        def __reduce__(self):
-            return self.__name__
-
-        def __init_subclass__(self, *args, **kwds):
-            if '_root' not in kwds:
-                raise TypeError("Cannot subclass special typing classes")
-
-
-if hasattr(typing, "reveal_type"):
-    reveal_type = typing.reveal_type
-else:
-    def reveal_type(__obj: T) -> T:
-        """Reveal the inferred type of a variable.
-
-        When a static type checker encounters a call to ``reveal_type()``,
-        it will emit the inferred type of the argument::
-
-            x: int = 1
-            reveal_type(x)
-
-        Running a static type checker (e.g., ``mypy``) on this example
-        will produce output similar to 'Revealed type is "builtins.int"'.
-
-        At runtime, the function prints the runtime type of the
-        argument and returns it unchanged.
-
-        """
-        print(f"Runtime type is {type(__obj).__name__!r}", file=sys.stderr)
-        return __obj
-
-
-if hasattr(typing, "assert_never"):
-    assert_never = typing.assert_never
-else:
-    def assert_never(__arg: Never) -> Never:
-        """Assert to the type checker that a line of code is unreachable.
-
-        Example::
-
-            def int_or_str(arg: int | str) -> None:
-                match arg:
-                    case int():
-                        print("It's an int")
-                    case str():
-                        print("It's a str")
-                    case _:
-                        assert_never(arg)
-
-        If a type checker finds that a call to assert_never() is
-        reachable, it will emit an error.
-
-        At runtime, this throws an exception when called.
-
-        """
-        raise AssertionError("Expected code to be unreachable")
-
-
-if hasattr(typing, 'dataclass_transform'):
-    dataclass_transform = typing.dataclass_transform
-else:
-    def dataclass_transform(
-        *,
-        eq_default: bool = True,
-        order_default: bool = False,
-        kw_only_default: bool = False,
-        field_specifiers: typing.Tuple[
-            typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],
-            ...
-        ] = (),
-        **kwargs: typing.Any,
-    ) -> typing.Callable[[T], T]:
-        """Decorator that marks a function, class, or metaclass as providing
-        dataclass-like behavior.
-
-        Example:
-
-            from typing_extensions import dataclass_transform
-
-            _T = TypeVar("_T")
-
-            # Used on a decorator function
-            @dataclass_transform()
-            def create_model(cls: type[_T]) -> type[_T]:
-                ...
-                return cls
-
-            @create_model
-            class CustomerModel:
-                id: int
-                name: str
-
-            # Used on a base class
-            @dataclass_transform()
-            class ModelBase: ...
-
-            class CustomerModel(ModelBase):
-                id: int
-                name: str
-
-            # Used on a metaclass
-            @dataclass_transform()
-            class ModelMeta(type): ...
-
-            class ModelBase(metaclass=ModelMeta): ...
-
-            class CustomerModel(ModelBase):
-                id: int
-                name: str
-
-        Each of the ``CustomerModel`` classes defined in this example will now
-        behave similarly to a dataclass created with the ``@dataclasses.dataclass``
-        decorator. For example, the type checker will synthesize an ``__init__``
-        method.
-
-        The arguments to this decorator can be used to customize this behavior:
-        - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
-          True or False if it is omitted by the caller.
-        - ``order_default`` indicates whether the ``order`` parameter is
-          assumed to be True or False if it is omitted by the caller.
-        - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
-          assumed to be True or False if it is omitted by the caller.
-        - ``field_specifiers`` specifies a static list of supported classes
-          or functions that describe fields, similar to ``dataclasses.field()``.
-
-        At runtime, this decorator records its arguments in the
-        ``__dataclass_transform__`` attribute on the decorated object.
-
-        See PEP 681 for details.
-
-        """
-        def decorator(cls_or_fn):
-            cls_or_fn.__dataclass_transform__ = {
-                "eq_default": eq_default,
-                "order_default": order_default,
-                "kw_only_default": kw_only_default,
-                "field_specifiers": field_specifiers,
-                "kwargs": kwargs,
-            }
-            return cls_or_fn
-        return decorator
-
-
-if hasattr(typing, "override"):
-    override = typing.override
-else:
-    _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
-
-    def override(__arg: _F) -> _F:
-        """Indicate that a method is intended to override a method in a base class.
-
-        Usage:
-
-            class Base:
-                def method(self) -> None: ...
-                    pass
-
-            class Child(Base):
-                @override
-                def method(self) -> None:
-                    super().method()
-
-        When this decorator is applied to a method, the type checker will
-        validate that it overrides a method with the same name on a base class.
-        This helps prevent bugs that may occur when a base class is changed
-        without an equivalent change to a child class.
-
-        See PEP 698 for details.
-
-        """
-        return __arg
-
-
-# We have to do some monkey patching to deal with the dual nature of
-# Unpack/TypeVarTuple:
-# - We want Unpack to be a kind of TypeVar so it gets accepted in
-#   Generic[Unpack[Ts]]
-# - We want it to *not* be treated as a TypeVar for the purposes of
-#   counting generic parameters, so that when we subscript a generic,
-#   the runtime doesn't try to substitute the Unpack with the subscripted type.
-if not hasattr(typing, "TypeVarTuple"):
-    typing._collect_type_vars = _collect_type_vars
-    typing._check_generic = _check_generic
-
-
-# Backport typing.NamedTuple as it exists in Python 3.11.
-# In 3.11, the ability to define generic `NamedTuple`s was supported.
-# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8.
-if sys.version_info >= (3, 11):
-    NamedTuple = typing.NamedTuple
-else:
-    def _caller():
-        try:
-            return sys._getframe(2).f_globals.get('__name__', '__main__')
-        except (AttributeError, ValueError):  # For platforms without _getframe()
-            return None
-
-    def _make_nmtuple(name, types, module, defaults=()):
-        fields = [n for n, t in types]
-        annotations = {n: typing._type_check(t, f"field {n} annotation must be a type")
-                       for n, t in types}
-        nm_tpl = collections.namedtuple(name, fields,
-                                        defaults=defaults, module=module)
-        nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations
-        # The `_field_types` attribute was removed in 3.9;
-        # in earlier versions, it is the same as the `__annotations__` attribute
-        if sys.version_info < (3, 9):
-            nm_tpl._field_types = annotations
-        return nm_tpl
-
-    _prohibited_namedtuple_fields = typing._prohibited
-    _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'})
-
-    class _NamedTupleMeta(type):
-        def __new__(cls, typename, bases, ns):
-            assert _NamedTuple in bases
-            for base in bases:
-                if base is not _NamedTuple and base is not typing.Generic:
-                    raise TypeError(
-                        'can only inherit from a NamedTuple type and Generic')
-            bases = tuple(tuple if base is _NamedTuple else base for base in bases)
-            types = ns.get('__annotations__', {})
-            default_names = []
-            for field_name in types:
-                if field_name in ns:
-                    default_names.append(field_name)
-                elif default_names:
-                    raise TypeError(f"Non-default namedtuple field {field_name} "
-                                    f"cannot follow default field"
-                                    f"{'s' if len(default_names) > 1 else ''} "
-                                    f"{', '.join(default_names)}")
-            nm_tpl = _make_nmtuple(
-                typename, types.items(),
-                defaults=[ns[n] for n in default_names],
-                module=ns['__module__']
-            )
-            nm_tpl.__bases__ = bases
-            if typing.Generic in bases:
-                class_getitem = typing.Generic.__class_getitem__.__func__
-                nm_tpl.__class_getitem__ = classmethod(class_getitem)
-            # update from user namespace without overriding special namedtuple attributes
-            for key in ns:
-                if key in _prohibited_namedtuple_fields:
-                    raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
-                elif key not in _special_namedtuple_fields and key not in nm_tpl._fields:
-                    setattr(nm_tpl, key, ns[key])
-            if typing.Generic in bases:
-                nm_tpl.__init_subclass__()
-            return nm_tpl
-
-    def NamedTuple(__typename, __fields=None, **kwargs):
-        if __fields is None:
-            __fields = kwargs.items()
-        elif kwargs:
-            raise TypeError("Either list of fields or keywords"
-                            " can be provided to NamedTuple, not both")
-        return _make_nmtuple(__typename, __fields, module=_caller())
-
-    NamedTuple.__doc__ = typing.NamedTuple.__doc__
-    _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {})
-
-    # On 3.8+, alter the signature so that it matches typing.NamedTuple.
-    # The signature of typing.NamedTuple on >=3.8 is invalid syntax in Python 3.7,
-    # so just leave the signature as it is on 3.7.
-    if sys.version_info >= (3, 8):
-        NamedTuple.__text_signature__ = '(typename, fields=None, /, **kwargs)'
-
-    def _namedtuple_mro_entries(bases):
-        assert NamedTuple in bases
-        return (_NamedTuple,)
-
-    NamedTuple.__mro_entries__ = _namedtuple_mro_entries
diff --git a/pkg_resources/_vendor/vendored.txt b/pkg_resources/_vendor/vendored.txt
deleted file mode 100644
index 4cd4ab8cb8..0000000000
--- a/pkg_resources/_vendor/vendored.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-packaging==23.1
-
-platformdirs==2.6.2
-# required for platformdirs on Python < 3.8
-typing_extensions==4.4.0
-
-jaraco.text==3.7.0
-# required for jaraco.text on older Pythons
-importlib_resources==5.10.2
-# required for importlib_resources on older Pythons
-zipp==3.7.0
diff --git a/pkg_resources/_vendor/zipp-3.7.0.dist-info/INSTALLER b/pkg_resources/_vendor/zipp-3.7.0.dist-info/INSTALLER
deleted file mode 100644
index a1b589e38a..0000000000
--- a/pkg_resources/_vendor/zipp-3.7.0.dist-info/INSTALLER
+++ /dev/null
@@ -1 +0,0 @@
-pip
diff --git a/pkg_resources/_vendor/zipp-3.7.0.dist-info/METADATA b/pkg_resources/_vendor/zipp-3.7.0.dist-info/METADATA
deleted file mode 100644
index b1308b5f6e..0000000000
--- a/pkg_resources/_vendor/zipp-3.7.0.dist-info/METADATA
+++ /dev/null
@@ -1,58 +0,0 @@
-Metadata-Version: 2.1
-Name: zipp
-Version: 3.7.0
-Summary: Backport of pathlib-compatible object wrapper for zip files
-Home-page: https://github.com/jaraco/zipp
-Author: Jason R. Coombs
-Author-email: jaraco@jaraco.com
-License: UNKNOWN
-Platform: UNKNOWN
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: MIT License
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3 :: Only
-Requires-Python: >=3.7
-License-File: LICENSE
-Provides-Extra: docs
-Requires-Dist: sphinx ; extra == 'docs'
-Requires-Dist: jaraco.packaging (>=8.2) ; extra == 'docs'
-Requires-Dist: rst.linker (>=1.9) ; extra == 'docs'
-Provides-Extra: testing
-Requires-Dist: pytest (>=6) ; extra == 'testing'
-Requires-Dist: pytest-checkdocs (>=2.4) ; extra == 'testing'
-Requires-Dist: pytest-flake8 ; extra == 'testing'
-Requires-Dist: pytest-cov ; extra == 'testing'
-Requires-Dist: pytest-enabler (>=1.0.1) ; extra == 'testing'
-Requires-Dist: jaraco.itertools ; extra == 'testing'
-Requires-Dist: func-timeout ; extra == 'testing'
-Requires-Dist: pytest-black (>=0.3.7) ; (platform_python_implementation != "PyPy") and extra == 'testing'
-Requires-Dist: pytest-mypy ; (platform_python_implementation != "PyPy") and extra == 'testing'
-
-.. image:: https://img.shields.io/pypi/v/zipp.svg
-   :target: `PyPI link`_
-
-.. image:: https://img.shields.io/pypi/pyversions/zipp.svg
-   :target: `PyPI link`_
-
-.. _PyPI link: https://pypi.org/project/zipp
-
-.. image:: https://github.com/jaraco/zipp/workflows/tests/badge.svg
-   :target: https://github.com/jaraco/zipp/actions?query=workflow%3A%22tests%22
-   :alt: tests
-
-.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
-   :target: https://github.com/psf/black
-   :alt: Code style: Black
-
-.. .. image:: https://readthedocs.org/projects/skeleton/badge/?version=latest
-..    :target: https://skeleton.readthedocs.io/en/latest/?badge=latest
-
-.. image:: https://img.shields.io/badge/skeleton-2021-informational
-   :target: https://blog.jaraco.com/skeleton
-
-
-A pathlib-compatible Zipfile object wrapper. Official backport of the standard library
-`Path object `_.
-
-
diff --git a/pkg_resources/_vendor/zipp-3.7.0.dist-info/RECORD b/pkg_resources/_vendor/zipp-3.7.0.dist-info/RECORD
deleted file mode 100644
index 0a88551ce0..0000000000
--- a/pkg_resources/_vendor/zipp-3.7.0.dist-info/RECORD
+++ /dev/null
@@ -1,9 +0,0 @@
-__pycache__/zipp.cpython-311.pyc,,
-zipp-3.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-zipp-3.7.0.dist-info/LICENSE,sha256=2z8CRrH5J48VhFuZ_sR4uLUG63ZIeZNyL4xuJUKF-vg,1050
-zipp-3.7.0.dist-info/METADATA,sha256=ZLzgaXTyZX_MxTU0lcGfhdPY4CjFrT_3vyQ2Fo49pl8,2261
-zipp-3.7.0.dist-info/RECORD,,
-zipp-3.7.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-zipp-3.7.0.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
-zipp-3.7.0.dist-info/top_level.txt,sha256=iAbdoSHfaGqBfVb2XuR9JqSQHCoOsOtG6y9C_LSpqFw,5
-zipp.py,sha256=ajztOH-9I7KA_4wqDYygtHa6xUBVZgFpmZ8FE74HHHI,8425
diff --git a/pkg_resources/_vendor/zipp.py b/pkg_resources/_vendor/zipp.py
deleted file mode 100644
index 26b723c1fd..0000000000
--- a/pkg_resources/_vendor/zipp.py
+++ /dev/null
@@ -1,329 +0,0 @@
-import io
-import posixpath
-import zipfile
-import itertools
-import contextlib
-import sys
-import pathlib
-
-if sys.version_info < (3, 7):
-    from collections import OrderedDict
-else:
-    OrderedDict = dict
-
-
-__all__ = ['Path']
-
-
-def _parents(path):
-    """
-    Given a path with elements separated by
-    posixpath.sep, generate all parents of that path.
-
-    >>> list(_parents('b/d'))
-    ['b']
-    >>> list(_parents('/b/d/'))
-    ['/b']
-    >>> list(_parents('b/d/f/'))
-    ['b/d', 'b']
-    >>> list(_parents('b'))
-    []
-    >>> list(_parents(''))
-    []
-    """
-    return itertools.islice(_ancestry(path), 1, None)
-
-
-def _ancestry(path):
-    """
-    Given a path with elements separated by
-    posixpath.sep, generate all elements of that path
-
-    >>> list(_ancestry('b/d'))
-    ['b/d', 'b']
-    >>> list(_ancestry('/b/d/'))
-    ['/b/d', '/b']
-    >>> list(_ancestry('b/d/f/'))
-    ['b/d/f', 'b/d', 'b']
-    >>> list(_ancestry('b'))
-    ['b']
-    >>> list(_ancestry(''))
-    []
-    """
-    path = path.rstrip(posixpath.sep)
-    while path and path != posixpath.sep:
-        yield path
-        path, tail = posixpath.split(path)
-
-
-_dedupe = OrderedDict.fromkeys
-"""Deduplicate an iterable in original order"""
-
-
-def _difference(minuend, subtrahend):
-    """
-    Return items in minuend not in subtrahend, retaining order
-    with O(1) lookup.
-    """
-    return itertools.filterfalse(set(subtrahend).__contains__, minuend)
-
-
-class CompleteDirs(zipfile.ZipFile):
-    """
-    A ZipFile subclass that ensures that implied directories
-    are always included in the namelist.
-    """
-
-    @staticmethod
-    def _implied_dirs(names):
-        parents = itertools.chain.from_iterable(map(_parents, names))
-        as_dirs = (p + posixpath.sep for p in parents)
-        return _dedupe(_difference(as_dirs, names))
-
-    def namelist(self):
-        names = super(CompleteDirs, self).namelist()
-        return names + list(self._implied_dirs(names))
-
-    def _name_set(self):
-        return set(self.namelist())
-
-    def resolve_dir(self, name):
-        """
-        If the name represents a directory, return that name
-        as a directory (with the trailing slash).
-        """
-        names = self._name_set()
-        dirname = name + '/'
-        dir_match = name not in names and dirname in names
-        return dirname if dir_match else name
-
-    @classmethod
-    def make(cls, source):
-        """
-        Given a source (filename or zipfile), return an
-        appropriate CompleteDirs subclass.
-        """
-        if isinstance(source, CompleteDirs):
-            return source
-
-        if not isinstance(source, zipfile.ZipFile):
-            return cls(_pathlib_compat(source))
-
-        # Only allow for FastLookup when supplied zipfile is read-only
-        if 'r' not in source.mode:
-            cls = CompleteDirs
-
-        source.__class__ = cls
-        return source
-
-
-class FastLookup(CompleteDirs):
-    """
-    ZipFile subclass to ensure implicit
-    dirs exist and are resolved rapidly.
-    """
-
-    def namelist(self):
-        with contextlib.suppress(AttributeError):
-            return self.__names
-        self.__names = super(FastLookup, self).namelist()
-        return self.__names
-
-    def _name_set(self):
-        with contextlib.suppress(AttributeError):
-            return self.__lookup
-        self.__lookup = super(FastLookup, self)._name_set()
-        return self.__lookup
-
-
-def _pathlib_compat(path):
-    """
-    For path-like objects, convert to a filename for compatibility
-    on Python 3.6.1 and earlier.
-    """
-    try:
-        return path.__fspath__()
-    except AttributeError:
-        return str(path)
-
-
-class Path:
-    """
-    A pathlib-compatible interface for zip files.
-
-    Consider a zip file with this structure::
-
-        .
-        ├── a.txt
-        └── b
-            ├── c.txt
-            └── d
-                └── e.txt
-
-    >>> data = io.BytesIO()
-    >>> zf = zipfile.ZipFile(data, 'w')
-    >>> zf.writestr('a.txt', 'content of a')
-    >>> zf.writestr('b/c.txt', 'content of c')
-    >>> zf.writestr('b/d/e.txt', 'content of e')
-    >>> zf.filename = 'mem/abcde.zip'
-
-    Path accepts the zipfile object itself or a filename
-
-    >>> root = Path(zf)
-
-    From there, several path operations are available.
-
-    Directory iteration (including the zip file itself):
-
-    >>> a, b = root.iterdir()
-    >>> a
-    Path('mem/abcde.zip', 'a.txt')
-    >>> b
-    Path('mem/abcde.zip', 'b/')
-
-    name property:
-
-    >>> b.name
-    'b'
-
-    join with divide operator:
-
-    >>> c = b / 'c.txt'
-    >>> c
-    Path('mem/abcde.zip', 'b/c.txt')
-    >>> c.name
-    'c.txt'
-
-    Read text:
-
-    >>> c.read_text()
-    'content of c'
-
-    existence:
-
-    >>> c.exists()
-    True
-    >>> (b / 'missing.txt').exists()
-    False
-
-    Coercion to string:
-
-    >>> import os
-    >>> str(c).replace(os.sep, posixpath.sep)
-    'mem/abcde.zip/b/c.txt'
-
-    At the root, ``name``, ``filename``, and ``parent``
-    resolve to the zipfile. Note these attributes are not
-    valid and will raise a ``ValueError`` if the zipfile
-    has no filename.
-
-    >>> root.name
-    'abcde.zip'
-    >>> str(root.filename).replace(os.sep, posixpath.sep)
-    'mem/abcde.zip'
-    >>> str(root.parent)
-    'mem'
-    """
-
-    __repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})"
-
-    def __init__(self, root, at=""):
-        """
-        Construct a Path from a ZipFile or filename.
-
-        Note: When the source is an existing ZipFile object,
-        its type (__class__) will be mutated to a
-        specialized type. If the caller wishes to retain the
-        original type, the caller should either create a
-        separate ZipFile object or pass a filename.
-        """
-        self.root = FastLookup.make(root)
-        self.at = at
-
-    def open(self, mode='r', *args, pwd=None, **kwargs):
-        """
-        Open this entry as text or binary following the semantics
-        of ``pathlib.Path.open()`` by passing arguments through
-        to io.TextIOWrapper().
-        """
-        if self.is_dir():
-            raise IsADirectoryError(self)
-        zip_mode = mode[0]
-        if not self.exists() and zip_mode == 'r':
-            raise FileNotFoundError(self)
-        stream = self.root.open(self.at, zip_mode, pwd=pwd)
-        if 'b' in mode:
-            if args or kwargs:
-                raise ValueError("encoding args invalid for binary operation")
-            return stream
-        return io.TextIOWrapper(stream, *args, **kwargs)
-
-    @property
-    def name(self):
-        return pathlib.Path(self.at).name or self.filename.name
-
-    @property
-    def suffix(self):
-        return pathlib.Path(self.at).suffix or self.filename.suffix
-
-    @property
-    def suffixes(self):
-        return pathlib.Path(self.at).suffixes or self.filename.suffixes
-
-    @property
-    def stem(self):
-        return pathlib.Path(self.at).stem or self.filename.stem
-
-    @property
-    def filename(self):
-        return pathlib.Path(self.root.filename).joinpath(self.at)
-
-    def read_text(self, *args, **kwargs):
-        with self.open('r', *args, **kwargs) as strm:
-            return strm.read()
-
-    def read_bytes(self):
-        with self.open('rb') as strm:
-            return strm.read()
-
-    def _is_child(self, path):
-        return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/")
-
-    def _next(self, at):
-        return self.__class__(self.root, at)
-
-    def is_dir(self):
-        return not self.at or self.at.endswith("/")
-
-    def is_file(self):
-        return self.exists() and not self.is_dir()
-
-    def exists(self):
-        return self.at in self.root._name_set()
-
-    def iterdir(self):
-        if not self.is_dir():
-            raise ValueError("Can't listdir a file")
-        subs = map(self._next, self.root.namelist())
-        return filter(self._is_child, subs)
-
-    def __str__(self):
-        return posixpath.join(self.root.filename, self.at)
-
-    def __repr__(self):
-        return self.__repr.format(self=self)
-
-    def joinpath(self, *other):
-        next = posixpath.join(self.at, *map(_pathlib_compat, other))
-        return self._next(self.root.resolve_dir(next))
-
-    __truediv__ = joinpath
-
-    @property
-    def parent(self):
-        if not self.at:
-            return self.filename.parent
-        parent_at = posixpath.dirname(self.at.rstrip('/'))
-        if parent_at:
-            parent_at += '/'
-        return self._next(parent_at)
diff --git a/pkg_resources/api_tests.txt b/pkg_resources/api_tests.txt
deleted file mode 100644
index d72b85aa37..0000000000
--- a/pkg_resources/api_tests.txt
+++ /dev/null
@@ -1,424 +0,0 @@
-Pluggable Distributions of Python Software
-==========================================
-
-Distributions
--------------
-
-A "Distribution" is a collection of files that represent a "Release" of a
-"Project" as of a particular point in time, denoted by a
-"Version"::
-
-    >>> import sys, pkg_resources
-    >>> from pkg_resources import Distribution
-    >>> Distribution(project_name="Foo", version="1.2")
-    Foo 1.2
-
-Distributions have a location, which can be a filename, URL, or really anything
-else you care to use::
-
-    >>> dist = Distribution(
-    ...     location="http://example.com/something",
-    ...     project_name="Bar", version="0.9"
-    ... )
-
-    >>> dist
-    Bar 0.9 (http://example.com/something)
-
-
-Distributions have various introspectable attributes::
-
-    >>> dist.location
-    'http://example.com/something'
-
-    >>> dist.project_name
-    'Bar'
-
-    >>> dist.version
-    '0.9'
-
-    >>> dist.py_version == '{}.{}'.format(*sys.version_info)
-    True
-
-    >>> print(dist.platform)
-    None
-
-Including various computed attributes::
-
-    >>> from pkg_resources import parse_version
-    >>> dist.parsed_version == parse_version(dist.version)
-    True
-
-    >>> dist.key    # case-insensitive form of the project name
-    'bar'
-
-Distributions are compared (and hashed) by version first::
-
-    >>> Distribution(version='1.0') == Distribution(version='1.0')
-    True
-    >>> Distribution(version='1.0') == Distribution(version='1.1')
-    False
-    >>> Distribution(version='1.0') <  Distribution(version='1.1')
-    True
-
-but also by project name (case-insensitive), platform, Python version,
-location, etc.::
-
-    >>> Distribution(project_name="Foo",version="1.0") == \
-    ... Distribution(project_name="Foo",version="1.0")
-    True
-
-    >>> Distribution(project_name="Foo",version="1.0") == \
-    ... Distribution(project_name="foo",version="1.0")
-    True
-
-    >>> Distribution(project_name="Foo",version="1.0") == \
-    ... Distribution(project_name="Foo",version="1.1")
-    False
-
-    >>> Distribution(project_name="Foo",py_version="2.3",version="1.0") == \
-    ... Distribution(project_name="Foo",py_version="2.4",version="1.0")
-    False
-
-    >>> Distribution(location="spam",version="1.0") == \
-    ... Distribution(location="spam",version="1.0")
-    True
-
-    >>> Distribution(location="spam",version="1.0") == \
-    ... Distribution(location="baz",version="1.0")
-    False
-
-
-
-Hash and compare distribution by prio/plat
-
-Get version from metadata
-provider capabilities
-egg_name()
-as_requirement()
-from_location, from_filename (w/path normalization)
-
-Releases may have zero or more "Requirements", which indicate
-what releases of another project the release requires in order to
-function.  A Requirement names the other project, expresses some criteria
-as to what releases of that project are acceptable, and lists any "Extras"
-that the requiring release may need from that project.  (An Extra is an
-optional feature of a Release, that can only be used if its additional
-Requirements are satisfied.)
-
-
-
-The Working Set
----------------
-
-A collection of active distributions is called a Working Set.  Note that a
-Working Set can contain any importable distribution, not just pluggable ones.
-For example, the Python standard library is an importable distribution that
-will usually be part of the Working Set, even though it is not pluggable.
-Similarly, when you are doing development work on a project, the files you are
-editing are also a Distribution.  (And, with a little attention to the
-directory names used,  and including some additional metadata, such a
-"development distribution" can be made pluggable as well.)
-
-    >>> from pkg_resources import WorkingSet
-
-A working set's entries are the sys.path entries that correspond to the active
-distributions.  By default, the working set's entries are the items on
-``sys.path``::
-
-    >>> ws = WorkingSet()
-    >>> ws.entries == sys.path
-    True
-
-But you can also create an empty working set explicitly, and add distributions
-to it::
-
-    >>> ws = WorkingSet([])
-    >>> ws.add(dist)
-    >>> ws.entries
-    ['http://example.com/something']
-    >>> dist in ws
-    True
-    >>> Distribution('foo',version="") in ws
-    False
-
-And you can iterate over its distributions::
-
-    >>> list(ws)
-    [Bar 0.9 (http://example.com/something)]
-
-Adding the same distribution more than once is a no-op::
-
-    >>> ws.add(dist)
-    >>> list(ws)
-    [Bar 0.9 (http://example.com/something)]
-
-For that matter, adding multiple distributions for the same project also does
-nothing, because a working set can only hold one active distribution per
-project -- the first one added to it::
-
-    >>> ws.add(
-    ...     Distribution(
-    ...         'http://example.com/something', project_name="Bar",
-    ...         version="7.2"
-    ...     )
-    ... )
-    >>> list(ws)
-    [Bar 0.9 (http://example.com/something)]
-
-You can append a path entry to a working set using ``add_entry()``::
-
-    >>> ws.entries
-    ['http://example.com/something']
-    >>> ws.add_entry(pkg_resources.__file__)
-    >>> ws.entries
-    ['http://example.com/something', '...pkg_resources...']
-
-Multiple additions result in multiple entries, even if the entry is already in
-the working set (because ``sys.path`` can contain the same entry more than
-once)::
-
-    >>> ws.add_entry(pkg_resources.__file__)
-    >>> ws.entries
-    ['...example.com...', '...pkg_resources...', '...pkg_resources...']
-
-And you can specify the path entry a distribution was found under, using the
-optional second parameter to ``add()``::
-
-    >>> ws = WorkingSet([])
-    >>> ws.add(dist,"foo")
-    >>> ws.entries
-    ['foo']
-
-But even if a distribution is found under multiple path entries, it still only
-shows up once when iterating the working set:
-
-    >>> ws.add_entry(ws.entries[0])
-    >>> list(ws)
-    [Bar 0.9 (http://example.com/something)]
-
-You can ask a WorkingSet to ``find()`` a distribution matching a requirement::
-
-    >>> from pkg_resources import Requirement
-    >>> print(ws.find(Requirement.parse("Foo==1.0")))   # no match, return None
-    None
-
-    >>> ws.find(Requirement.parse("Bar==0.9"))  # match, return distribution
-    Bar 0.9 (http://example.com/something)
-
-Note that asking for a conflicting version of a distribution already in a
-working set triggers a ``pkg_resources.VersionConflict`` error:
-
-    >>> try:
-    ...     ws.find(Requirement.parse("Bar==1.0"))
-    ... except pkg_resources.VersionConflict as exc:
-    ...     print(str(exc))
-    ... else:
-    ...     raise AssertionError("VersionConflict was not raised")
-    (Bar 0.9 (http://example.com/something), Requirement.parse('Bar==1.0'))
-
-You can subscribe a callback function to receive notifications whenever a new
-distribution is added to a working set.  The callback is immediately invoked
-once for each existing distribution in the working set, and then is called
-again for new distributions added thereafter::
-
-    >>> def added(dist): print("Added %s" % dist)
-    >>> ws.subscribe(added)
-    Added Bar 0.9
-    >>> foo12 = Distribution(project_name="Foo", version="1.2", location="f12")
-    >>> ws.add(foo12)
-    Added Foo 1.2
-
-Note, however, that only the first distribution added for a given project name
-will trigger a callback, even during the initial ``subscribe()`` callback::
-
-    >>> foo14 = Distribution(project_name="Foo", version="1.4", location="f14")
-    >>> ws.add(foo14)   # no callback, because Foo 1.2 is already active
-
-    >>> ws = WorkingSet([])
-    >>> ws.add(foo12)
-    >>> ws.add(foo14)
-    >>> ws.subscribe(added)
-    Added Foo 1.2
-
-And adding a callback more than once has no effect, either::
-
-    >>> ws.subscribe(added)     # no callbacks
-
-    # and no double-callbacks on subsequent additions, either
-    >>> just_a_test = Distribution(project_name="JustATest", version="0.99")
-    >>> ws.add(just_a_test)
-    Added JustATest 0.99
-
-
-Finding Plugins
----------------
-
-``WorkingSet`` objects can be used to figure out what plugins in an
-``Environment`` can be loaded without any resolution errors::
-
-    >>> from pkg_resources import Environment
-
-    >>> plugins = Environment([])   # normally, a list of plugin directories
-    >>> plugins.add(foo12)
-    >>> plugins.add(foo14)
-    >>> plugins.add(just_a_test)
-
-In the simplest case, we just get the newest version of each distribution in
-the plugin environment::
-
-    >>> ws = WorkingSet([])
-    >>> ws.find_plugins(plugins)
-    ([JustATest 0.99, Foo 1.4 (f14)], {})
-
-But if there's a problem with a version conflict or missing requirements, the
-method falls back to older versions, and the error info dict will contain an
-exception instance for each unloadable plugin::
-
-    >>> ws.add(foo12)   # this will conflict with Foo 1.4
-    >>> ws.find_plugins(plugins)
-    ([JustATest 0.99, Foo 1.2 (f12)], {Foo 1.4 (f14): VersionConflict(...)})
-
-But if you disallow fallbacks, the failed plugin will be skipped instead of
-trying older versions::
-
-    >>> ws.find_plugins(plugins, fallback=False)
-    ([JustATest 0.99], {Foo 1.4 (f14): VersionConflict(...)})
-
-
-
-Platform Compatibility Rules
-----------------------------
-
-On the Mac, there are potential compatibility issues for modules compiled
-on newer versions of macOS than what the user is running. Additionally,
-macOS will soon have two platforms to contend with: Intel and PowerPC.
-
-Basic equality works as on other platforms::
-
-    >>> from pkg_resources import compatible_platforms as cp
-    >>> reqd = 'macosx-10.4-ppc'
-    >>> cp(reqd, reqd)
-    True
-    >>> cp("win32", reqd)
-    False
-
-Distributions made on other machine types are not compatible::
-
-    >>> cp("macosx-10.4-i386", reqd)
-    False
-
-Distributions made on earlier versions of the OS are compatible, as
-long as they are from the same top-level version. The patchlevel version
-number does not matter::
-
-    >>> cp("macosx-10.4-ppc", reqd)
-    True
-    >>> cp("macosx-10.3-ppc", reqd)
-    True
-    >>> cp("macosx-10.5-ppc", reqd)
-    False
-    >>> cp("macosx-9.5-ppc", reqd)
-    False
-
-Backwards compatibility for packages made via earlier versions of
-setuptools is provided as well::
-
-    >>> cp("darwin-8.2.0-Power_Macintosh", reqd)
-    True
-    >>> cp("darwin-7.2.0-Power_Macintosh", reqd)
-    True
-    >>> cp("darwin-8.2.0-Power_Macintosh", "macosx-10.3-ppc")
-    False
-
-
-Environment Markers
--------------------
-
-    >>> from pkg_resources import invalid_marker as im, evaluate_marker as em
-    >>> import os
-
-    >>> print(im("sys_platform"))
-    Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in
-        sys_platform
-                    ^
-
-    >>> print(im("sys_platform=="))
-    Expected a marker variable or quoted string
-        sys_platform==
-                      ^
-
-    >>> print(im("sys_platform=='win32'"))
-    False
-
-    >>> print(im("sys=='x'"))
-    Expected a marker variable or quoted string
-        sys=='x'
-        ^
-
-    >>> print(im("(extra)"))
-    Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in
-        (extra)
-              ^
-
-    >>> print(im("(extra"))
-    Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in
-        (extra
-              ^
-
-    >>> print(im("os.open('foo')=='y'"))
-    Expected a marker variable or quoted string
-        os.open('foo')=='y'
-        ^
-
-    >>> print(im("'x'=='y' and os.open('foo')=='y'"))   # no short-circuit!
-    Expected a marker variable or quoted string
-        'x'=='y' and os.open('foo')=='y'
-                     ^
-
-    >>> print(im("'x'=='x' or os.open('foo')=='y'"))   # no short-circuit!
-    Expected a marker variable or quoted string
-        'x'=='x' or os.open('foo')=='y'
-                    ^
-
-    >>> print(im("r'x'=='x'"))
-    Expected a marker variable or quoted string
-        r'x'=='x'
-        ^
-
-    >>> print(im("'''x'''=='x'"))
-    Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in
-        '''x'''=='x'
-          ^
-
-    >>> print(im('"""x"""=="x"'))
-    Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in
-        """x"""=="x"
-          ^
-
-    >>> print(im(r"x\n=='x'"))
-    Expected a marker variable or quoted string
-        x\n=='x'
-        ^
-
-    >>> print(im("os.open=='y'"))
-    Expected a marker variable or quoted string
-        os.open=='y'
-        ^
-
-    >>> em("sys_platform=='win32'") == (sys.platform=='win32')
-    True
-
-    >>> em("python_version >= '2.7'")
-    True
-
-    >>> em("python_version > '2.6'")
-    True
-
-    >>> im("implementation_name=='cpython'")
-    False
-
-    >>> im("platform_python_implementation=='CPython'")
-    False
-
-    >>> im("implementation_version=='3.5.1'")
-    False
diff --git a/pkg_resources/extern/__init__.py b/pkg_resources/extern/__init__.py
deleted file mode 100644
index 948bcc6094..0000000000
--- a/pkg_resources/extern/__init__.py
+++ /dev/null
@@ -1,80 +0,0 @@
-import importlib.util
-import sys
-
-
-class VendorImporter:
-    """
-    A PEP 302 meta path importer for finding optionally-vendored
-    or otherwise naturally-installed packages from root_name.
-    """
-
-    def __init__(self, root_name, vendored_names=(), vendor_pkg=None):
-        self.root_name = root_name
-        self.vendored_names = set(vendored_names)
-        self.vendor_pkg = vendor_pkg or root_name.replace('extern', '_vendor')
-
-    @property
-    def search_path(self):
-        """
-        Search first the vendor package then as a natural package.
-        """
-        yield self.vendor_pkg + '.'
-        yield ''
-
-    def _module_matches_namespace(self, fullname):
-        """Figure out if the target module is vendored."""
-        root, base, target = fullname.partition(self.root_name + '.')
-        return not root and any(map(target.startswith, self.vendored_names))
-
-    def load_module(self, fullname):
-        """
-        Iterate over the search path to locate and load fullname.
-        """
-        root, base, target = fullname.partition(self.root_name + '.')
-        for prefix in self.search_path:
-            try:
-                extant = prefix + target
-                __import__(extant)
-                mod = sys.modules[extant]
-                sys.modules[fullname] = mod
-                return mod
-            except ImportError:
-                pass
-        else:
-            raise ImportError(
-                "The '{target}' package is required; "
-                "normally this is bundled with this package so if you get "
-                "this warning, consult the packager of your "
-                "distribution.".format(**locals())
-            )
-
-    def create_module(self, spec):
-        return self.load_module(spec.name)
-
-    def exec_module(self, module):
-        pass
-
-    def find_spec(self, fullname, path=None, target=None):
-        """Return a module spec for vendored names."""
-        return (
-            importlib.util.spec_from_loader(fullname, self)
-            if self._module_matches_namespace(fullname)
-            else None
-        )
-
-    def install(self):
-        """
-        Install this importer into sys.meta_path if not already present.
-        """
-        if self not in sys.meta_path:
-            sys.meta_path.append(self)
-
-
-names = (
-    'packaging',
-    'platformdirs',
-    'jaraco',
-    'importlib_resources',
-    'more_itertools',
-)
-VendorImporter(__name__, names).install()
diff --git a/pkg_resources/tests/__init__.py b/pkg_resources/tests/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/pkg_resources/tests/data/my-test-package-source/setup.cfg b/pkg_resources/tests/data/my-test-package-source/setup.cfg
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/pkg_resources/tests/data/my-test-package-source/setup.py b/pkg_resources/tests/data/my-test-package-source/setup.py
deleted file mode 100644
index ce9080640c..0000000000
--- a/pkg_resources/tests/data/my-test-package-source/setup.py
+++ /dev/null
@@ -1,7 +0,0 @@
-import setuptools
-
-setuptools.setup(
-    name="my-test-package",
-    version="1.0",
-    zip_safe=True,
-)
diff --git a/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip b/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip
deleted file mode 100644
index 81f9a0170f..0000000000
Binary files a/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip and /dev/null differ
diff --git a/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/PKG-INFO b/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/PKG-INFO
deleted file mode 100644
index 7328e3f7d1..0000000000
--- a/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/PKG-INFO
+++ /dev/null
@@ -1,10 +0,0 @@
-Metadata-Version: 1.0
-Name: my-test-package
-Version: 1.0
-Summary: UNKNOWN
-Home-page: UNKNOWN
-Author: UNKNOWN
-Author-email: UNKNOWN
-License: UNKNOWN
-Description: UNKNOWN
-Platform: UNKNOWN
diff --git a/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/SOURCES.txt b/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/SOURCES.txt
deleted file mode 100644
index 3c4ee1676d..0000000000
--- a/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/SOURCES.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-setup.cfg
-setup.py
-my_test_package.egg-info/PKG-INFO
-my_test_package.egg-info/SOURCES.txt
-my_test_package.egg-info/dependency_links.txt
-my_test_package.egg-info/top_level.txt
-my_test_package.egg-info/zip-safe
\ No newline at end of file
diff --git a/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/dependency_links.txt b/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/dependency_links.txt
deleted file mode 100644
index 8b13789179..0000000000
--- a/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/dependency_links.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/top_level.txt b/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/top_level.txt
deleted file mode 100644
index 8b13789179..0000000000
--- a/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/zip-safe b/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/zip-safe
deleted file mode 100644
index 8b13789179..0000000000
--- a/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/zip-safe
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/pkg_resources/tests/data/my-test-package_zipped-egg/my_test_package-1.0-py3.7.egg b/pkg_resources/tests/data/my-test-package_zipped-egg/my_test_package-1.0-py3.7.egg
deleted file mode 100644
index 5115b8957d..0000000000
Binary files a/pkg_resources/tests/data/my-test-package_zipped-egg/my_test_package-1.0-py3.7.egg and /dev/null differ
diff --git a/pkg_resources/tests/test_find_distributions.py b/pkg_resources/tests/test_find_distributions.py
deleted file mode 100644
index 4ffcdf3b58..0000000000
--- a/pkg_resources/tests/test_find_distributions.py
+++ /dev/null
@@ -1,44 +0,0 @@
-import py
-import pytest
-import pkg_resources
-
-
-TESTS_DATA_DIR = py.path.local(__file__).dirpath('data')
-
-
-class TestFindDistributions:
-    @pytest.fixture
-    def target_dir(self, tmpdir):
-        target_dir = tmpdir.mkdir('target')
-        # place a .egg named directory in the target that is not an egg:
-        target_dir.mkdir('not.an.egg')
-        return target_dir
-
-    def test_non_egg_dir_named_egg(self, target_dir):
-        dists = pkg_resources.find_distributions(str(target_dir))
-        assert not list(dists)
-
-    def test_standalone_egg_directory(self, target_dir):
-        (TESTS_DATA_DIR / 'my-test-package_unpacked-egg').copy(target_dir)
-        dists = pkg_resources.find_distributions(str(target_dir))
-        assert [dist.project_name for dist in dists] == ['my-test-package']
-        dists = pkg_resources.find_distributions(str(target_dir), only=True)
-        assert not list(dists)
-
-    def test_zipped_egg(self, target_dir):
-        (TESTS_DATA_DIR / 'my-test-package_zipped-egg').copy(target_dir)
-        dists = pkg_resources.find_distributions(str(target_dir))
-        assert [dist.project_name for dist in dists] == ['my-test-package']
-        dists = pkg_resources.find_distributions(str(target_dir), only=True)
-        assert not list(dists)
-
-    def test_zipped_sdist_one_level_removed(self, target_dir):
-        (TESTS_DATA_DIR / 'my-test-package-zip').copy(target_dir)
-        dists = pkg_resources.find_distributions(
-            str(target_dir / "my-test-package.zip")
-        )
-        assert [dist.project_name for dist in dists] == ['my-test-package']
-        dists = pkg_resources.find_distributions(
-            str(target_dir / "my-test-package.zip"), only=True
-        )
-        assert not list(dists)
diff --git a/pkg_resources/tests/test_markers.py b/pkg_resources/tests/test_markers.py
deleted file mode 100644
index 9306d5b348..0000000000
--- a/pkg_resources/tests/test_markers.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from unittest import mock
-
-from pkg_resources import evaluate_marker
-
-
-@mock.patch('platform.python_version', return_value='2.7.10')
-def test_ordering(python_version_mock):
-    assert evaluate_marker("python_full_version > '2.7.3'") is True
diff --git a/pkg_resources/tests/test_pkg_resources.py b/pkg_resources/tests/test_pkg_resources.py
deleted file mode 100644
index a05aeb2603..0000000000
--- a/pkg_resources/tests/test_pkg_resources.py
+++ /dev/null
@@ -1,417 +0,0 @@
-import sys
-import tempfile
-import os
-import zipfile
-import datetime
-import time
-import subprocess
-import stat
-import distutils.dist
-import distutils.command.install_egg_info
-
-from unittest import mock
-
-from pkg_resources import (
-    DistInfoDistribution,
-    Distribution,
-    EggInfoDistribution,
-)
-
-import pytest
-
-import pkg_resources
-
-
-def timestamp(dt):
-    """
-    Return a timestamp for a local, naive datetime instance.
-    """
-    try:
-        return dt.timestamp()
-    except AttributeError:
-        # Python 3.2 and earlier
-        return time.mktime(dt.timetuple())
-
-
-class EggRemover(str):
-    def __call__(self):
-        if self in sys.path:
-            sys.path.remove(self)
-        if os.path.exists(self):
-            os.remove(self)
-
-
-class TestZipProvider:
-    finalizers = []
-
-    ref_time = datetime.datetime(2013, 5, 12, 13, 25, 0)
-    "A reference time for a file modification"
-
-    @classmethod
-    def setup_class(cls):
-        "create a zip egg and add it to sys.path"
-        egg = tempfile.NamedTemporaryFile(suffix='.egg', delete=False)
-        zip_egg = zipfile.ZipFile(egg, 'w')
-        zip_info = zipfile.ZipInfo()
-        zip_info.filename = 'mod.py'
-        zip_info.date_time = cls.ref_time.timetuple()
-        zip_egg.writestr(zip_info, 'x = 3\n')
-        zip_info = zipfile.ZipInfo()
-        zip_info.filename = 'data.dat'
-        zip_info.date_time = cls.ref_time.timetuple()
-        zip_egg.writestr(zip_info, 'hello, world!')
-        zip_info = zipfile.ZipInfo()
-        zip_info.filename = 'subdir/mod2.py'
-        zip_info.date_time = cls.ref_time.timetuple()
-        zip_egg.writestr(zip_info, 'x = 6\n')
-        zip_info = zipfile.ZipInfo()
-        zip_info.filename = 'subdir/data2.dat'
-        zip_info.date_time = cls.ref_time.timetuple()
-        zip_egg.writestr(zip_info, 'goodbye, world!')
-        zip_egg.close()
-        egg.close()
-
-        sys.path.append(egg.name)
-        subdir = os.path.join(egg.name, 'subdir')
-        sys.path.append(subdir)
-        cls.finalizers.append(EggRemover(subdir))
-        cls.finalizers.append(EggRemover(egg.name))
-
-    @classmethod
-    def teardown_class(cls):
-        for finalizer in cls.finalizers:
-            finalizer()
-
-    def test_resource_listdir(self):
-        import mod
-
-        zp = pkg_resources.ZipProvider(mod)
-
-        expected_root = ['data.dat', 'mod.py', 'subdir']
-        assert sorted(zp.resource_listdir('')) == expected_root
-
-        expected_subdir = ['data2.dat', 'mod2.py']
-        assert sorted(zp.resource_listdir('subdir')) == expected_subdir
-        assert sorted(zp.resource_listdir('subdir/')) == expected_subdir
-
-        assert zp.resource_listdir('nonexistent') == []
-        assert zp.resource_listdir('nonexistent/') == []
-
-        import mod2
-
-        zp2 = pkg_resources.ZipProvider(mod2)
-
-        assert sorted(zp2.resource_listdir('')) == expected_subdir
-
-        assert zp2.resource_listdir('subdir') == []
-        assert zp2.resource_listdir('subdir/') == []
-
-    def test_resource_filename_rewrites_on_change(self):
-        """
-        If a previous call to get_resource_filename has saved the file, but
-        the file has been subsequently mutated with different file of the
-        same size and modification time, it should not be overwritten on a
-        subsequent call to get_resource_filename.
-        """
-        import mod
-
-        manager = pkg_resources.ResourceManager()
-        zp = pkg_resources.ZipProvider(mod)
-        filename = zp.get_resource_filename(manager, 'data.dat')
-        actual = datetime.datetime.fromtimestamp(os.stat(filename).st_mtime)
-        assert actual == self.ref_time
-        f = open(filename, 'w')
-        f.write('hello, world?')
-        f.close()
-        ts = timestamp(self.ref_time)
-        os.utime(filename, (ts, ts))
-        filename = zp.get_resource_filename(manager, 'data.dat')
-        with open(filename) as f:
-            assert f.read() == 'hello, world!'
-        manager.cleanup_resources()
-
-
-class TestResourceManager:
-    def test_get_cache_path(self):
-        mgr = pkg_resources.ResourceManager()
-        path = mgr.get_cache_path('foo')
-        type_ = str(type(path))
-        message = "Unexpected type from get_cache_path: " + type_
-        assert isinstance(path, str), message
-
-    def test_get_cache_path_race(self, tmpdir):
-        # Patch to os.path.isdir to create a race condition
-        def patched_isdir(dirname, unpatched_isdir=pkg_resources.isdir):
-            patched_isdir.dirnames.append(dirname)
-
-            was_dir = unpatched_isdir(dirname)
-            if not was_dir:
-                os.makedirs(dirname)
-            return was_dir
-
-        patched_isdir.dirnames = []
-
-        # Get a cache path with a "race condition"
-        mgr = pkg_resources.ResourceManager()
-        mgr.set_extraction_path(str(tmpdir))
-
-        archive_name = os.sep.join(('foo', 'bar', 'baz'))
-        with mock.patch.object(pkg_resources, 'isdir', new=patched_isdir):
-            mgr.get_cache_path(archive_name)
-
-        # Because this test relies on the implementation details of this
-        # function, these assertions are a sentinel to ensure that the
-        # test suite will not fail silently if the implementation changes.
-        called_dirnames = patched_isdir.dirnames
-        assert len(called_dirnames) == 2
-        assert called_dirnames[0].split(os.sep)[-2:] == ['foo', 'bar']
-        assert called_dirnames[1].split(os.sep)[-1:] == ['foo']
-
-    """
-    Tests to ensure that pkg_resources runs independently from setuptools.
-    """
-
-    def test_setuptools_not_imported(self):
-        """
-        In a separate Python environment, import pkg_resources and assert
-        that action doesn't cause setuptools to be imported.
-        """
-        lines = (
-            'import pkg_resources',
-            'import sys',
-            ('assert "setuptools" not in sys.modules, ' '"setuptools was imported"'),
-        )
-        cmd = [sys.executable, '-c', '; '.join(lines)]
-        subprocess.check_call(cmd)
-
-
-def make_test_distribution(metadata_path, metadata):
-    """
-    Make a test Distribution object, and return it.
-
-    :param metadata_path: the path to the metadata file that should be
-        created. This should be inside a distribution directory that should
-        also be created. For example, an argument value might end with
-        ".dist-info/METADATA".
-    :param metadata: the desired contents of the metadata file, as bytes.
-    """
-    dist_dir = os.path.dirname(metadata_path)
-    os.mkdir(dist_dir)
-    with open(metadata_path, 'wb') as f:
-        f.write(metadata)
-    dists = list(pkg_resources.distributions_from_metadata(dist_dir))
-    (dist,) = dists
-
-    return dist
-
-
-def test_get_metadata__bad_utf8(tmpdir):
-    """
-    Test a metadata file with bytes that can't be decoded as utf-8.
-    """
-    filename = 'METADATA'
-    # Convert the tmpdir LocalPath object to a string before joining.
-    metadata_path = os.path.join(str(tmpdir), 'foo.dist-info', filename)
-    # Encode a non-ascii string with the wrong encoding (not utf-8).
-    metadata = 'née'.encode('iso-8859-1')
-    dist = make_test_distribution(metadata_path, metadata=metadata)
-
-    with pytest.raises(UnicodeDecodeError) as excinfo:
-        dist.get_metadata(filename)
-
-    exc = excinfo.value
-    actual = str(exc)
-    expected = (
-        # The error message starts with "'utf-8' codec ..." However, the
-        # spelling of "utf-8" can vary (e.g. "utf8") so we don't include it
-        "codec can't decode byte 0xe9 in position 1: "
-        'invalid continuation byte in METADATA file at path: '
-    )
-    assert expected in actual, 'actual: {}'.format(actual)
-    assert actual.endswith(metadata_path), 'actual: {}'.format(actual)
-
-
-def make_distribution_no_version(tmpdir, basename):
-    """
-    Create a distribution directory with no file containing the version.
-    """
-    dist_dir = tmpdir / basename
-    dist_dir.ensure_dir()
-    # Make the directory non-empty so distributions_from_metadata()
-    # will detect it and yield it.
-    dist_dir.join('temp.txt').ensure()
-
-    if sys.version_info < (3, 6):
-        dist_dir = str(dist_dir)
-
-    dists = list(pkg_resources.distributions_from_metadata(dist_dir))
-    assert len(dists) == 1
-    (dist,) = dists
-
-    return dist, dist_dir
-
-
-@pytest.mark.parametrize(
-    'suffix, expected_filename, expected_dist_type',
-    [
-        ('egg-info', 'PKG-INFO', EggInfoDistribution),
-        ('dist-info', 'METADATA', DistInfoDistribution),
-    ],
-)
-@pytest.mark.xfail(
-    sys.version_info[:2] == (3, 12) and sys.version_info.releaselevel != 'final',
-    reason="https://github.com/python/cpython/issues/103632",
-)
-def test_distribution_version_missing(
-    tmpdir, suffix, expected_filename, expected_dist_type
-):
-    """
-    Test Distribution.version when the "Version" header is missing.
-    """
-    basename = 'foo.{}'.format(suffix)
-    dist, dist_dir = make_distribution_no_version(tmpdir, basename)
-
-    expected_text = ("Missing 'Version:' header and/or {} file at path: ").format(
-        expected_filename
-    )
-    metadata_path = os.path.join(dist_dir, expected_filename)
-
-    # Now check the exception raised when the "version" attribute is accessed.
-    with pytest.raises(ValueError) as excinfo:
-        dist.version
-
-    err = str(excinfo.value)
-    # Include a string expression after the assert so the full strings
-    # will be visible for inspection on failure.
-    assert expected_text in err, str((expected_text, err))
-
-    # Also check the args passed to the ValueError.
-    msg, dist = excinfo.value.args
-    assert expected_text in msg
-    # Check that the message portion contains the path.
-    assert metadata_path in msg, str((metadata_path, msg))
-    assert type(dist) == expected_dist_type
-
-
-@pytest.mark.xfail(
-    sys.version_info[:2] == (3, 12) and sys.version_info.releaselevel != 'final',
-    reason="https://github.com/python/cpython/issues/103632",
-)
-def test_distribution_version_missing_undetected_path():
-    """
-    Test Distribution.version when the "Version" header is missing and
-    the path can't be detected.
-    """
-    # Create a Distribution object with no metadata argument, which results
-    # in an empty metadata provider.
-    dist = Distribution('/foo')
-    with pytest.raises(ValueError) as excinfo:
-        dist.version
-
-    msg, dist = excinfo.value.args
-    expected = (
-        "Missing 'Version:' header and/or PKG-INFO file at path: " '[could not detect]'
-    )
-    assert msg == expected
-
-
-@pytest.mark.parametrize('only', [False, True])
-def test_dist_info_is_not_dir(tmp_path, only):
-    """Test path containing a file with dist-info extension."""
-    dist_info = tmp_path / 'foobar.dist-info'
-    dist_info.touch()
-    assert not pkg_resources.dist_factory(str(tmp_path), str(dist_info), only)
-
-
-class TestDeepVersionLookupDistutils:
-    @pytest.fixture
-    def env(self, tmpdir):
-        """
-        Create a package environment, similar to a virtualenv,
-        in which packages are installed.
-        """
-
-        class Environment(str):
-            pass
-
-        env = Environment(tmpdir)
-        tmpdir.chmod(stat.S_IRWXU)
-        subs = 'home', 'lib', 'scripts', 'data', 'egg-base'
-        env.paths = dict((dirname, str(tmpdir / dirname)) for dirname in subs)
-        list(map(os.mkdir, env.paths.values()))
-        return env
-
-    def create_foo_pkg(self, env, version):
-        """
-        Create a foo package installed (distutils-style) to env.paths['lib']
-        as version.
-        """
-        ld = "This package has unicode metadata! ❄"
-        attrs = dict(name='foo', version=version, long_description=ld)
-        dist = distutils.dist.Distribution(attrs)
-        iei_cmd = distutils.command.install_egg_info.install_egg_info(dist)
-        iei_cmd.initialize_options()
-        iei_cmd.install_dir = env.paths['lib']
-        iei_cmd.finalize_options()
-        iei_cmd.run()
-
-    def test_version_resolved_from_egg_info(self, env):
-        version = '1.11.0.dev0+2329eae'
-        self.create_foo_pkg(env, version)
-
-        # this requirement parsing will raise a VersionConflict unless the
-        # .egg-info file is parsed (see #419 on BitBucket)
-        req = pkg_resources.Requirement.parse('foo>=1.9')
-        dist = pkg_resources.WorkingSet([env.paths['lib']]).find(req)
-        assert dist.version == version
-
-    @pytest.mark.parametrize(
-        'unnormalized, normalized',
-        [
-            ('foo', 'foo'),
-            ('foo/', 'foo'),
-            ('foo/bar', 'foo/bar'),
-            ('foo/bar/', 'foo/bar'),
-        ],
-    )
-    def test_normalize_path_trailing_sep(self, unnormalized, normalized):
-        """Ensure the trailing slash is cleaned for path comparison.
-
-        See pypa/setuptools#1519.
-        """
-        result_from_unnormalized = pkg_resources.normalize_path(unnormalized)
-        result_from_normalized = pkg_resources.normalize_path(normalized)
-        assert result_from_unnormalized == result_from_normalized
-
-    @pytest.mark.skipif(
-        os.path.normcase('A') != os.path.normcase('a'),
-        reason='Testing case-insensitive filesystems.',
-    )
-    @pytest.mark.parametrize(
-        'unnormalized, normalized',
-        [
-            ('MiXeD/CasE', 'mixed/case'),
-        ],
-    )
-    def test_normalize_path_normcase(self, unnormalized, normalized):
-        """Ensure mixed case is normalized on case-insensitive filesystems."""
-        result_from_unnormalized = pkg_resources.normalize_path(unnormalized)
-        result_from_normalized = pkg_resources.normalize_path(normalized)
-        assert result_from_unnormalized == result_from_normalized
-
-    @pytest.mark.skipif(
-        os.path.sep != '\\',
-        reason='Testing systems using backslashes as path separators.',
-    )
-    @pytest.mark.parametrize(
-        'unnormalized, expected',
-        [
-            ('forward/slash', 'forward\\slash'),
-            ('forward/slash/', 'forward\\slash'),
-            ('backward\\slash\\', 'backward\\slash'),
-        ],
-    )
-    def test_normalize_path_backslash_sep(self, unnormalized, expected):
-        """Ensure path seps are cleaned on backslash path sep systems."""
-        result = pkg_resources.normalize_path(unnormalized)
-        assert result.endswith(expected)
diff --git a/pkg_resources/tests/test_resources.py b/pkg_resources/tests/test_resources.py
deleted file mode 100644
index 608c67aeeb..0000000000
--- a/pkg_resources/tests/test_resources.py
+++ /dev/null
@@ -1,881 +0,0 @@
-import os
-import sys
-import string
-import platform
-import itertools
-
-import pytest
-from pkg_resources.extern import packaging
-
-import pkg_resources
-from pkg_resources import (
-    parse_requirements,
-    VersionConflict,
-    parse_version,
-    Distribution,
-    EntryPoint,
-    Requirement,
-    safe_version,
-    safe_name,
-    WorkingSet,
-)
-
-
-# from Python 3.6 docs.
-def pairwise(iterable):
-    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
-    a, b = itertools.tee(iterable)
-    next(b, None)
-    return zip(a, b)
-
-
-class Metadata(pkg_resources.EmptyProvider):
-    """Mock object to return metadata as if from an on-disk distribution"""
-
-    def __init__(self, *pairs):
-        self.metadata = dict(pairs)
-
-    def has_metadata(self, name):
-        return name in self.metadata
-
-    def get_metadata(self, name):
-        return self.metadata[name]
-
-    def get_metadata_lines(self, name):
-        return pkg_resources.yield_lines(self.get_metadata(name))
-
-
-dist_from_fn = pkg_resources.Distribution.from_filename
-
-
-class TestDistro:
-    def testCollection(self):
-        # empty path should produce no distributions
-        ad = pkg_resources.Environment([], platform=None, python=None)
-        assert list(ad) == []
-        assert ad['FooPkg'] == []
-        ad.add(dist_from_fn("FooPkg-1.3_1.egg"))
-        ad.add(dist_from_fn("FooPkg-1.4-py2.4-win32.egg"))
-        ad.add(dist_from_fn("FooPkg-1.2-py2.4.egg"))
-
-        # Name is in there now
-        assert ad['FooPkg']
-        # But only 1 package
-        assert list(ad) == ['foopkg']
-
-        # Distributions sort by version
-        expected = ['1.4', '1.3-1', '1.2']
-        assert [dist.version for dist in ad['FooPkg']] == expected
-
-        # Removing a distribution leaves sequence alone
-        ad.remove(ad['FooPkg'][1])
-        assert [dist.version for dist in ad['FooPkg']] == ['1.4', '1.2']
-
-        # And inserting adds them in order
-        ad.add(dist_from_fn("FooPkg-1.9.egg"))
-        assert [dist.version for dist in ad['FooPkg']] == ['1.9', '1.4', '1.2']
-
-        ws = WorkingSet([])
-        foo12 = dist_from_fn("FooPkg-1.2-py2.4.egg")
-        foo14 = dist_from_fn("FooPkg-1.4-py2.4-win32.egg")
-        (req,) = parse_requirements("FooPkg>=1.3")
-
-        # Nominal case: no distros on path, should yield all applicable
-        assert ad.best_match(req, ws).version == '1.9'
-        # If a matching distro is already installed, should return only that
-        ws.add(foo14)
-        assert ad.best_match(req, ws).version == '1.4'
-
-        # If the first matching distro is unsuitable, it's a version conflict
-        ws = WorkingSet([])
-        ws.add(foo12)
-        ws.add(foo14)
-        with pytest.raises(VersionConflict):
-            ad.best_match(req, ws)
-
-        # If more than one match on the path, the first one takes precedence
-        ws = WorkingSet([])
-        ws.add(foo14)
-        ws.add(foo12)
-        ws.add(foo14)
-        assert ad.best_match(req, ws).version == '1.4'
-
-    def checkFooPkg(self, d):
-        assert d.project_name == "FooPkg"
-        assert d.key == "foopkg"
-        assert d.version == "1.3.post1"
-        assert d.py_version == "2.4"
-        assert d.platform == "win32"
-        assert d.parsed_version == parse_version("1.3-1")
-
-    def testDistroBasics(self):
-        d = Distribution(
-            "/some/path",
-            project_name="FooPkg",
-            version="1.3-1",
-            py_version="2.4",
-            platform="win32",
-        )
-        self.checkFooPkg(d)
-
-        d = Distribution("/some/path")
-        assert d.py_version == '{}.{}'.format(*sys.version_info)
-        assert d.platform is None
-
-    def testDistroParse(self):
-        d = dist_from_fn("FooPkg-1.3.post1-py2.4-win32.egg")
-        self.checkFooPkg(d)
-        d = dist_from_fn("FooPkg-1.3.post1-py2.4-win32.egg-info")
-        self.checkFooPkg(d)
-
-    def testDistroMetadata(self):
-        d = Distribution(
-            "/some/path",
-            project_name="FooPkg",
-            py_version="2.4",
-            platform="win32",
-            metadata=Metadata(('PKG-INFO', "Metadata-Version: 1.0\nVersion: 1.3-1\n")),
-        )
-        self.checkFooPkg(d)
-
-    def distRequires(self, txt):
-        return Distribution("/foo", metadata=Metadata(('depends.txt', txt)))
-
-    def checkRequires(self, dist, txt, extras=()):
-        assert list(dist.requires(extras)) == list(parse_requirements(txt))
-
-    def testDistroDependsSimple(self):
-        for v in "Twisted>=1.5", "Twisted>=1.5\nZConfig>=2.0":
-            self.checkRequires(self.distRequires(v), v)
-
-    needs_object_dir = pytest.mark.skipif(
-        not hasattr(object, '__dir__'),
-        reason='object.__dir__ necessary for self.__dir__ implementation',
-    )
-
-    def test_distribution_dir(self):
-        d = pkg_resources.Distribution()
-        dir(d)
-
-    @needs_object_dir
-    def test_distribution_dir_includes_provider_dir(self):
-        d = pkg_resources.Distribution()
-        before = d.__dir__()
-        assert 'test_attr' not in before
-        d._provider.test_attr = None
-        after = d.__dir__()
-        assert len(after) == len(before) + 1
-        assert 'test_attr' in after
-
-    @needs_object_dir
-    def test_distribution_dir_ignores_provider_dir_leading_underscore(self):
-        d = pkg_resources.Distribution()
-        before = d.__dir__()
-        assert '_test_attr' not in before
-        d._provider._test_attr = None
-        after = d.__dir__()
-        assert len(after) == len(before)
-        assert '_test_attr' not in after
-
-    def testResolve(self):
-        ad = pkg_resources.Environment([])
-        ws = WorkingSet([])
-        # Resolving no requirements -> nothing to install
-        assert list(ws.resolve([], ad)) == []
-        # Request something not in the collection -> DistributionNotFound
-        with pytest.raises(pkg_resources.DistributionNotFound):
-            ws.resolve(parse_requirements("Foo"), ad)
-
-        Foo = Distribution.from_filename(
-            "/foo_dir/Foo-1.2.egg",
-            metadata=Metadata(('depends.txt', "[bar]\nBaz>=2.0")),
-        )
-        ad.add(Foo)
-        ad.add(Distribution.from_filename("Foo-0.9.egg"))
-
-        # Request thing(s) that are available -> list to activate
-        for i in range(3):
-            targets = list(ws.resolve(parse_requirements("Foo"), ad))
-            assert targets == [Foo]
-            list(map(ws.add, targets))
-        with pytest.raises(VersionConflict):
-            ws.resolve(parse_requirements("Foo==0.9"), ad)
-        ws = WorkingSet([])  # reset
-
-        # Request an extra that causes an unresolved dependency for "Baz"
-        with pytest.raises(pkg_resources.DistributionNotFound):
-            ws.resolve(parse_requirements("Foo[bar]"), ad)
-        Baz = Distribution.from_filename(
-            "/foo_dir/Baz-2.1.egg", metadata=Metadata(('depends.txt', "Foo"))
-        )
-        ad.add(Baz)
-
-        # Activation list now includes resolved dependency
-        assert list(ws.resolve(parse_requirements("Foo[bar]"), ad)) == [Foo, Baz]
-        # Requests for conflicting versions produce VersionConflict
-        with pytest.raises(VersionConflict) as vc:
-            ws.resolve(parse_requirements("Foo==1.2\nFoo!=1.2"), ad)
-
-        msg = 'Foo 0.9 is installed but Foo==1.2 is required'
-        assert vc.value.report() == msg
-
-    def test_environment_marker_evaluation_negative(self):
-        """Environment markers are evaluated at resolution time."""
-        ad = pkg_resources.Environment([])
-        ws = WorkingSet([])
-        res = ws.resolve(parse_requirements("Foo;python_version<'2'"), ad)
-        assert list(res) == []
-
-    def test_environment_marker_evaluation_positive(self):
-        ad = pkg_resources.Environment([])
-        ws = WorkingSet([])
-        Foo = Distribution.from_filename("/foo_dir/Foo-1.2.dist-info")
-        ad.add(Foo)
-        res = ws.resolve(parse_requirements("Foo;python_version>='2'"), ad)
-        assert list(res) == [Foo]
-
-    def test_environment_marker_evaluation_called(self):
-        """
-        If one package foo requires bar without any extras,
-        markers should pass for bar without extras.
-        """
-        (parent_req,) = parse_requirements("foo")
-        (req,) = parse_requirements("bar;python_version>='2'")
-        req_extras = pkg_resources._ReqExtras({req: parent_req.extras})
-        assert req_extras.markers_pass(req)
-
-        (parent_req,) = parse_requirements("foo[]")
-        (req,) = parse_requirements("bar;python_version>='2'")
-        req_extras = pkg_resources._ReqExtras({req: parent_req.extras})
-        assert req_extras.markers_pass(req)
-
-    def test_marker_evaluation_with_extras(self):
-        """Extras are also evaluated as markers at resolution time."""
-        ad = pkg_resources.Environment([])
-        ws = WorkingSet([])
-        Foo = Distribution.from_filename(
-            "/foo_dir/Foo-1.2.dist-info",
-            metadata=Metadata(
-                (
-                    "METADATA",
-                    "Provides-Extra: baz\n" "Requires-Dist: quux; extra=='baz'",
-                )
-            ),
-        )
-        ad.add(Foo)
-        assert list(ws.resolve(parse_requirements("Foo"), ad)) == [Foo]
-        quux = Distribution.from_filename("/foo_dir/quux-1.0.dist-info")
-        ad.add(quux)
-        res = list(ws.resolve(parse_requirements("Foo[baz]"), ad))
-        assert res == [Foo, quux]
-
-    def test_marker_evaluation_with_extras_normlized(self):
-        """Extras are also evaluated as markers at resolution time."""
-        ad = pkg_resources.Environment([])
-        ws = WorkingSet([])
-        Foo = Distribution.from_filename(
-            "/foo_dir/Foo-1.2.dist-info",
-            metadata=Metadata(
-                (
-                    "METADATA",
-                    "Provides-Extra: baz-lightyear\n"
-                    "Requires-Dist: quux; extra=='baz-lightyear'",
-                )
-            ),
-        )
-        ad.add(Foo)
-        assert list(ws.resolve(parse_requirements("Foo"), ad)) == [Foo]
-        quux = Distribution.from_filename("/foo_dir/quux-1.0.dist-info")
-        ad.add(quux)
-        res = list(ws.resolve(parse_requirements("Foo[baz-lightyear]"), ad))
-        assert res == [Foo, quux]
-
-    def test_marker_evaluation_with_multiple_extras(self):
-        ad = pkg_resources.Environment([])
-        ws = WorkingSet([])
-        Foo = Distribution.from_filename(
-            "/foo_dir/Foo-1.2.dist-info",
-            metadata=Metadata(
-                (
-                    "METADATA",
-                    "Provides-Extra: baz\n"
-                    "Requires-Dist: quux; extra=='baz'\n"
-                    "Provides-Extra: bar\n"
-                    "Requires-Dist: fred; extra=='bar'\n",
-                )
-            ),
-        )
-        ad.add(Foo)
-        quux = Distribution.from_filename("/foo_dir/quux-1.0.dist-info")
-        ad.add(quux)
-        fred = Distribution.from_filename("/foo_dir/fred-0.1.dist-info")
-        ad.add(fred)
-        res = list(ws.resolve(parse_requirements("Foo[baz,bar]"), ad))
-        assert sorted(res) == [fred, quux, Foo]
-
-    def test_marker_evaluation_with_extras_loop(self):
-        ad = pkg_resources.Environment([])
-        ws = WorkingSet([])
-        a = Distribution.from_filename(
-            "/foo_dir/a-0.2.dist-info",
-            metadata=Metadata(("METADATA", "Requires-Dist: c[a]")),
-        )
-        b = Distribution.from_filename(
-            "/foo_dir/b-0.3.dist-info",
-            metadata=Metadata(("METADATA", "Requires-Dist: c[b]")),
-        )
-        c = Distribution.from_filename(
-            "/foo_dir/c-1.0.dist-info",
-            metadata=Metadata(
-                (
-                    "METADATA",
-                    "Provides-Extra: a\n"
-                    "Requires-Dist: b;extra=='a'\n"
-                    "Provides-Extra: b\n"
-                    "Requires-Dist: foo;extra=='b'",
-                )
-            ),
-        )
-        foo = Distribution.from_filename("/foo_dir/foo-0.1.dist-info")
-        for dist in (a, b, c, foo):
-            ad.add(dist)
-        res = list(ws.resolve(parse_requirements("a"), ad))
-        assert res == [a, c, b, foo]
-
-    @pytest.mark.xfail(
-        sys.version_info[:2] == (3, 12) and sys.version_info.releaselevel != 'final',
-        reason="https://github.com/python/cpython/issues/103632",
-    )
-    def testDistroDependsOptions(self):
-        d = self.distRequires(
-            """
-            Twisted>=1.5
-            [docgen]
-            ZConfig>=2.0
-            docutils>=0.3
-            [fastcgi]
-            fcgiapp>=0.1"""
-        )
-        self.checkRequires(d, "Twisted>=1.5")
-        self.checkRequires(
-            d, "Twisted>=1.5 ZConfig>=2.0 docutils>=0.3".split(), ["docgen"]
-        )
-        self.checkRequires(d, "Twisted>=1.5 fcgiapp>=0.1".split(), ["fastcgi"])
-        self.checkRequires(
-            d,
-            "Twisted>=1.5 ZConfig>=2.0 docutils>=0.3 fcgiapp>=0.1".split(),
-            ["docgen", "fastcgi"],
-        )
-        self.checkRequires(
-            d,
-            "Twisted>=1.5 fcgiapp>=0.1 ZConfig>=2.0 docutils>=0.3".split(),
-            ["fastcgi", "docgen"],
-        )
-        with pytest.raises(pkg_resources.UnknownExtra):
-            d.requires(["foo"])
-
-
-class TestWorkingSet:
-    def test_find_conflicting(self):
-        ws = WorkingSet([])
-        Foo = Distribution.from_filename("/foo_dir/Foo-1.2.egg")
-        ws.add(Foo)
-
-        # create a requirement that conflicts with Foo 1.2
-        req = next(parse_requirements("Foo<1.2"))
-
-        with pytest.raises(VersionConflict) as vc:
-            ws.find(req)
-
-        msg = 'Foo 1.2 is installed but Foo<1.2 is required'
-        assert vc.value.report() == msg
-
-    def test_resolve_conflicts_with_prior(self):
-        """
-        A ContextualVersionConflict should be raised when a requirement
-        conflicts with a prior requirement for a different package.
-        """
-        # Create installation where Foo depends on Baz 1.0 and Bar depends on
-        # Baz 2.0.
-        ws = WorkingSet([])
-        md = Metadata(('depends.txt', "Baz==1.0"))
-        Foo = Distribution.from_filename("/foo_dir/Foo-1.0.egg", metadata=md)
-        ws.add(Foo)
-        md = Metadata(('depends.txt', "Baz==2.0"))
-        Bar = Distribution.from_filename("/foo_dir/Bar-1.0.egg", metadata=md)
-        ws.add(Bar)
-        Baz = Distribution.from_filename("/foo_dir/Baz-1.0.egg")
-        ws.add(Baz)
-        Baz = Distribution.from_filename("/foo_dir/Baz-2.0.egg")
-        ws.add(Baz)
-
-        with pytest.raises(VersionConflict) as vc:
-            ws.resolve(parse_requirements("Foo\nBar\n"))
-
-        msg = "Baz 1.0 is installed but Baz==2.0 is required by "
-        msg += repr(set(['Bar']))
-        assert vc.value.report() == msg
-
-
-class TestEntryPoints:
-    def assertfields(self, ep):
-        assert ep.name == "foo"
-        assert ep.module_name == "pkg_resources.tests.test_resources"
-        assert ep.attrs == ("TestEntryPoints",)
-        assert ep.extras == ("x",)
-        assert ep.load() is TestEntryPoints
-        expect = "foo = pkg_resources.tests.test_resources:TestEntryPoints [x]"
-        assert str(ep) == expect
-
-    def setup_method(self, method):
-        self.dist = Distribution.from_filename(
-            "FooPkg-1.2-py2.4.egg", metadata=Metadata(('requires.txt', '[x]'))
-        )
-
-    def testBasics(self):
-        ep = EntryPoint(
-            "foo",
-            "pkg_resources.tests.test_resources",
-            ["TestEntryPoints"],
-            ["x"],
-            self.dist,
-        )
-        self.assertfields(ep)
-
-    def testParse(self):
-        s = "foo = pkg_resources.tests.test_resources:TestEntryPoints [x]"
-        ep = EntryPoint.parse(s, self.dist)
-        self.assertfields(ep)
-
-        ep = EntryPoint.parse("bar baz=  spammity[PING]")
-        assert ep.name == "bar baz"
-        assert ep.module_name == "spammity"
-        assert ep.attrs == ()
-        assert ep.extras == ("ping",)
-
-        ep = EntryPoint.parse(" fizzly =  wocka:foo")
-        assert ep.name == "fizzly"
-        assert ep.module_name == "wocka"
-        assert ep.attrs == ("foo",)
-        assert ep.extras == ()
-
-        # plus in the name
-        spec = "html+mako = mako.ext.pygmentplugin:MakoHtmlLexer"
-        ep = EntryPoint.parse(spec)
-        assert ep.name == 'html+mako'
-
-    reject_specs = "foo", "x=a:b:c", "q=x/na", "fez=pish:tush-z", "x=f[a]>2"
-
-    @pytest.mark.parametrize("reject_spec", reject_specs)
-    def test_reject_spec(self, reject_spec):
-        with pytest.raises(ValueError):
-            EntryPoint.parse(reject_spec)
-
-    def test_printable_name(self):
-        """
-        Allow any printable character in the name.
-        """
-        # Create a name with all printable characters; strip the whitespace.
-        name = string.printable.strip()
-        spec = "{name} = module:attr".format(**locals())
-        ep = EntryPoint.parse(spec)
-        assert ep.name == name
-
-    def checkSubMap(self, m):
-        assert len(m) == len(self.submap_expect)
-        for key, ep in self.submap_expect.items():
-            assert m.get(key).name == ep.name
-            assert m.get(key).module_name == ep.module_name
-            assert sorted(m.get(key).attrs) == sorted(ep.attrs)
-            assert sorted(m.get(key).extras) == sorted(ep.extras)
-
-    submap_expect = dict(
-        feature1=EntryPoint('feature1', 'somemodule', ['somefunction']),
-        feature2=EntryPoint(
-            'feature2', 'another.module', ['SomeClass'], ['extra1', 'extra2']
-        ),
-        feature3=EntryPoint('feature3', 'this.module', extras=['something']),
-    )
-    submap_str = """
-            # define features for blah blah
-            feature1 = somemodule:somefunction
-            feature2 = another.module:SomeClass [extra1,extra2]
-            feature3 = this.module [something]
-    """
-
-    def testParseList(self):
-        self.checkSubMap(EntryPoint.parse_group("xyz", self.submap_str))
-        with pytest.raises(ValueError):
-            EntryPoint.parse_group("x a", "foo=bar")
-        with pytest.raises(ValueError):
-            EntryPoint.parse_group("x", ["foo=baz", "foo=bar"])
-
-    def testParseMap(self):
-        m = EntryPoint.parse_map({'xyz': self.submap_str})
-        self.checkSubMap(m['xyz'])
-        assert list(m.keys()) == ['xyz']
-        m = EntryPoint.parse_map("[xyz]\n" + self.submap_str)
-        self.checkSubMap(m['xyz'])
-        assert list(m.keys()) == ['xyz']
-        with pytest.raises(ValueError):
-            EntryPoint.parse_map(["[xyz]", "[xyz]"])
-        with pytest.raises(ValueError):
-            EntryPoint.parse_map(self.submap_str)
-
-    def testDeprecationWarnings(self):
-        ep = EntryPoint(
-            "foo", "pkg_resources.tests.test_resources", ["TestEntryPoints"], ["x"]
-        )
-        with pytest.warns(pkg_resources.PkgResourcesDeprecationWarning):
-            ep.load(require=False)
-
-
-class TestRequirements:
-    def testBasics(self):
-        r = Requirement.parse("Twisted>=1.2")
-        assert str(r) == "Twisted>=1.2"
-        assert repr(r) == "Requirement.parse('Twisted>=1.2')"
-        assert r == Requirement("Twisted>=1.2")
-        assert r == Requirement("twisTed>=1.2")
-        assert r != Requirement("Twisted>=2.0")
-        assert r != Requirement("Zope>=1.2")
-        assert r != Requirement("Zope>=3.0")
-        assert r != Requirement("Twisted[extras]>=1.2")
-
-    def testOrdering(self):
-        r1 = Requirement("Twisted==1.2c1,>=1.2")
-        r2 = Requirement("Twisted>=1.2,==1.2c1")
-        assert r1 == r2
-        assert str(r1) == str(r2)
-        assert str(r2) == "Twisted==1.2c1,>=1.2"
-        assert Requirement("Twisted") != Requirement(
-            "Twisted @ https://localhost/twisted.zip"
-        )
-
-    def testBasicContains(self):
-        r = Requirement("Twisted>=1.2")
-        foo_dist = Distribution.from_filename("FooPkg-1.3_1.egg")
-        twist11 = Distribution.from_filename("Twisted-1.1.egg")
-        twist12 = Distribution.from_filename("Twisted-1.2.egg")
-        assert parse_version('1.2') in r
-        assert parse_version('1.1') not in r
-        assert '1.2' in r
-        assert '1.1' not in r
-        assert foo_dist not in r
-        assert twist11 not in r
-        assert twist12 in r
-
-    def testOptionsAndHashing(self):
-        r1 = Requirement.parse("Twisted[foo,bar]>=1.2")
-        r2 = Requirement.parse("Twisted[bar,FOO]>=1.2")
-        assert r1 == r2
-        assert set(r1.extras) == set(("foo", "bar"))
-        assert set(r2.extras) == set(("foo", "bar"))
-        assert hash(r1) == hash(r2)
-        assert hash(r1) == hash(
-            (
-                "twisted",
-                None,
-                packaging.specifiers.SpecifierSet(">=1.2"),
-                frozenset(["foo", "bar"]),
-                None,
-            )
-        )
-        assert hash(
-            Requirement.parse("Twisted @ https://localhost/twisted.zip")
-        ) == hash(
-            (
-                "twisted",
-                "https://localhost/twisted.zip",
-                packaging.specifiers.SpecifierSet(),
-                frozenset(),
-                None,
-            )
-        )
-
-    def testVersionEquality(self):
-        r1 = Requirement.parse("foo==0.3a2")
-        r2 = Requirement.parse("foo!=0.3a4")
-        d = Distribution.from_filename
-
-        assert d("foo-0.3a4.egg") not in r1
-        assert d("foo-0.3a1.egg") not in r1
-        assert d("foo-0.3a4.egg") not in r2
-
-        assert d("foo-0.3a2.egg") in r1
-        assert d("foo-0.3a2.egg") in r2
-        assert d("foo-0.3a3.egg") in r2
-        assert d("foo-0.3a5.egg") in r2
-
-    def testSetuptoolsProjectName(self):
-        """
-        The setuptools project should implement the setuptools package.
-        """
-
-        assert Requirement.parse('setuptools').project_name == 'setuptools'
-        # setuptools 0.7 and higher means setuptools.
-        assert Requirement.parse('setuptools == 0.7').project_name == 'setuptools'
-        assert Requirement.parse('setuptools == 0.7a1').project_name == 'setuptools'
-        assert Requirement.parse('setuptools >= 0.7').project_name == 'setuptools'
-
-
-class TestParsing:
-    def testEmptyParse(self):
-        assert list(parse_requirements('')) == []
-
-    def testYielding(self):
-        for inp, out in [
-            ([], []),
-            ('x', ['x']),
-            ([[]], []),
-            (' x\n y', ['x', 'y']),
-            (['x\n\n', 'y'], ['x', 'y']),
-        ]:
-            assert list(pkg_resources.yield_lines(inp)) == out
-
-    def testSplitting(self):
-        sample = """
-                    x
-                    [Y]
-                    z
-
-                    a
-                    [b ]
-                    # foo
-                    c
-                    [ d]
-                    [q]
-                    v
-                    """
-        assert list(pkg_resources.split_sections(sample)) == [
-            (None, ["x"]),
-            ("Y", ["z", "a"]),
-            ("b", ["c"]),
-            ("d", []),
-            ("q", ["v"]),
-        ]
-        with pytest.raises(ValueError):
-            list(pkg_resources.split_sections("[foo"))
-
-    def testSafeName(self):
-        assert safe_name("adns-python") == "adns-python"
-        assert safe_name("WSGI Utils") == "WSGI-Utils"
-        assert safe_name("WSGI  Utils") == "WSGI-Utils"
-        assert safe_name("Money$$$Maker") == "Money-Maker"
-        assert safe_name("peak.web") != "peak-web"
-
-    def testSafeVersion(self):
-        assert safe_version("1.2-1") == "1.2.post1"
-        assert safe_version("1.2 alpha") == "1.2.alpha"
-        assert safe_version("2.3.4 20050521") == "2.3.4.20050521"
-        assert safe_version("Money$$$Maker") == "Money-Maker"
-        assert safe_version("peak.web") == "peak.web"
-
-    def testSimpleRequirements(self):
-        assert list(parse_requirements('Twis-Ted>=1.2-1')) == [
-            Requirement('Twis-Ted>=1.2-1')
-        ]
-        assert list(parse_requirements('Twisted >=1.2, \\ # more\n<2.0')) == [
-            Requirement('Twisted>=1.2,<2.0')
-        ]
-        assert Requirement.parse("FooBar==1.99a3") == Requirement("FooBar==1.99a3")
-        with pytest.raises(ValueError):
-            Requirement.parse(">=2.3")
-        with pytest.raises(ValueError):
-            Requirement.parse("x\\")
-        with pytest.raises(ValueError):
-            Requirement.parse("x==2 q")
-        with pytest.raises(ValueError):
-            Requirement.parse("X==1\nY==2")
-        with pytest.raises(ValueError):
-            Requirement.parse("#")
-
-    def test_requirements_with_markers(self):
-        assert Requirement.parse("foobar;os_name=='a'") == Requirement.parse(
-            "foobar;os_name=='a'"
-        )
-        assert Requirement.parse(
-            "name==1.1;python_version=='2.7'"
-        ) != Requirement.parse("name==1.1;python_version=='3.6'")
-        assert Requirement.parse(
-            "name==1.0;python_version=='2.7'"
-        ) != Requirement.parse("name==1.2;python_version=='2.7'")
-        assert Requirement.parse(
-            "name[foo]==1.0;python_version=='3.6'"
-        ) != Requirement.parse("name[foo,bar]==1.0;python_version=='3.6'")
-
-    def test_local_version(self):
-        (req,) = parse_requirements('foo==1.0+org1')
-
-    def test_spaces_between_multiple_versions(self):
-        (req,) = parse_requirements('foo>=1.0, <3')
-        (req,) = parse_requirements('foo >= 1.0, < 3')
-
-    @pytest.mark.parametrize(
-        ['lower', 'upper'],
-        [
-            ('1.2-rc1', '1.2rc1'),
-            ('0.4', '0.4.0'),
-            ('0.4.0.0', '0.4.0'),
-            ('0.4.0-0', '0.4-0'),
-            ('0post1', '0.0post1'),
-            ('0pre1', '0.0c1'),
-            ('0.0.0preview1', '0c1'),
-            ('0.0c1', '0-rc1'),
-            ('1.2a1', '1.2.a.1'),
-            ('1.2.a', '1.2a'),
-        ],
-    )
-    def testVersionEquality(self, lower, upper):
-        assert parse_version(lower) == parse_version(upper)
-
-    torture = """
-        0.80.1-3 0.80.1-2 0.80.1-1 0.79.9999+0.80.0pre4-1
-        0.79.9999+0.80.0pre2-3 0.79.9999+0.80.0pre2-2
-        0.77.2-1 0.77.1-1 0.77.0-1
-        """
-
-    @pytest.mark.parametrize(
-        ['lower', 'upper'],
-        [
-            ('2.1', '2.1.1'),
-            ('2a1', '2b0'),
-            ('2a1', '2.1'),
-            ('2.3a1', '2.3'),
-            ('2.1-1', '2.1-2'),
-            ('2.1-1', '2.1.1'),
-            ('2.1', '2.1post4'),
-            ('2.1a0-20040501', '2.1'),
-            ('1.1', '02.1'),
-            ('3.2', '3.2.post0'),
-            ('3.2post1', '3.2post2'),
-            ('0.4', '4.0'),
-            ('0.0.4', '0.4.0'),
-            ('0post1', '0.4post1'),
-            ('2.1.0-rc1', '2.1.0'),
-            ('2.1dev', '2.1a0'),
-        ]
-        + list(pairwise(reversed(torture.split()))),
-    )
-    def testVersionOrdering(self, lower, upper):
-        assert parse_version(lower) < parse_version(upper)
-
-    def testVersionHashable(self):
-        """
-        Ensure that our versions stay hashable even though we've subclassed
-        them and added some shim code to them.
-        """
-        assert hash(parse_version("1.0")) == hash(parse_version("1.0"))
-
-
-class TestNamespaces:
-    ns_str = "__import__('pkg_resources').declare_namespace(__name__)\n"
-
-    @pytest.fixture
-    def symlinked_tmpdir(self, tmpdir):
-        """
-        Where available, return the tempdir as a symlink,
-        which as revealed in #231 is more fragile than
-        a natural tempdir.
-        """
-        if not hasattr(os, 'symlink'):
-            yield str(tmpdir)
-            return
-
-        link_name = str(tmpdir) + '-linked'
-        os.symlink(str(tmpdir), link_name)
-        try:
-            yield type(tmpdir)(link_name)
-        finally:
-            os.unlink(link_name)
-
-    @pytest.fixture(autouse=True)
-    def patched_path(self, tmpdir):
-        """
-        Patch sys.path to include the 'site-pkgs' dir. Also
-        restore pkg_resources._namespace_packages to its
-        former state.
-        """
-        saved_ns_pkgs = pkg_resources._namespace_packages.copy()
-        saved_sys_path = sys.path[:]
-        site_pkgs = tmpdir.mkdir('site-pkgs')
-        sys.path.append(str(site_pkgs))
-        try:
-            yield
-        finally:
-            pkg_resources._namespace_packages = saved_ns_pkgs
-            sys.path = saved_sys_path
-
-    issue591 = pytest.mark.xfail(platform.system() == 'Windows', reason="#591")
-
-    @issue591
-    def test_two_levels_deep(self, symlinked_tmpdir):
-        """
-        Test nested namespace packages
-        Create namespace packages in the following tree :
-            site-packages-1/pkg1/pkg2
-            site-packages-2/pkg1/pkg2
-        Check both are in the _namespace_packages dict and that their __path__
-        is correct
-        """
-        real_tmpdir = symlinked_tmpdir.realpath()
-        tmpdir = symlinked_tmpdir
-        sys.path.append(str(tmpdir / 'site-pkgs2'))
-        site_dirs = tmpdir / 'site-pkgs', tmpdir / 'site-pkgs2'
-        for site in site_dirs:
-            pkg1 = site / 'pkg1'
-            pkg2 = pkg1 / 'pkg2'
-            pkg2.ensure_dir()
-            (pkg1 / '__init__.py').write_text(self.ns_str, encoding='utf-8')
-            (pkg2 / '__init__.py').write_text(self.ns_str, encoding='utf-8')
-        with pytest.warns(DeprecationWarning, match="pkg_resources.declare_namespace"):
-            import pkg1
-        assert "pkg1" in pkg_resources._namespace_packages
-        # attempt to import pkg2 from site-pkgs2
-        with pytest.warns(DeprecationWarning, match="pkg_resources.declare_namespace"):
-            import pkg1.pkg2
-        # check the _namespace_packages dict
-        assert "pkg1.pkg2" in pkg_resources._namespace_packages
-        assert pkg_resources._namespace_packages["pkg1"] == ["pkg1.pkg2"]
-        # check the __path__ attribute contains both paths
-        expected = [
-            str(real_tmpdir / "site-pkgs" / "pkg1" / "pkg2"),
-            str(real_tmpdir / "site-pkgs2" / "pkg1" / "pkg2"),
-        ]
-        assert pkg1.pkg2.__path__ == expected
-
-    @issue591
-    def test_path_order(self, symlinked_tmpdir):
-        """
-        Test that if multiple versions of the same namespace package subpackage
-        are on different sys.path entries, that only the one earliest on
-        sys.path is imported, and that the namespace package's __path__ is in
-        the correct order.
-
-        Regression test for https://github.com/pypa/setuptools/issues/207
-        """
-
-        tmpdir = symlinked_tmpdir
-        site_dirs = (
-            tmpdir / "site-pkgs",
-            tmpdir / "site-pkgs2",
-            tmpdir / "site-pkgs3",
-        )
-
-        vers_str = "__version__ = %r"
-
-        for number, site in enumerate(site_dirs, 1):
-            if number > 1:
-                sys.path.append(str(site))
-            nspkg = site / 'nspkg'
-            subpkg = nspkg / 'subpkg'
-            subpkg.ensure_dir()
-            (nspkg / '__init__.py').write_text(self.ns_str, encoding='utf-8')
-            (subpkg / '__init__.py').write_text(vers_str % number, encoding='utf-8')
-
-        with pytest.warns(DeprecationWarning, match="pkg_resources.declare_namespace"):
-            import nspkg.subpkg
-            import nspkg
-        expected = [str(site.realpath() / 'nspkg') for site in site_dirs]
-        assert nspkg.__path__ == expected
-        assert nspkg.subpkg.__version__ == 1
diff --git a/pkg_resources/tests/test_working_set.py b/pkg_resources/tests/test_working_set.py
deleted file mode 100644
index 435d3c6beb..0000000000
--- a/pkg_resources/tests/test_working_set.py
+++ /dev/null
@@ -1,501 +0,0 @@
-import inspect
-import re
-import textwrap
-import functools
-
-import pytest
-
-import pkg_resources
-
-from .test_resources import Metadata
-
-
-def strip_comments(s):
-    return '\n'.join(
-        line
-        for line in s.split('\n')
-        if line.strip() and not line.strip().startswith('#')
-    )
-
-
-def parse_distributions(s):
-    '''
-    Parse a series of distribution specs of the form:
-    {project_name}-{version}
-       [optional, indented requirements specification]
-
-    Example:
-
-        foo-0.2
-        bar-1.0
-          foo>=3.0
-          [feature]
-          baz
-
-    yield 2 distributions:
-        - project_name=foo, version=0.2
-        - project_name=bar, version=1.0,
-          requires=['foo>=3.0', 'baz; extra=="feature"']
-    '''
-    s = s.strip()
-    for spec in re.split(r'\n(?=[^\s])', s):
-        if not spec:
-            continue
-        fields = spec.split('\n', 1)
-        assert 1 <= len(fields) <= 2
-        name, version = fields.pop(0).rsplit('-', 1)
-        if fields:
-            requires = textwrap.dedent(fields.pop(0))
-            metadata = Metadata(('requires.txt', requires))
-        else:
-            metadata = None
-        dist = pkg_resources.Distribution(
-            project_name=name, version=version, metadata=metadata
-        )
-        yield dist
-
-
-class FakeInstaller:
-    def __init__(self, installable_dists):
-        self._installable_dists = installable_dists
-
-    def __call__(self, req):
-        return next(
-            iter(filter(lambda dist: dist in req, self._installable_dists)), None
-        )
-
-
-def parametrize_test_working_set_resolve(*test_list):
-    idlist = []
-    argvalues = []
-    for test in test_list:
-        (
-            name,
-            installed_dists,
-            installable_dists,
-            requirements,
-            expected1,
-            expected2,
-        ) = [
-            strip_comments(s.lstrip())
-            for s in textwrap.dedent(test).lstrip().split('\n\n', 5)
-        ]
-        installed_dists = list(parse_distributions(installed_dists))
-        installable_dists = list(parse_distributions(installable_dists))
-        requirements = list(pkg_resources.parse_requirements(requirements))
-        for id_, replace_conflicting, expected in (
-            (name, False, expected1),
-            (name + '_replace_conflicting', True, expected2),
-        ):
-            idlist.append(id_)
-            expected = strip_comments(expected.strip())
-            if re.match(r'\w+$', expected):
-                expected = getattr(pkg_resources, expected)
-                assert issubclass(expected, Exception)
-            else:
-                expected = list(parse_distributions(expected))
-            argvalues.append(
-                pytest.param(
-                    installed_dists,
-                    installable_dists,
-                    requirements,
-                    replace_conflicting,
-                    expected,
-                )
-            )
-    return pytest.mark.parametrize(
-        'installed_dists,installable_dists,'
-        'requirements,replace_conflicting,'
-        'resolved_dists_or_exception',
-        argvalues,
-        ids=idlist,
-    )
-
-
-@parametrize_test_working_set_resolve(
-    '''
-    # id
-    noop
-
-    # installed
-
-    # installable
-
-    # wanted
-
-    # resolved
-
-    # resolved [replace conflicting]
-    ''',
-    '''
-    # id
-    already_installed
-
-    # installed
-    foo-3.0
-
-    # installable
-
-    # wanted
-    foo>=2.1,!=3.1,<4
-
-    # resolved
-    foo-3.0
-
-    # resolved [replace conflicting]
-    foo-3.0
-    ''',
-    '''
-    # id
-    installable_not_installed
-
-    # installed
-
-    # installable
-    foo-3.0
-    foo-4.0
-
-    # wanted
-    foo>=2.1,!=3.1,<4
-
-    # resolved
-    foo-3.0
-
-    # resolved [replace conflicting]
-    foo-3.0
-    ''',
-    '''
-    # id
-    not_installable
-
-    # installed
-
-    # installable
-
-    # wanted
-    foo>=2.1,!=3.1,<4
-
-    # resolved
-    DistributionNotFound
-
-    # resolved [replace conflicting]
-    DistributionNotFound
-    ''',
-    '''
-    # id
-    no_matching_version
-
-    # installed
-
-    # installable
-    foo-3.1
-
-    # wanted
-    foo>=2.1,!=3.1,<4
-
-    # resolved
-    DistributionNotFound
-
-    # resolved [replace conflicting]
-    DistributionNotFound
-    ''',
-    '''
-    # id
-    installable_with_installed_conflict
-
-    # installed
-    foo-3.1
-
-    # installable
-    foo-3.5
-
-    # wanted
-    foo>=2.1,!=3.1,<4
-
-    # resolved
-    VersionConflict
-
-    # resolved [replace conflicting]
-    foo-3.5
-    ''',
-    '''
-    # id
-    not_installable_with_installed_conflict
-
-    # installed
-    foo-3.1
-
-    # installable
-
-    # wanted
-    foo>=2.1,!=3.1,<4
-
-    # resolved
-    VersionConflict
-
-    # resolved [replace conflicting]
-    DistributionNotFound
-    ''',
-    '''
-    # id
-    installed_with_installed_require
-
-    # installed
-    foo-3.9
-    baz-0.1
-        foo>=2.1,!=3.1,<4
-
-    # installable
-
-    # wanted
-    baz
-
-    # resolved
-    foo-3.9
-    baz-0.1
-
-    # resolved [replace conflicting]
-    foo-3.9
-    baz-0.1
-    ''',
-    '''
-    # id
-    installed_with_conflicting_installed_require
-
-    # installed
-    foo-5
-    baz-0.1
-        foo>=2.1,!=3.1,<4
-
-    # installable
-
-    # wanted
-    baz
-
-    # resolved
-    VersionConflict
-
-    # resolved [replace conflicting]
-    DistributionNotFound
-    ''',
-    '''
-    # id
-    installed_with_installable_conflicting_require
-
-    # installed
-    foo-5
-    baz-0.1
-        foo>=2.1,!=3.1,<4
-
-    # installable
-    foo-2.9
-
-    # wanted
-    baz
-
-    # resolved
-    VersionConflict
-
-    # resolved [replace conflicting]
-    baz-0.1
-    foo-2.9
-    ''',
-    '''
-    # id
-    installed_with_installable_require
-
-    # installed
-    baz-0.1
-        foo>=2.1,!=3.1,<4
-
-    # installable
-    foo-3.9
-
-    # wanted
-    baz
-
-    # resolved
-    foo-3.9
-    baz-0.1
-
-    # resolved [replace conflicting]
-    foo-3.9
-    baz-0.1
-    ''',
-    '''
-    # id
-    installable_with_installed_require
-
-    # installed
-    foo-3.9
-
-    # installable
-    baz-0.1
-        foo>=2.1,!=3.1,<4
-
-    # wanted
-    baz
-
-    # resolved
-    foo-3.9
-    baz-0.1
-
-    # resolved [replace conflicting]
-    foo-3.9
-    baz-0.1
-    ''',
-    '''
-    # id
-    installable_with_installable_require
-
-    # installed
-
-    # installable
-    foo-3.9
-    baz-0.1
-        foo>=2.1,!=3.1,<4
-
-    # wanted
-    baz
-
-    # resolved
-    foo-3.9
-    baz-0.1
-
-    # resolved [replace conflicting]
-    foo-3.9
-    baz-0.1
-    ''',
-    '''
-    # id
-    installable_with_conflicting_installable_require
-
-    # installed
-    foo-5
-
-    # installable
-    foo-2.9
-    baz-0.1
-        foo>=2.1,!=3.1,<4
-
-    # wanted
-    baz
-
-    # resolved
-    VersionConflict
-
-    # resolved [replace conflicting]
-    baz-0.1
-    foo-2.9
-    ''',
-    '''
-    # id
-    conflicting_installables
-
-    # installed
-
-    # installable
-    foo-2.9
-    foo-5.0
-
-    # wanted
-    foo>=2.1,!=3.1,<4
-    foo>=4
-
-    # resolved
-    VersionConflict
-
-    # resolved [replace conflicting]
-    VersionConflict
-    ''',
-    '''
-    # id
-    installables_with_conflicting_requires
-
-    # installed
-
-    # installable
-    foo-2.9
-        dep==1.0
-    baz-5.0
-        dep==2.0
-    dep-1.0
-    dep-2.0
-
-    # wanted
-    foo
-    baz
-
-    # resolved
-    VersionConflict
-
-    # resolved [replace conflicting]
-    VersionConflict
-    ''',
-    '''
-    # id
-    installables_with_conflicting_nested_requires
-
-    # installed
-
-    # installable
-    foo-2.9
-        dep1
-    dep1-1.0
-        subdep<1.0
-    baz-5.0
-        dep2
-    dep2-1.0
-        subdep>1.0
-    subdep-0.9
-    subdep-1.1
-
-    # wanted
-    foo
-    baz
-
-    # resolved
-    VersionConflict
-
-    # resolved [replace conflicting]
-    VersionConflict
-    ''',
-    '''
-    # id
-    wanted_normalized_name_installed_canonical
-
-    # installed
-    foo.bar-3.6
-
-    # installable
-
-    # wanted
-    foo-bar==3.6
-
-    # resolved
-    foo.bar-3.6
-
-    # resolved [replace conflicting]
-    foo.bar-3.6
-    ''',
-)
-def test_working_set_resolve(
-    installed_dists,
-    installable_dists,
-    requirements,
-    replace_conflicting,
-    resolved_dists_or_exception,
-):
-    ws = pkg_resources.WorkingSet([])
-    list(map(ws.add, installed_dists))
-    resolve_call = functools.partial(
-        ws.resolve,
-        requirements,
-        installer=FakeInstaller(installable_dists),
-        replace_conflicting=replace_conflicting,
-    )
-    if inspect.isclass(resolved_dists_or_exception):
-        with pytest.raises(resolved_dists_or_exception):
-            resolve_call()
-    else:
-        assert sorted(resolve_call()) == sorted(resolved_dists_or_exception)
diff --git a/pyproject.toml b/pyproject.toml
index eae729c05a..bbfa0dd0ca 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,13 +1,222 @@
 [build-system]
-requires = []
+requires = [
+	# "setuptools>=77",
+	# "setuptools_scm[toml]>=3.4.1",
+	# jaraco/skeleton#174
+	# "coherent.licensed",
+]
 build-backend = "setuptools.build_meta"
 backend-path = ["."]
 
-[tool.black]
-skip-string-normalization = true
-extend_exclude = "_vendor"
+[project]
+name = "setuptools"
+version = "82.0.1"
+authors = [
+	{ name = "Python Packaging Authority", email = "distutils-sig@python.org" },
+]
+description = "Most extensible Python build backend with support for C/C++ extension modules"
+readme = "README.rst"
+classifiers = [
+	"Development Status :: 5 - Production/Stable",
+	"Intended Audience :: Developers",
+	"Programming Language :: Python :: 3",
+	"Programming Language :: Python :: 3 :: Only",
+	"Topic :: Software Development :: Libraries :: Python Modules",
+	"Topic :: System :: Archiving :: Packaging",
+	"Topic :: System :: Systems Administration",
+	"Topic :: Utilities",
+]
+requires-python = ">=3.10"
+license = "MIT"
+dependencies = [
+]
+keywords = ["CPAN PyPI distutils eggs package management"]
 
-[tool.setuptools_scm]
+[project.urls]
+Source = "https://github.com/pypa/setuptools"
+Documentation = "https://setuptools.pypa.io/"
+Changelog = "https://setuptools.pypa.io/en/stable/history.html"
+
+[project.optional-dependencies]
+test = [
+	# upstream
+	"pytest >= 6, != 8.1.*",
+
+	# local
+	"virtualenv>=13.0.0",
+	"wheel>=0.44.0", # Consistent requirement normalisation in METADATA (see #4547)
+	"pip>=19.1", # For proper file:// URLs support.
+	"packaging>=24.2",
+	"jaraco.envs>=2.2",
+	"pytest-xdist>=3", # Dropped dependency on pytest-fork and py
+	"jaraco.path>=3.7.2", # Typing fixes
+	"build[virtualenv]>=1.0.3",
+	"filelock>=3.4.0",
+	"ini2toml[lite]>=0.14",
+	"tomli-w>=1.0.0",
+	"pytest-timeout",
+	'pytest-perf; sys_platform != "cygwin"', # workaround for jaraco/inflect#195, pydantic/pydantic-core#773 (see #3986)
+	# for tools/finalize.py
+	'jaraco.develop >= 7.21; python_version >= "3.9" and sys_platform != "cygwin"',
+	"pytest-home >= 0.5",
+	"pytest-subprocess",
+
+	# workaround for pypa/pyproject-hooks#206
+	"pyproject-hooks!=1.1",
+
+	"jaraco.test>=5.5", # py.typed
+]
+
+doc = [
+	# upstream
+	"sphinx >= 3.5",
+	"jaraco.packaging >= 9.3",
+	"rst.linker >= 1.9",
+	"furo",
+	"sphinx-lint",
+
+	# tidelift
+	"jaraco.tidelift >= 1.4",
+
+	# local
+	"pygments-github-lexers==0.0.5",
+	"sphinx-favicon",
+	"sphinx-inline-tabs",
+	"sphinx-reredirects",
+	"sphinxcontrib-towncrier",
+	"sphinx-notfound-page >=1,<2",
+
+	# workaround for pypa/setuptools#4333
+	"pyproject-hooks!=1.1",
+
+	# workaround for sphinx-contrib/sphinxcontrib-towncrier#92
+	"towncrier<24.7",
+]
+ssl = []
+certs = []
+core = [
+	"packaging>=24.2",
+	"more_itertools>=8.8",
+	"jaraco.text>=3.7",
+	"importlib_metadata>=6; python_version < '3.10'",
+	"tomli>=2.0.1; python_version < '3.11'",
+	"wheel>=0.43.0",
+
+	# for distutils
+	"jaraco.functools >= 4",
+	"more_itertools",
+]
+
+check = [
+	# upstream
+	"pytest-checkdocs >= 2.14",
+	"pytest-ruff >= 0.2.1; sys_platform != 'cygwin'",
+
+	# local
+
+	# Deprecated rules must now be selected by exact rule code
+	"ruff >= 0.13.0; sys_platform != 'cygwin'",
+]
+
+cover = [
+	"pytest-cov",
+]
 
-[tool.pytest-enabler.mypy]
-# disabled
+enabler = [
+	"pytest-enabler >= 3.4",
+]
+
+type = [
+	# upstream
+	
+    # Exclude PyPy from type checks (python/mypy#20454 jaraco/skeleton#187)
+	"pytest-mypy >= 1.0.1; platform_python_implementation != 'PyPy'",
+
+	# local
+
+	# pin mypy version so a new version doesn't suddenly cause the CI to fail,
+	# until types-setuptools is removed from typeshed.
+	# For help with static-typing issues, or mypy update, ping @Avasam
+	"mypy==1.18.*",
+	# Typing fixes in version newer than we require at runtime
+	"importlib_metadata>=7.0.2; python_version < '3.10'",
+	# Imported unconditionally in tools/finalize.py
+	'jaraco.develop >= 7.21; sys_platform != "cygwin"',
+]
+
+
+[project.entry-points."distutils.commands"]
+alias = "setuptools.command.alias:alias"
+bdist_egg = "setuptools.command.bdist_egg:bdist_egg"
+bdist_rpm = "setuptools.command.bdist_rpm:bdist_rpm"
+bdist_wheel = "setuptools.command.bdist_wheel:bdist_wheel"
+build = "setuptools.command.build:build"
+build_clib = "setuptools.command.build_clib:build_clib"
+build_ext = "setuptools.command.build_ext:build_ext"
+build_py = "setuptools.command.build_py:build_py"
+develop = "setuptools.command.develop:develop"
+dist_info = "setuptools.command.dist_info:dist_info"
+easy_install = "setuptools.command.easy_install:easy_install"
+editable_wheel = "setuptools.command.editable_wheel:editable_wheel"
+egg_info = "setuptools.command.egg_info:egg_info"
+install = "setuptools.command.install:install"
+install_egg_info = "setuptools.command.install_egg_info:install_egg_info"
+install_lib = "setuptools.command.install_lib:install_lib"
+install_scripts = "setuptools.command.install_scripts:install_scripts"
+rotate = "setuptools.command.rotate:rotate"
+saveopts = "setuptools.command.saveopts:saveopts"
+sdist = "setuptools.command.sdist:sdist"
+setopt = "setuptools.command.setopt:setopt"
+
+[project.entry-points."setuptools.finalize_distribution_options"]
+parent_finalize = "setuptools.dist:_Distribution.finalize_options"
+keywords = "setuptools.dist:Distribution._finalize_setup_keywords"
+
+[project.entry-points."distutils.setup_keywords"]
+eager_resources = "setuptools.dist:assert_string_list"
+namespace_packages = "setuptools.dist:check_nsp"
+extras_require = "setuptools.dist:check_extras"
+install_requires = "setuptools.dist:check_requirements"
+setup_requires = "setuptools.dist:check_requirements"
+python_requires = "setuptools.dist:check_specifier"
+entry_points = "setuptools.dist:check_entry_points"
+zip_safe = "setuptools.dist:assert_bool"
+package_data = "setuptools.dist:check_package_data"
+exclude_package_data = "setuptools.dist:check_package_data"
+include_package_data = "setuptools.dist:assert_bool"
+packages = "setuptools.dist:check_packages"
+dependency_links = "setuptools.dist:assert_string_list"
+use_2to3 = "setuptools.dist:invalid_unless_false"
+
+[project.entry-points."egg_info.writers"]
+PKG-INFO = "setuptools.command.egg_info:write_pkg_info"
+"requires.txt" = "setuptools.command.egg_info:write_requirements"
+"entry_points.txt" = "setuptools.command.egg_info:write_entries"
+"eager_resources.txt" = "setuptools.command.egg_info:overwrite_arg"
+"namespace_packages.txt" = "setuptools.command.egg_info:overwrite_arg"
+"top_level.txt" = "setuptools.command.egg_info:write_toplevel_names"
+"dependency_links.txt" = "setuptools.command.egg_info:overwrite_arg"
+
+[tool.setuptools]
+include-package-data = true
+
+[tool.setuptools.packages.find]
+include = [
+	"setuptools*",
+	"_distutils_hack*",
+]
+exclude = [
+	"*.tests",
+	"*.tests.*",
+]
+namespaces = true
+
+[tool.setuptools.exclude-package-data]
+# Remove ruff.toml when installing vendored packages (#4652)
+"*" = ["ruff.toml"]
+
+[tool.distutils.sdist]
+formats = "zip"
+
+
+[tool.setuptools_scm]
diff --git a/pyrightconfig.json b/pyrightconfig.json
new file mode 100644
index 0000000000..da3cd978ce
--- /dev/null
+++ b/pyrightconfig.json
@@ -0,0 +1,32 @@
+{
+	"$schema": "https://raw.githubusercontent.com/microsoft/pyright/main/packages/vscode-pyright/schemas/pyrightconfig.schema.json",
+	"exclude": [
+		// Avoid scanning Python files in generated folders
+		"build",
+		".tox",
+		".eggs",
+		"setuptools/config/_validate_pyproject/**",
+		// These are vendored
+		"**/_vendor",
+		"setuptools/_distutils",
+	],
+	// Our testing setup doesn't allow passing CLI arguments, so local devs have to set this manually.
+	// "pythonVersion": "3.9",
+	// For now we don't mind if mypy's `type: ignore` comments accidentally suppresses pyright issues
+	"enableTypeIgnoreComments": true,
+	"typeCheckingMode": "basic",
+	// Too many issues caused by dynamic patching, still worth fixing when we can
+	"reportAttributeAccessIssue": "warning",
+	// Fails on Python 3.12 due to missing distutils
+	"reportMissingImports": "warning",
+	// FIXME: A handful of reportOperatorIssue spread throughout the codebase
+	"reportOperatorIssue": "warning",
+	// Deferred initialization (initialize_options/finalize_options) causes many "potentially None" issues
+	// TODO: Fix with type-guards, by changing how it's initialized, or by casting initial assignments
+	"reportArgumentType": "warning",
+	"reportCallIssue": "warning",
+	"reportGeneralTypeIssues": "warning",
+	"reportOptionalIterable": "warning",
+	"reportOptionalMemberAccess": "warning",
+	"reportOptionalOperand": "warning",
+}
diff --git a/pytest.ini b/pytest.ini
index 20421f945c..de541404e6 100644
--- a/pytest.ini
+++ b/pytest.ini
@@ -2,34 +2,37 @@
 norecursedirs=dist build .tox .eggs
 addopts=
 	--doctest-modules
-	--doctest-glob=pkg_resources/api_tests.txt
-	-r sxX
-doctest_optionflags=ALLOW_UNICODE ELLIPSIS
+	--import-mode importlib
+consider_namespace_packages=true
 filterwarnings=
 	# Fail on warnings
 	error
 
+	# Workarounds for pypa/setuptools#3810
+	# Can't use EncodingWarning as it doesn't exist on Python 3.9.
+	# These warnings only appear on Python 3.10+
+
 	## upstream
 
 	# Ensure ResourceWarnings are emitted
 	default::ResourceWarning
 
-	# shopkeep/pytest-black#55
-	ignore: is not using a cooperative constructor:pytest.PytestDeprecationWarning
-	ignore:The \(fspath. py.path.local\) argument to BlackItem is deprecated.:pytest.PytestDeprecationWarning
-	ignore:BlackItem is an Item subclass and should not be a collector:pytest.PytestWarning
-
-	# shopkeep/pytest-black#67
-	ignore:'encoding' argument not specified::pytest_black
+	# python/mypy#17057
+	ignore:'encoding' argument not specified::mypy
+	ignore:'encoding' argument not specified::configparser
+	# ^-- ConfigParser is called by mypy,
+	#     but ignoring the warning in `mypy` is not enough
+	#     to make it work on PyPy
 
 	# realpython/pytest-mypy#152
 	ignore:'encoding' argument not specified::pytest_mypy
 
-	# python/cpython#100750
-	ignore:'encoding' argument not specified::platform
+	# TODO: Set encoding when opening/writing tmpdir files with pytest's LocalPath.open
+	# see pypa/setuptools#4326
+	ignore:'encoding' argument not specified::_pytest
 
-	# pypa/build#615
-	ignore:'encoding' argument not specified::build.env
+	# Already fixed in pypa/distutils, but present in stdlib
+	ignore:'encoding' argument not specified::distutils
 
 	## end upstream
 
@@ -48,9 +51,7 @@ filterwarnings=
 	# https://github.com/pypa/setuptools/issues/917
 	ignore:setup.py install is deprecated.
 	ignore:easy_install command is deprecated.
-
-	# https://github.com/pypa/setuptools/issues/2497
-	ignore:.* is an invalid version and will not be supported::pkg_resources
+	ignore:develop command is deprecated.
 
 	# https://github.com/pypa/setuptools/pull/2865#issuecomment-965700112
 	# ideally would apply to Python 3.10+ when
@@ -68,24 +69,23 @@ filterwarnings=
 	# suppress warnings in deprecated msvc compilers
 	ignore:(bcpp|msvc9?)compiler is deprecated
 
+	# Ignore warnings about deprecated stdlib distutils pypa/setuptools#4137
+	ignore:Reliance on distutils from stdlib is deprecated
+
 	ignore::setuptools.command.editable_wheel.InformationOnly
 
 	# https://github.com/pypa/setuptools/issues/3655
 	ignore:The --rsyncdir command line argument and rsyncdirs config variable are deprecated.:DeprecationWarning
 
-	# Workarounds for pypa/setuptools#3810
-	# Can't use EncodingWarning as it doesn't exist on Python 3.9
-	default:'encoding' argument not specified
-	default:UTF-8 Mode affects locale.getpreferredencoding().
-
-	# Avoid errors when testing pkg_resources.declare_namespace
-	ignore:.*pkg_resources\.declare_namespace.*:DeprecationWarning
-
-	# suppress known deprecation
-	ignore:pkg_resources is deprecated:DeprecationWarning
-
 	# Dependencies might not have been updated yet
 	default:onerror argument is deprecated, use onexc instead
 
 	# Ignore warnings about experimental features
 	ignore:..tool\.distutils.. in .pyproject\.toml. is still .experimental.*
+
+	# Ignore warnings about consider_namespace_packages (jaraco/skeleton@6ff02e0eefcd)
+	ignore:Unknown config option. consider_namespace_packages:pytest.PytestConfigWarning
+
+	# Ignore warnings we cannot do anything about:
+	# https://github.com/pypa/setuptools/pull/5042#issuecomment-2981138461
+	ignore:Couldn't import C tracer:coverage.exceptions.CoverageWarning
diff --git a/ruff.toml b/ruff.toml
new file mode 100644
index 0000000000..9525996ab0
--- /dev/null
+++ b/ruff.toml
@@ -0,0 +1,94 @@
+exclude = [
+	"**/_vendor",
+	"setuptools/_distutils",
+	"setuptools/config/_validate_pyproject",
+]
+
+[lint]
+extend-select = [
+	# upstream
+
+	"C901", # complex-structure
+	"I", # isort
+	"PERF401", # manual-list-comprehension
+
+	# Ensure modern type annotation syntax and best practices
+	# Not including those covered by type-checkers or exclusive to Python 3.11+
+	"FA", # flake8-future-annotations
+	"F404", # late-future-import
+	"PYI", # flake8-pyi
+	"UP006", # non-pep585-annotation
+	"UP007", # non-pep604-annotation
+	"UP010", # unnecessary-future-import
+	"UP035", # deprecated-import
+	"UP037", # quoted-annotation
+	"UP043", # unnecessary-default-type-args
+
+	# local
+	"ANN2", # missing-return-type-*
+	"ISC", # flake8-implicit-str-concat
+	"FURB", # refurb
+	"PERF", # Perflint
+	"PIE", # flake8-pie
+	"PGH", # pygrep-hooks (blanket-* rules)
+	"PT", # flake8-pytest-style
+	"RUF10", # unused-noqa & redirected-noqa
+	"TRY", # tryceratops
+	"UP", # pyupgrade
+	"YTT", # flake8-2020
+]
+ignore = [
+	# upstream
+
+	# Typeshed rejects complex or non-literal defaults for maintenance and testing reasons,
+	# irrelevant to this project.
+	"PYI011", # typed-argument-default-in-stub
+	# https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules
+	"W191",
+	"E111",
+	"E114",
+	"E117",
+	"D206",
+	"D300",
+	"Q000",
+	"Q001",
+	"Q002",
+	"Q003",
+	"COM812",
+	"COM819",
+
+	# local
+	"PERF203", # try-except-in-loop, micro-optimisation with many false-positive. Worth checking but don't block CI
+	"PT007", # temporarily disabled, TODO: configure and standardize to preference
+	"PT011", # temporarily disabled, TODO: tighten expected error 
+	"PT012", # pytest-raises-with-multiple-statements, avoid extra dummy methods for a few lines, sometimes we explicitly assert in case of no error
+	"TRY003", # raise-vanilla-args, avoid multitude of exception classes
+	"TRY301", # raise-within-try, it's handy
+	"UP015", # redundant-open-modes, explicit is preferred
+	# Only enforcing return type annotations for public functions
+	"ANN202", # missing-return-type-private-function
+]
+
+[lint.per-file-ignores]
+# Suppress nuisance warnings about module-import-not-at-top-of-file (E402) due to workaround for #4476
+"setuptools/__init__.py" = ["E402"]
+
+[lint.isort]
+combine-as-imports = true
+split-on-trailing-comma = false
+# Force Ruff/isort to always import setuptools before distutils in tests as long as distutils_hack is supported
+# This also ensures _distutils_hack is imported before distutils
+# https://github.com/pypa/setuptools/issues/4137
+section-order = ["future", "standard-library", "eager", "third-party", "first-party", "local-folder", "delayed"]
+sections.eager = ["_distutils_hack"]
+sections.delayed = ["distutils"]
+
+[lint.flake8-annotations]
+ignore-fully-untyped = true
+
+[format]
+# Enable preview to get hugged parenthesis unwrapping and other nice surprises
+# See https://github.com/jaraco/skeleton/pull/133#issuecomment-2239538373
+preview = true
+# https://docs.astral.sh/ruff/settings/#format_quote-style
+quote-style = "preserve"
diff --git a/setup.cfg b/setup.cfg
deleted file mode 100644
index 358f302bd8..0000000000
--- a/setup.cfg
+++ /dev/null
@@ -1,178 +0,0 @@
-[metadata]
-name = setuptools
-version = 68.1.2
-author = Python Packaging Authority
-author_email = distutils-sig@python.org
-description = Easily download, build, install, upgrade, and uninstall Python packages
-long_description = file:README.rst
-url = https://github.com/pypa/setuptools
-classifiers =
-	Development Status :: 5 - Production/Stable
-	Intended Audience :: Developers
-	License :: OSI Approved :: MIT License
-	Programming Language :: Python :: 3
-	Programming Language :: Python :: 3 :: Only
-	Topic :: Software Development :: Libraries :: Python Modules
-	Topic :: System :: Archiving :: Packaging
-	Topic :: System :: Systems Administration
-	Topic :: Utilities
-keywords = CPAN PyPI distutils eggs package management
-project_urls =
-	Documentation = https://setuptools.pypa.io/
-	Changelog = https://setuptools.pypa.io/en/stable/history.html
-
-[options]
-packages = find_namespace:
-# disabled as it causes tests to be included #2505
-# include_package_data = true
-python_requires = >=3.8
-install_requires =
-
-[options.packages.find]
-exclude =
-	build*
-	dist*
-	docs*
-	tests*
-	*.tests
-	*.tests.*
-	tools*
-	debian*
-	launcher*
-	newsfragments*
-
-[options.extras_require]
-testing =
-	# upstream
-	pytest >= 6
-	pytest-checkdocs >= 2.4
-	pytest-black >= 0.3.7; \
-		# workaround for jaraco/skeleton#22
-		python_implementation != "PyPy"
-	pytest-cov; \
-		# coverage seems to make PyPy extremely slow
-		python_implementation != "PyPy"
-	pytest-mypy >= 0.9.1; \
-		# workaround for jaraco/skeleton#22
-		python_implementation != "PyPy"
-	pytest-enabler >= 2.2
-	# workaround for pypa/setuptools#3921
-	pytest-ruff; sys_platform != "cygwin"
-
-	# local
-	flake8-2020
-	virtualenv>=13.0.0
-	wheel
-	pip>=19.1 # For proper file:// URLs support.
-	jaraco.envs>=2.2
-	pytest-xdist
-	jaraco.path>=3.2.0
-	build[virtualenv]
-	filelock>=3.4.0
-	ini2toml[lite]>=0.9
-	tomli-w>=1.0.0
-	pytest-timeout
-	pytest-perf; \
-		# workaround for jaraco/inflect#195, pydantic/pydantic-core#773 (see #3986)
-		sys_platform != "cygwin"
-	# for tools/finalize.py
-	jaraco.develop >= 7.21; python_version >= "3.9" and sys_platform != "cygwin"
-
-testing-integration =
-	pytest
-	pytest-xdist
-	pytest-enabler
-	virtualenv>=13.0.0
-	tomli
-	wheel
-	jaraco.path>=3.2.0
-	jaraco.envs>=2.2
-	build[virtualenv]
-	filelock>=3.4.0
-	packaging
-
-docs =
-	# upstream
-	sphinx >= 3.5
-	jaraco.packaging >= 9.3
-	rst.linker >= 1.9
-	furo
-	sphinx-lint
-
-	# tidelift
-	jaraco.tidelift >= 1.4
-
-	# local
-	pygments-github-lexers==0.0.5
-	sphinx-favicon
-	sphinx-inline-tabs
-	sphinx-reredirects
-	sphinxcontrib-towncrier
-	sphinx-notfound-page == 0.8.3
-	sphinx-hoverxref < 2
-
-ssl =
-
-certs =
-
-[options.entry_points]
-distutils.commands =
-	alias = setuptools.command.alias:alias
-	bdist_egg = setuptools.command.bdist_egg:bdist_egg
-	bdist_rpm = setuptools.command.bdist_rpm:bdist_rpm
-	build = setuptools.command.build:build
-	build_clib = setuptools.command.build_clib:build_clib
-	build_ext = setuptools.command.build_ext:build_ext
-	build_py = setuptools.command.build_py:build_py
-	develop = setuptools.command.develop:develop
-	dist_info = setuptools.command.dist_info:dist_info
-	easy_install = setuptools.command.easy_install:easy_install
-	editable_wheel = setuptools.command.editable_wheel:editable_wheel
-	egg_info = setuptools.command.egg_info:egg_info
-	install = setuptools.command.install:install
-	install_egg_info = setuptools.command.install_egg_info:install_egg_info
-	install_lib = setuptools.command.install_lib:install_lib
-	install_scripts = setuptools.command.install_scripts:install_scripts
-	rotate = setuptools.command.rotate:rotate
-	saveopts = setuptools.command.saveopts:saveopts
-	sdist = setuptools.command.sdist:sdist
-	setopt = setuptools.command.setopt:setopt
-	test = setuptools.command.test:test
-	upload_docs = setuptools.command.upload_docs:upload_docs
-setuptools.finalize_distribution_options =
-	parent_finalize = setuptools.dist:_Distribution.finalize_options
-	keywords = setuptools.dist:Distribution._finalize_setup_keywords
-distutils.setup_keywords =
-	eager_resources = setuptools.dist:assert_string_list
-	namespace_packages = setuptools.dist:check_nsp
-	extras_require = setuptools.dist:check_extras
-	install_requires = setuptools.dist:check_requirements
-	tests_require = setuptools.dist:check_requirements
-	setup_requires = setuptools.dist:check_requirements
-	python_requires = setuptools.dist:check_specifier
-	entry_points = setuptools.dist:check_entry_points
-	test_suite = setuptools.dist:check_test_suite
-	zip_safe = setuptools.dist:assert_bool
-	package_data = setuptools.dist:check_package_data
-	exclude_package_data = setuptools.dist:check_package_data
-	include_package_data = setuptools.dist:assert_bool
-	packages = setuptools.dist:check_packages
-	dependency_links = setuptools.dist:assert_string_list
-	test_loader = setuptools.dist:check_importable
-	test_runner = setuptools.dist:check_importable
-	use_2to3 = setuptools.dist:invalid_unless_false
-egg_info.writers =
-	PKG-INFO = setuptools.command.egg_info:write_pkg_info
-	requires.txt = setuptools.command.egg_info:write_requirements
-	entry_points.txt = setuptools.command.egg_info:write_entries
-	eager_resources.txt = setuptools.command.egg_info:overwrite_arg
-	namespace_packages.txt = setuptools.command.egg_info:overwrite_arg
-	top_level.txt = setuptools.command.egg_info:write_toplevel_names
-	dependency_links.txt = setuptools.command.egg_info:overwrite_arg
-
-[egg_info]
-tag_build = .post
-tag_date = 1
-
-[sdist]
-formats = zip
diff --git a/setup.py b/setup.py
index 075d7c405f..fe33940f89 100755
--- a/setup.py
+++ b/setup.py
@@ -1,7 +1,6 @@
 #!/usr/bin/env python
 
 import os
-import sys
 import textwrap
 
 import setuptools
@@ -10,32 +9,6 @@
 here = os.path.dirname(__file__)
 
 
-package_data = dict(
-    setuptools=['script (dev).tmpl', 'script.tmpl', 'site-patch.py'],
-)
-
-force_windows_specific_files = os.environ.get(
-    "SETUPTOOLS_INSTALL_WINDOWS_SPECIFIC_FILES", "1"
-).lower() not in ("", "0", "false", "no")
-
-include_windows_files = sys.platform == 'win32' or force_windows_specific_files
-
-if include_windows_files:
-    package_data.setdefault('setuptools', []).extend(['*.exe'])
-    package_data.setdefault('setuptools.command', []).extend(['*.xml'])
-
-
-def pypi_link(pkg_filename):
-    """
-    Given the filename, including md5 fragment, construct the
-    dependency link for PyPI.
-    """
-    root = 'https://files.pythonhosted.org/packages/source'
-    name, sep, rest = pkg_filename.partition('-')
-    parts = root, name[0], name, pkg_filename
-    return '/'.join(parts)
-
-
 class install_with_pth(install):
     """
     Custom install command to install a .pth file for distutils patching.
@@ -51,7 +24,8 @@ class install_with_pth(install):
 
     _pth_name = 'distutils-precedence'
     _pth_contents = (
-        textwrap.dedent(
+        textwrap
+        .dedent(
             """
         import os
         var = 'SETUPTOOLS_USE_DISTUTILS'
@@ -83,10 +57,10 @@ def _restore_install_lib(self):
 
 setup_params = dict(
     cmdclass={'install': install_with_pth},
-    package_data=package_data,
 )
 
 if __name__ == '__main__':
     # allow setup.py to run from another directory
-    here and os.chdir(here)
+    # TODO: Use a proper conditional statement here
+    here and os.chdir(here)  # type: ignore[func-returns-value]
     dist = setuptools.setup(**setup_params)
diff --git a/setuptools/__init__.py b/setuptools/__init__.py
index 563ca1c4ba..87ca47bbc9 100644
--- a/setuptools/__init__.py
+++ b/setuptools/__init__.py
@@ -1,22 +1,35 @@
 """Extensions to the 'distutils' for large or complex distributions"""
+# mypy: disable_error_code=override
+# Command.reinitialize_command has an extra **kw param that distutils doesn't have
+# Can't disable on the exact line because distutils doesn't exists on Python 3.12
+# and mypy isn't aware of distutils_hack, causing distutils.core.Command to be Any,
+# and a [unused-ignore] to be raised on 3.12+
+
+from __future__ import annotations
 
 import functools
 import os
-import re
+import sys
+from abc import abstractmethod
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, TypeVar, overload
+
+sys.path.extend(((vendor_path := os.path.join(os.path.dirname(os.path.dirname(__file__)), 'setuptools', '_vendor')) not in sys.path) * [vendor_path])  # fmt: skip
+# workaround for #4476
+sys.modules.pop('backports', None)
 
 import _distutils_hack.override  # noqa: F401
-import distutils.core
-from distutils.errors import DistutilsOptionError
-from distutils.util import convert_path as _convert_path
 
 from . import logging, monkey
-from . import version as _version_module
 from .depends import Require
 from .discovery import PackageFinder, PEP420PackageFinder
 from .dist import Distribution
 from .extension import Extension
+from .version import __version__ as __version__
 from .warnings import SetuptoolsDeprecationWarning
 
+import distutils.core
+
 __all__ = [
     'setup',
     'Distribution',
@@ -28,11 +41,10 @@
     'find_namespace_packages',
 ]
 
-__version__ = _version_module.__version__
+_CommandT = TypeVar("_CommandT", bound="_Command")
 
 bootstrap_install_from = None
 
-
 find_packages = PackageFinder.find
 find_namespace_packages = PEP420PackageFinder.find
 
@@ -46,7 +58,7 @@ class MinimalDistribution(distutils.core.Distribution):
         fetch_build_eggs interface.
         """
 
-        def __init__(self, attrs):
+        def __init__(self, attrs: Mapping[str, object]) -> None:
             _incl = 'dependency_links', 'setup_requires'
             filtered = {k: attrs[k] for k in set(_incl) & set(attrs)}
             super().__init__(filtered)
@@ -56,10 +68,10 @@ def __init__(self, attrs):
         def _get_project_config_files(self, filenames=None):
             """Ignore ``pyproject.toml``, they are not related to setup_requires"""
             try:
-                cfg, toml = super()._split_standard_project_metadata(filenames)
-                return cfg, ()
+                cfg, _toml = super()._split_standard_project_metadata(filenames)
             except Exception:
                 return filenames, ()
+            return cfg, ()
 
         def finalize_options(self):
             """
@@ -75,7 +87,7 @@ def finalize_options(self):
         _fetch_build_eggs(dist)
 
 
-def _fetch_build_eggs(dist):
+def _fetch_build_eggs(dist: Distribution):
     try:
         dist.fetch_build_eggs(dist.setup_requires)
     except Exception as ex:
@@ -96,17 +108,22 @@ def _fetch_build_eggs(dist):
         raise
 
 
-def setup(**attrs):
-    # Make sure we have any requirements needed to interpret 'attrs'.
+def setup(**attrs) -> Distribution:
     logging.configure()
+    # Make sure we have any requirements needed to interpret 'attrs'.
     _install_setup_requires(attrs)
-    return distutils.core.setup(**attrs)
+    # Override return type of distutils.core.Distribution with setuptools.dist.Distribution
+    # (implicitly implemented via `setuptools.monkey.patch_all`).
+    return distutils.core.setup(**attrs)  # type: ignore[return-value]
 
 
 setup.__doc__ = distutils.core.setup.__doc__
 
-
-_Command = monkey.get_unpatched(distutils.core.Command)
+if TYPE_CHECKING:
+    # Work around a mypy issue where type[T] can't be used as a base: https://github.com/python/mypy/issues/10962
+    from distutils.core import Command as _Command
+else:
+    _Command = monkey.get_unpatched(distutils.core.Command)
 
 
 class Command(_Command):
@@ -122,42 +139,25 @@ class Command(_Command):
     When creating a new command from scratch, custom defined classes **SHOULD** inherit
     from ``setuptools.Command`` and implement a few mandatory methods.
     Between these mandatory methods, are listed:
-
-    .. method:: initialize_options(self)
-
-        Set or (reset) all options/attributes/caches used by the command
-        to their default values. Note that these values may be overwritten during
-        the build.
-
-    .. method:: finalize_options(self)
-
-        Set final values for all options/attributes used by the command.
-        Most of the time, each option/attribute/cache should only be set if it does not
-        have any value yet (e.g. ``if self.attr is None: self.attr = val``).
-
-    .. method:: run(self)
-
-        Execute the actions intended by the command.
-        (Side effects **SHOULD** only take place when ``run`` is executed,
-        for example, creating new files or writing to the terminal output).
+    :meth:`initialize_options`, :meth:`finalize_options` and :meth:`run`.
 
     A useful analogy for command classes is to think of them as subroutines with local
-    variables called "options".  The options are "declared" in ``initialize_options()``
-    and "defined" (given their final values, aka "finalized") in ``finalize_options()``,
+    variables called "options".  The options are "declared" in :meth:`initialize_options`
+    and "defined" (given their final values, aka "finalized") in :meth:`finalize_options`,
     both of which must be defined by every command class. The "body" of the subroutine,
-    (where it does all the work) is the ``run()`` method.
-    Between ``initialize_options()`` and ``finalize_options()``, ``setuptools`` may set
+    (where it does all the work) is the :meth:`run` method.
+    Between :meth:`initialize_options` and :meth:`finalize_options`, ``setuptools`` may set
     the values for options/attributes based on user's input (or circumstance),
     which means that the implementation should be careful to not overwrite values in
-    ``finalize_options`` unless necessary.
+    :meth:`finalize_options` unless necessary.
 
     Please note that other commands (or other parts of setuptools) may also overwrite
     the values of the command's options/attributes multiple times during the build
     process.
-    Therefore it is important to consistently implement ``initialize_options()`` and
-    ``finalize_options()``. For example, all derived attributes (or attributes that
+    Therefore it is important to consistently implement :meth:`initialize_options` and
+    :meth:`finalize_options`. For example, all derived attributes (or attributes that
     depend on the value of other attributes) **SHOULD** be recomputed in
-    ``finalize_options``.
+    :meth:`finalize_options`.
 
     When overwriting existing commands, custom defined classes **MUST** abide by the
     same APIs implemented by the original class. They also **SHOULD** inherit from the
@@ -165,8 +165,15 @@ class Command(_Command):
     """
 
     command_consumes_arguments = False
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+
+    dry_run = False  # type: ignore[assignment] # pyright: ignore[reportAssignmentType] (until #4689; see #4872)
+    """
+    For compatibility with vendored bdist_wheel.
+    https://github.com/pypa/setuptools/pull/4872/files#r1986395142
+    """
 
-    def __init__(self, dist, **kw):
+    def __init__(self, dist: Distribution, **kw) -> None:
         """
         Construct the command for dist, updating
         vars(self) with any keyword parameters.
@@ -174,48 +181,47 @@ def __init__(self, dist, **kw):
         super().__init__(dist)
         vars(self).update(kw)
 
-    def _ensure_stringlike(self, option, what, default=None):
-        val = getattr(self, option)
-        if val is None:
-            setattr(self, option, default)
-            return default
-        elif not isinstance(val, str):
-            raise DistutilsOptionError(
-                "'%s' must be a %s (got `%s`)" % (option, what, val)
-            )
-        return val
-
-    def ensure_string_list(self, option):
-        r"""Ensure that 'option' is a list of strings.  If 'option' is
-        currently a string, we split it either on /,\s*/ or /\s+/, so
-        "foo bar baz", "foo,bar,baz", and "foo,   bar baz" all become
-        ["foo", "bar", "baz"].
-
-        ..
-           TODO: This method seems to be similar to the one in ``distutils.cmd``
-           Probably it is just here for backward compatibility with old Python versions?
-
-        :meta private:
-        """
-        val = getattr(self, option)
-        if val is None:
-            return
-        elif isinstance(val, str):
-            setattr(self, option, re.split(r',\s*|\s+', val))
-        else:
-            if isinstance(val, list):
-                ok = all(isinstance(v, str) for v in val)
-            else:
-                ok = False
-            if not ok:
-                raise DistutilsOptionError(
-                    "'%s' must be a list of strings (got %r)" % (option, val)
-                )
-
-    def reinitialize_command(self, command, reinit_subcommands=0, **kw):
+    @overload
+    def reinitialize_command(
+        self, command: str, reinit_subcommands: bool = False, **kw
+    ) -> Command: ...  # override distutils.cmd.Command with setuptools.Command
+    @overload
+    def reinitialize_command(
+        self, command: _CommandT, reinit_subcommands: bool = False, **kw
+    ) -> _CommandT: ...
+    def reinitialize_command(
+        self, command: str | _Command, reinit_subcommands: bool = False, **kw
+    ) -> Command | _Command:
         cmd = _Command.reinitialize_command(self, command, reinit_subcommands)
         vars(cmd).update(kw)
-        return cmd
+        return cmd  # pyright: ignore[reportReturnType] # pypa/distutils#307
+
+    @abstractmethod
+    def initialize_options(self) -> None:
+        """
+        Set or (reset) all options/attributes/caches used by the command
+        to their default values. Note that these values may be overwritten during
+        the build.
+        """
+        raise NotImplementedError
+
+    @abstractmethod
+    def finalize_options(self) -> None:
+        """
+        Set final values for all options/attributes used by the command.
+        Most of the time, each option/attribute/cache should only be set if it does not
+        have any value yet (e.g. ``if self.attr is None: self.attr = val``).
+        """
+        raise NotImplementedError
+
+    @abstractmethod
+    def run(self) -> None:
+        """
+        Execute the actions intended by the command.
+        (Side effects **SHOULD** only take place when :meth:`run` is executed,
+        for example, creating new files or writing to the terminal output).
+        """
+        raise NotImplementedError
 
 
 def _find_all_simple(path):
@@ -242,22 +248,6 @@ def findall(dir=os.curdir):
     return list(files)
 
 
-@functools.wraps(_convert_path)
-def convert_path(pathname):
-    SetuptoolsDeprecationWarning.emit(
-        "Access to implementation detail",
-        """
-        The function `convert_path` is not provided by setuptools itself,
-        and therefore not part of the public API.
-
-        Its direct usage by 3rd-party packages is considered improper and the function
-        may be removed in the future.
-        """,
-        due_date=(2023, 12, 13),  # initial deprecation 2022-03-25, see #3201
-    )
-    return _convert_path(pathname)
-
-
 class sic(str):
     """Treat this string as-is (https://en.wikipedia.org/wiki/Sic)"""
 
diff --git a/setuptools/_core_metadata.py b/setuptools/_core_metadata.py
index c1d41c6680..a52d5cf755 100644
--- a/setuptools/_core_metadata.py
+++ b/setuptools/_core_metadata.py
@@ -3,27 +3,32 @@
 
 See: https://packaging.python.org/en/latest/specifications/core-metadata/
 """
+
+from __future__ import annotations
+
 import os
 import stat
 import textwrap
 from email import message_from_file
 from email.message import Message
 from tempfile import NamedTemporaryFile
-from typing import Optional, List
 
-from distutils.util import rfc822_escape
+from packaging.markers import Marker
+from packaging.requirements import Requirement
+from packaging.utils import canonicalize_name, canonicalize_version
+from packaging.version import Version
 
-from . import _normalization
-from .extern.packaging.markers import Marker
-from .extern.packaging.requirements import Requirement
-from .extern.packaging.version import Version
+from . import _normalization, _reqs
+from ._static import is_static
 from .warnings import SetuptoolsDeprecationWarning
 
+from distutils.util import rfc822_escape
+
 
 def get_metadata_version(self):
     mv = getattr(self, 'metadata_version', None)
     if mv is None:
-        mv = Version('2.1')
+        mv = Version('2.4')
         self.metadata_version = mv
     return mv
 
@@ -36,7 +41,7 @@ def rfc822_unescape(content: str) -> str:
     return '\n'.join((lines[0].lstrip(), textwrap.dedent('\n'.join(lines[1:]))))
 
 
-def _read_field_from_msg(msg: Message, field: str) -> Optional[str]:
+def _read_field_from_msg(msg: Message, field: str) -> str | None:
     """Read Message header field."""
     value = msg[field]
     if value == 'UNKNOWN':
@@ -44,7 +49,7 @@ def _read_field_from_msg(msg: Message, field: str) -> Optional[str]:
     return value
 
 
-def _read_field_unescaped_from_msg(msg: Message, field: str) -> Optional[str]:
+def _read_field_unescaped_from_msg(msg: Message, field: str) -> str | None:
     """Read Message header field and apply rfc822_unescape."""
     value = _read_field_from_msg(msg, field)
     if value is None:
@@ -52,7 +57,7 @@ def _read_field_unescaped_from_msg(msg: Message, field: str) -> Optional[str]:
     return rfc822_unescape(value)
 
 
-def _read_list_from_msg(msg: Message, field: str) -> Optional[List[str]]:
+def _read_list_from_msg(msg: Message, field: str) -> list[str] | None:
     """Read Message header field and return all results as list."""
     values = msg.get_all(field, None)
     if values == []:
@@ -60,8 +65,8 @@ def _read_list_from_msg(msg: Message, field: str) -> Optional[List[str]]:
     return values
 
 
-def _read_payload_from_msg(msg: Message) -> Optional[str]:
-    value = msg.get_payload().strip()
+def _read_payload_from_msg(msg: Message) -> str | None:
+    value = str(msg.get_payload()).strip()
     if value == 'UNKNOWN' or not value:
         return None
     return value
@@ -83,6 +88,7 @@ def read_pkg_file(self, file):
     self.url = _read_field_from_msg(msg, 'home-page')
     self.download_url = _read_field_from_msg(msg, 'download-url')
     self.license = _read_field_unescaped_from_msg(msg, 'license')
+    self.license_expression = _read_field_unescaped_from_msg(msg, 'license-expression')
 
     self.long_description = _read_field_unescaped_from_msg(msg, 'description')
     if self.long_description is None and self.metadata_version >= Version('2.1'):
@@ -146,7 +152,7 @@ def write_pkg_file(self, file):  # noqa: C901  # is too complex (14)  # FIXME
     version = self.get_metadata_version()
 
     def write_field(key, value):
-        file.write("%s: %s\n" % (key, value))
+        file.write(f"{key}: {value}\n")
 
     write_field('Metadata-Version', str(version))
     write_field('Name', self.get_name())
@@ -170,12 +176,13 @@ def write_field(key, value):
         if attr_val is not None:
             write_field(field, attr_val)
 
-    license = self.get_license()
-    if license:
+    if license_expression := self.license_expression:
+        write_field('License-Expression', license_expression)
+    elif license := self.get_license():
         write_field('License', rfc822_escape(license))
 
-    for project_url in self.project_urls.items():
-        write_field('Project-URL', '%s, %s' % project_url)
+    for label, url in self.project_urls.items():
+        write_field('Project-URL', f'{label}, {url}')
 
     keywords = ','.join(self.get_keywords())
     if keywords:
@@ -200,22 +207,27 @@ def write_field(key, value):
     if self.long_description_content_type:
         write_field('Description-Content-Type', self.long_description_content_type)
 
-    self._write_list(file, 'License-File', self.license_files or [])
+    safe_license_files = map(_safe_license_file, self.license_files or [])
+    self._write_list(file, 'License-File', safe_license_files)
     _write_requirements(self, file)
 
+    for field, attr in _POSSIBLE_DYNAMIC_FIELDS.items():
+        if (val := getattr(self, attr, None)) and not is_static(val):
+            write_field('Dynamic', field)
+
     long_description = self.get_long_description()
     if long_description:
-        file.write("\n%s" % long_description)
+        file.write(f"\n{long_description}")
         if not long_description.endswith("\n"):
             file.write("\n")
 
 
 def _write_requirements(self, file):
-    for req in self._normalized_install_requires:
+    for req in _reqs.parse(self.install_requires):
         file.write(f"Requires-Dist: {req}\n")
 
     processed_extras = {}
-    for augmented_extra, reqs in self._normalized_extras_require.items():
+    for augmented_extra, reqs in self.extras_require.items():
         # Historically, setuptools allows "augmented extras": `:`
         unsafe_extra, _, condition = augmented_extra.partition(":")
         unsafe_extra = unsafe_extra.strip()
@@ -223,7 +235,7 @@ def _write_requirements(self, file):
 
         if extra:
             _write_provides_extra(file, processed_extras, extra, unsafe_extra)
-        for req in reqs:
+        for req in _reqs.parse_strings(reqs):
             r = _include_extra(req, extra, condition.strip())
             file.write(f"Requires-Dist: {r}\n")
 
@@ -231,7 +243,7 @@ def _write_requirements(self, file):
 
 
 def _include_extra(req: str, extra: str, condition: str) -> Requirement:
-    r = Requirement(req)
+    r = Requirement(req)  # create a fresh object that can be modified
     parts = (
         f"({r.marker})" if r.marker else None,
         f"({condition})" if condition else None,
@@ -256,3 +268,70 @@ def _write_provides_extra(file, processed_extras, safe, unsafe):
     else:
         processed_extras[safe] = unsafe
         file.write(f"Provides-Extra: {safe}\n")
+
+
+# from pypa/distutils#244; needed only until that logic is always available
+def get_fullname(self):
+    return _distribution_fullname(self.get_name(), self.get_version())
+
+
+def _distribution_fullname(name: str, version: str) -> str:
+    """
+    >>> _distribution_fullname('setup.tools', '1.0-2')
+    'setup_tools-1.0.post2'
+    >>> _distribution_fullname('setup-tools', '1.2post2')
+    'setup_tools-1.2.post2'
+    >>> _distribution_fullname('setup-tools', '1.0-r2')
+    'setup_tools-1.0.post2'
+    >>> _distribution_fullname('setup.tools', '1.0.post')
+    'setup_tools-1.0.post0'
+    >>> _distribution_fullname('setup.tools', '1.0+ubuntu-1')
+    'setup_tools-1.0+ubuntu.1'
+    """
+    return "{}-{}".format(
+        canonicalize_name(name).replace('-', '_'),
+        canonicalize_version(version, strip_trailing_zero=False),
+    )
+
+
+def _safe_license_file(file):
+    # XXX: Do we need this after the deprecation discussed in #4892, #4896??
+    normalized = os.path.normpath(file).replace(os.sep, "/")
+    if "../" in normalized:
+        return os.path.basename(normalized)  # Temporarily restore pre PEP639 behaviour
+    return normalized
+
+
+_POSSIBLE_DYNAMIC_FIELDS = {
+    # Core Metadata Field x related Distribution attribute
+    "author": "author",
+    "author-email": "author_email",
+    "classifier": "classifiers",
+    "description": "long_description",
+    "description-content-type": "long_description_content_type",
+    "download-url": "download_url",
+    "home-page": "url",
+    "keywords": "keywords",
+    "license": "license",
+    # XXX: License-File is complicated because the user gives globs that are expanded
+    #      during the build. Without special handling it is likely always
+    #      marked as Dynamic, which is an acceptable outcome according to:
+    #      https://github.com/pypa/setuptools/issues/4629#issuecomment-2331233677
+    "license-file": "license_files",
+    "license-expression": "license_expression",  # PEP 639
+    "maintainer": "maintainer",
+    "maintainer-email": "maintainer_email",
+    "obsoletes": "obsoletes",
+    # "obsoletes-dist": "obsoletes_dist",  # NOT USED
+    "platform": "platforms",
+    "project-url": "project_urls",
+    "provides": "provides",
+    # "provides-dist": "provides_dist",  # NOT USED
+    "provides-extra": "extras_require",
+    "requires": "requires",
+    "requires-dist": "install_requires",
+    # "requires-external": "requires_external",  # NOT USED
+    "requires-python": "python_requires",
+    "summary": "description",
+    # "supported-platform": "supported_platforms",  # NOT USED
+}
diff --git a/setuptools/_discovery.py b/setuptools/_discovery.py
new file mode 100644
index 0000000000..d1b4a0ee03
--- /dev/null
+++ b/setuptools/_discovery.py
@@ -0,0 +1,33 @@
+import functools
+import operator
+
+import packaging.requirements
+
+
+# from coherent.build.discovery
+def extras_from_dep(dep):
+    try:
+        markers = packaging.requirements.Requirement(dep).marker._markers
+    except AttributeError:
+        markers = ()
+    return set(
+        marker[2].value
+        for marker in markers
+        if isinstance(marker, tuple) and marker[0].value == 'extra'
+    )
+
+
+def extras_from_deps(deps):
+    """
+    >>> extras_from_deps(['requests'])
+    set()
+    >>> extras_from_deps(['pytest; extra == "test"'])
+    {'test'}
+    >>> sorted(extras_from_deps([
+    ...     'requests',
+    ...     'pytest; extra == "test"',
+    ...     'pytest-cov; extra == "test"',
+    ...     'sphinx; extra=="doc"']))
+    ['doc', 'test']
+    """
+    return functools.reduce(operator.or_, map(extras_from_dep, deps), set())
diff --git a/setuptools/_distutils/__init__.py b/setuptools/_distutils/__init__.py
index 1a188c35cb..e374d5c560 100644
--- a/setuptools/_distutils/__init__.py
+++ b/setuptools/_distutils/__init__.py
@@ -1,5 +1,5 @@
-import sys
 import importlib
+import sys
 
 __version__, _, _ = sys.version.partition(' ')
 
diff --git a/setuptools/_distutils/_collections.py b/setuptools/_distutils/_collections.py
deleted file mode 100644
index 5ad21cc7c9..0000000000
--- a/setuptools/_distutils/_collections.py
+++ /dev/null
@@ -1,194 +0,0 @@
-import collections
-import functools
-import itertools
-import operator
-
-
-# from jaraco.collections 3.5.1
-class DictStack(list, collections.abc.Mapping):
-    """
-    A stack of dictionaries that behaves as a view on those dictionaries,
-    giving preference to the last.
-
-    >>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)])
-    >>> stack['a']
-    2
-    >>> stack['b']
-    2
-    >>> stack['c']
-    2
-    >>> len(stack)
-    3
-    >>> stack.push(dict(a=3))
-    >>> stack['a']
-    3
-    >>> set(stack.keys()) == set(['a', 'b', 'c'])
-    True
-    >>> set(stack.items()) == set([('a', 3), ('b', 2), ('c', 2)])
-    True
-    >>> dict(**stack) == dict(stack) == dict(a=3, c=2, b=2)
-    True
-    >>> d = stack.pop()
-    >>> stack['a']
-    2
-    >>> d = stack.pop()
-    >>> stack['a']
-    1
-    >>> stack.get('b', None)
-    >>> 'c' in stack
-    True
-    """
-
-    def __iter__(self):
-        dicts = list.__iter__(self)
-        return iter(set(itertools.chain.from_iterable(c.keys() for c in dicts)))
-
-    def __getitem__(self, key):
-        for scope in reversed(tuple(list.__iter__(self))):
-            if key in scope:
-                return scope[key]
-        raise KeyError(key)
-
-    push = list.append
-
-    def __contains__(self, other):
-        return collections.abc.Mapping.__contains__(self, other)
-
-    def __len__(self):
-        return len(list(iter(self)))
-
-
-# from jaraco.collections 3.7
-class RangeMap(dict):
-    """
-    A dictionary-like object that uses the keys as bounds for a range.
-    Inclusion of the value for that range is determined by the
-    key_match_comparator, which defaults to less-than-or-equal.
-    A value is returned for a key if it is the first key that matches in
-    the sorted list of keys.
-
-    One may supply keyword parameters to be passed to the sort function used
-    to sort keys (i.e. key, reverse) as sort_params.
-
-    Let's create a map that maps 1-3 -> 'a', 4-6 -> 'b'
-
-    >>> r = RangeMap({3: 'a', 6: 'b'})  # boy, that was easy
-    >>> r[1], r[2], r[3], r[4], r[5], r[6]
-    ('a', 'a', 'a', 'b', 'b', 'b')
-
-    Even float values should work so long as the comparison operator
-    supports it.
-
-    >>> r[4.5]
-    'b'
-
-    But you'll notice that the way rangemap is defined, it must be open-ended
-    on one side.
-
-    >>> r[0]
-    'a'
-    >>> r[-1]
-    'a'
-
-    One can close the open-end of the RangeMap by using undefined_value
-
-    >>> r = RangeMap({0: RangeMap.undefined_value, 3: 'a', 6: 'b'})
-    >>> r[0]
-    Traceback (most recent call last):
-    ...
-    KeyError: 0
-
-    One can get the first or last elements in the range by using RangeMap.Item
-
-    >>> last_item = RangeMap.Item(-1)
-    >>> r[last_item]
-    'b'
-
-    .last_item is a shortcut for Item(-1)
-
-    >>> r[RangeMap.last_item]
-    'b'
-
-    Sometimes it's useful to find the bounds for a RangeMap
-
-    >>> r.bounds()
-    (0, 6)
-
-    RangeMap supports .get(key, default)
-
-    >>> r.get(0, 'not found')
-    'not found'
-
-    >>> r.get(7, 'not found')
-    'not found'
-
-    One often wishes to define the ranges by their left-most values,
-    which requires use of sort params and a key_match_comparator.
-
-    >>> r = RangeMap({1: 'a', 4: 'b'},
-    ...     sort_params=dict(reverse=True),
-    ...     key_match_comparator=operator.ge)
-    >>> r[1], r[2], r[3], r[4], r[5], r[6]
-    ('a', 'a', 'a', 'b', 'b', 'b')
-
-    That wasn't nearly as easy as before, so an alternate constructor
-    is provided:
-
-    >>> r = RangeMap.left({1: 'a', 4: 'b', 7: RangeMap.undefined_value})
-    >>> r[1], r[2], r[3], r[4], r[5], r[6]
-    ('a', 'a', 'a', 'b', 'b', 'b')
-
-    """
-
-    def __init__(self, source, sort_params={}, key_match_comparator=operator.le):
-        dict.__init__(self, source)
-        self.sort_params = sort_params
-        self.match = key_match_comparator
-
-    @classmethod
-    def left(cls, source):
-        return cls(
-            source, sort_params=dict(reverse=True), key_match_comparator=operator.ge
-        )
-
-    def __getitem__(self, item):
-        sorted_keys = sorted(self.keys(), **self.sort_params)
-        if isinstance(item, RangeMap.Item):
-            result = self.__getitem__(sorted_keys[item])
-        else:
-            key = self._find_first_match_(sorted_keys, item)
-            result = dict.__getitem__(self, key)
-            if result is RangeMap.undefined_value:
-                raise KeyError(key)
-        return result
-
-    def get(self, key, default=None):
-        """
-        Return the value for key if key is in the dictionary, else default.
-        If default is not given, it defaults to None, so that this method
-        never raises a KeyError.
-        """
-        try:
-            return self[key]
-        except KeyError:
-            return default
-
-    def _find_first_match_(self, keys, item):
-        is_match = functools.partial(self.match, item)
-        matches = list(filter(is_match, keys))
-        if matches:
-            return matches[0]
-        raise KeyError(item)
-
-    def bounds(self):
-        sorted_keys = sorted(self.keys(), **self.sort_params)
-        return (sorted_keys[RangeMap.first_item], sorted_keys[RangeMap.last_item])
-
-    # some special values for the RangeMap
-    undefined_value = type('RangeValueUndefined', (), {})()
-
-    class Item(int):
-        "RangeMap Item"
-
-    first_item = Item(0)
-    last_item = Item(-1)
diff --git a/setuptools/_distutils/_functools.py b/setuptools/_distutils/_functools.py
deleted file mode 100644
index e7053bac12..0000000000
--- a/setuptools/_distutils/_functools.py
+++ /dev/null
@@ -1,20 +0,0 @@
-import functools
-
-
-# from jaraco.functools 3.5
-def pass_none(func):
-    """
-    Wrap func so it's not called if its first param is None
-
-    >>> print_text = pass_none(print)
-    >>> print_text('text')
-    text
-    >>> print_text(None)
-    """
-
-    @functools.wraps(func)
-    def wrapper(param, *args, **kwargs):
-        if param is not None:
-            return func(param, *args, **kwargs)
-
-    return wrapper
diff --git a/setuptools/_distutils/_log.py b/setuptools/_distutils/_log.py
index 4a2ae0acb8..0148f157ff 100644
--- a/setuptools/_distutils/_log.py
+++ b/setuptools/_distutils/_log.py
@@ -1,4 +1,3 @@
 import logging
 
-
 log = logging.getLogger()
diff --git a/setuptools/_distutils/_macos_compat.py b/setuptools/_distutils/_macos_compat.py
index 17769e9154..76ecb96abe 100644
--- a/setuptools/_distutils/_macos_compat.py
+++ b/setuptools/_distutils/_macos_compat.py
@@ -1,5 +1,5 @@
-import sys
 import importlib
+import sys
 
 
 def bypass_compiler_fixup(cmd, args):
diff --git a/setuptools/_distutils/_modified.py b/setuptools/_distutils/_modified.py
new file mode 100644
index 0000000000..f64cab7d61
--- /dev/null
+++ b/setuptools/_distutils/_modified.py
@@ -0,0 +1,95 @@
+"""Timestamp comparison of files and groups of files."""
+
+from __future__ import annotations
+
+import functools
+import os.path
+from collections.abc import Callable, Iterable
+from typing import Literal, TypeVar
+
+from jaraco.functools import splat
+
+from .compat.py39 import zip_strict
+from .errors import DistutilsFileError
+
+_SourcesT = TypeVar(
+    "_SourcesT", bound="str | bytes | os.PathLike[str] | os.PathLike[bytes]"
+)
+_TargetsT = TypeVar(
+    "_TargetsT", bound="str | bytes | os.PathLike[str] | os.PathLike[bytes]"
+)
+
+
+def _newer(source, target):
+    return not os.path.exists(target) or (
+        os.path.getmtime(source) > os.path.getmtime(target)
+    )
+
+
+def newer(
+    source: str | bytes | os.PathLike[str] | os.PathLike[bytes],
+    target: str | bytes | os.PathLike[str] | os.PathLike[bytes],
+) -> bool:
+    """
+    Is source modified more recently than target.
+
+    Returns True if 'source' is modified more recently than
+    'target' or if 'target' does not exist.
+
+    Raises DistutilsFileError if 'source' does not exist.
+    """
+    if not os.path.exists(source):
+        raise DistutilsFileError(f"file {os.path.abspath(source)!r} does not exist")
+
+    return _newer(source, target)
+
+
+def newer_pairwise(
+    sources: Iterable[_SourcesT],
+    targets: Iterable[_TargetsT],
+    newer: Callable[[_SourcesT, _TargetsT], bool] = newer,
+) -> tuple[list[_SourcesT], list[_TargetsT]]:
+    """
+    Filter filenames where sources are newer than targets.
+
+    Walk two filename iterables in parallel, testing if each source is newer
+    than its corresponding target.  Returns a pair of lists (sources,
+    targets) where source is newer than target, according to the semantics
+    of 'newer()'.
+    """
+    newer_pairs = filter(splat(newer), zip_strict(sources, targets))
+    return tuple(map(list, zip(*newer_pairs))) or ([], [])
+
+
+def newer_group(
+    sources: Iterable[str | bytes | os.PathLike[str] | os.PathLike[bytes]],
+    target: str | bytes | os.PathLike[str] | os.PathLike[bytes],
+    missing: Literal["error", "ignore", "newer"] = "error",
+) -> bool:
+    """
+    Is target out-of-date with respect to any file in sources.
+
+    Return True if 'target' is out-of-date with respect to any file
+    listed in 'sources'. In other words, if 'target' exists and is newer
+    than every file in 'sources', return False; otherwise return True.
+    ``missing`` controls how to handle a missing source file:
+
+    - error (default): allow the ``stat()`` call to fail.
+    - ignore: silently disregard any missing source files.
+    - newer: treat missing source files as "target out of date". This
+      mode is handy in "dry-run" mode: it will pretend to carry out
+      commands that wouldn't work because inputs are missing, but
+      that doesn't matter because dry-run won't run the commands.
+    """
+
+    def missing_as_newer(source):
+        return missing == 'newer' and not os.path.exists(source)
+
+    ignored = os.path.exists if missing == 'ignore' else None
+    return not os.path.exists(target) or any(
+        missing_as_newer(source) or _newer(source, target)
+        for source in filter(ignored, sources)
+    )
+
+
+newer_pairwise_group = functools.partial(newer_pairwise, newer=newer_group)
diff --git a/setuptools/_distutils/_msvccompiler.py b/setuptools/_distutils/_msvccompiler.py
index 4f081c7e92..d07c86ef8e 100644
--- a/setuptools/_distutils/_msvccompiler.py
+++ b/setuptools/_distutils/_msvccompiler.py
@@ -1,568 +1,16 @@
-"""distutils._msvccompiler
-
-Contains MSVCCompiler, an implementation of the abstract CCompiler class
-for Microsoft Visual Studio 2015.
-
-The module is compatible with VS 2015 and later. You can find legacy support
-for older versions in distutils.msvc9compiler and distutils.msvccompiler.
-"""
-
-# Written by Perry Stoll
-# hacked by Robin Becker and Thomas Heller to do a better job of
-#   finding DevStudio (through the registry)
-# ported to VS 2005 and VS 2008 by Christian Heimes
-# ported to VS 2015 by Steve Dower
-
-import os
-import subprocess
-import contextlib
 import warnings
-import unittest.mock as mock
-
-with contextlib.suppress(ImportError):
-    import winreg
-
-from .errors import (
-    DistutilsExecError,
-    DistutilsPlatformError,
-    CompileError,
-    LibError,
-    LinkError,
-)
-from .ccompiler import CCompiler, gen_lib_options
-from ._log import log
-from .util import get_platform
-
-from itertools import count
-
-
-def _find_vc2015():
-    try:
-        key = winreg.OpenKeyEx(
-            winreg.HKEY_LOCAL_MACHINE,
-            r"Software\Microsoft\VisualStudio\SxS\VC7",
-            access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY,
-        )
-    except OSError:
-        log.debug("Visual C++ is not registered")
-        return None, None
-
-    best_version = 0
-    best_dir = None
-    with key:
-        for i in count():
-            try:
-                v, vc_dir, vt = winreg.EnumValue(key, i)
-            except OSError:
-                break
-            if v and vt == winreg.REG_SZ and os.path.isdir(vc_dir):
-                try:
-                    version = int(float(v))
-                except (ValueError, TypeError):
-                    continue
-                if version >= 14 and version > best_version:
-                    best_version, best_dir = version, vc_dir
-    return best_version, best_dir
-
-
-def _find_vc2017():
-    """Returns "15, path" based on the result of invoking vswhere.exe
-    If no install is found, returns "None, None"
-
-    The version is returned to avoid unnecessarily changing the function
-    result. It may be ignored when the path is not None.
-
-    If vswhere.exe is not available, by definition, VS 2017 is not
-    installed.
-    """
-    root = os.environ.get("ProgramFiles(x86)") or os.environ.get("ProgramFiles")
-    if not root:
-        return None, None
-
-    try:
-        path = subprocess.check_output(
-            [
-                os.path.join(
-                    root, "Microsoft Visual Studio", "Installer", "vswhere.exe"
-                ),
-                "-latest",
-                "-prerelease",
-                "-requires",
-                "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
-                "-property",
-                "installationPath",
-                "-products",
-                "*",
-            ],
-            encoding="mbcs",
-            errors="strict",
-        ).strip()
-    except (subprocess.CalledProcessError, OSError, UnicodeDecodeError):
-        return None, None
-
-    path = os.path.join(path, "VC", "Auxiliary", "Build")
-    if os.path.isdir(path):
-        return 15, path
-
-    return None, None
-
-
-PLAT_SPEC_TO_RUNTIME = {
-    'x86': 'x86',
-    'x86_amd64': 'x64',
-    'x86_arm': 'arm',
-    'x86_arm64': 'arm64',
-}
-
-
-def _find_vcvarsall(plat_spec):
-    # bpo-38597: Removed vcruntime return value
-    _, best_dir = _find_vc2017()
-
-    if not best_dir:
-        best_version, best_dir = _find_vc2015()
-
-    if not best_dir:
-        log.debug("No suitable Visual C++ version found")
-        return None, None
-
-    vcvarsall = os.path.join(best_dir, "vcvarsall.bat")
-    if not os.path.isfile(vcvarsall):
-        log.debug("%s cannot be found", vcvarsall)
-        return None, None
-
-    return vcvarsall, None
-
-
-def _get_vc_env(plat_spec):
-    if os.getenv("DISTUTILS_USE_SDK"):
-        return {key.lower(): value for key, value in os.environ.items()}
-
-    vcvarsall, _ = _find_vcvarsall(plat_spec)
-    if not vcvarsall:
-        raise DistutilsPlatformError("Unable to find vcvarsall.bat")
-
-    try:
-        out = subprocess.check_output(
-            f'cmd /u /c "{vcvarsall}" {plat_spec} && set',
-            stderr=subprocess.STDOUT,
-        ).decode('utf-16le', errors='replace')
-    except subprocess.CalledProcessError as exc:
-        log.error(exc.output)
-        raise DistutilsPlatformError(f"Error executing {exc.cmd}")
-
-    env = {
-        key.lower(): value
-        for key, _, value in (line.partition('=') for line in out.splitlines())
-        if key and value
-    }
-
-    return env
-
-
-def _find_exe(exe, paths=None):
-    """Return path to an MSVC executable program.
-
-    Tries to find the program in several places: first, one of the
-    MSVC program search paths from the registry; next, the directories
-    in the PATH environment variable.  If any of those work, return an
-    absolute path that is known to exist.  If none of them work, just
-    return the original program name, 'exe'.
-    """
-    if not paths:
-        paths = os.getenv('path').split(os.pathsep)
-    for p in paths:
-        fn = os.path.join(os.path.abspath(p), exe)
-        if os.path.isfile(fn):
-            return fn
-    return exe
-
-
-# A map keyed by get_platform() return values to values accepted by
-# 'vcvarsall.bat'. Always cross-compile from x86 to work with the
-# lighter-weight MSVC installs that do not include native 64-bit tools.
-PLAT_TO_VCVARS = {
-    'win32': 'x86',
-    'win-amd64': 'x86_amd64',
-    'win-arm32': 'x86_arm',
-    'win-arm64': 'x86_arm64',
-}
-
-
-class MSVCCompiler(CCompiler):
-    """Concrete class that implements an interface to Microsoft Visual C++,
-    as defined by the CCompiler abstract class."""
-
-    compiler_type = 'msvc'
-
-    # Just set this so CCompiler's constructor doesn't barf.  We currently
-    # don't use the 'set_executables()' bureaucracy provided by CCompiler,
-    # as it really isn't necessary for this sort of single-compiler class.
-    # Would be nice to have a consistent interface with UnixCCompiler,
-    # though, so it's worth thinking about.
-    executables = {}
 
-    # Private class data (need to distinguish C from C++ source for compiler)
-    _c_extensions = ['.c']
-    _cpp_extensions = ['.cc', '.cpp', '.cxx']
-    _rc_extensions = ['.rc']
-    _mc_extensions = ['.mc']
+from .compilers.C import msvc
 
-    # Needed for the filename generation methods provided by the
-    # base class, CCompiler.
-    src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions
-    res_extension = '.res'
-    obj_extension = '.obj'
-    static_lib_extension = '.lib'
-    shared_lib_extension = '.dll'
-    static_lib_format = shared_lib_format = '%s%s'
-    exe_extension = '.exe'
+__all__ = ["MSVCCompiler"]
 
-    def __init__(self, verbose=0, dry_run=0, force=0):
-        super().__init__(verbose, dry_run, force)
-        # target platform (.plat_name is consistent with 'bdist')
-        self.plat_name = None
-        self.initialized = False
+MSVCCompiler = msvc.Compiler
 
-    @classmethod
-    def _configure(cls, vc_env):
-        """
-        Set class-level include/lib dirs.
-        """
-        cls.include_dirs = cls._parse_path(vc_env.get('include', ''))
-        cls.library_dirs = cls._parse_path(vc_env.get('lib', ''))
 
-    @staticmethod
-    def _parse_path(val):
-        return [dir.rstrip(os.sep) for dir in val.split(os.pathsep) if dir]
-
-    def initialize(self, plat_name=None):
-        # multi-init means we would need to check platform same each time...
-        assert not self.initialized, "don't init multiple times"
-        if plat_name is None:
-            plat_name = get_platform()
-        # sanity check for platforms to prevent obscure errors later.
-        if plat_name not in PLAT_TO_VCVARS:
-            raise DistutilsPlatformError(
-                f"--plat-name must be one of {tuple(PLAT_TO_VCVARS)}"
-            )
-
-        # Get the vcvarsall.bat spec for the requested platform.
-        plat_spec = PLAT_TO_VCVARS[plat_name]
-
-        vc_env = _get_vc_env(plat_spec)
-        if not vc_env:
-            raise DistutilsPlatformError(
-                "Unable to find a compatible " "Visual Studio installation."
-            )
-        self._configure(vc_env)
-
-        self._paths = vc_env.get('path', '')
-        paths = self._paths.split(os.pathsep)
-        self.cc = _find_exe("cl.exe", paths)
-        self.linker = _find_exe("link.exe", paths)
-        self.lib = _find_exe("lib.exe", paths)
-        self.rc = _find_exe("rc.exe", paths)  # resource compiler
-        self.mc = _find_exe("mc.exe", paths)  # message compiler
-        self.mt = _find_exe("mt.exe", paths)  # message compiler
-
-        self.preprocess_options = None
-        # bpo-38597: Always compile with dynamic linking
-        # Future releases of Python 3.x will include all past
-        # versions of vcruntime*.dll for compatibility.
-        self.compile_options = ['/nologo', '/O2', '/W3', '/GL', '/DNDEBUG', '/MD']
-
-        self.compile_options_debug = [
-            '/nologo',
-            '/Od',
-            '/MDd',
-            '/Zi',
-            '/W3',
-            '/D_DEBUG',
-        ]
-
-        ldflags = ['/nologo', '/INCREMENTAL:NO', '/LTCG']
-
-        ldflags_debug = ['/nologo', '/INCREMENTAL:NO', '/LTCG', '/DEBUG:FULL']
-
-        self.ldflags_exe = [*ldflags, '/MANIFEST:EMBED,ID=1']
-        self.ldflags_exe_debug = [*ldflags_debug, '/MANIFEST:EMBED,ID=1']
-        self.ldflags_shared = [
-            *ldflags,
-            '/DLL',
-            '/MANIFEST:EMBED,ID=2',
-            '/MANIFESTUAC:NO',
-        ]
-        self.ldflags_shared_debug = [
-            *ldflags_debug,
-            '/DLL',
-            '/MANIFEST:EMBED,ID=2',
-            '/MANIFESTUAC:NO',
-        ]
-        self.ldflags_static = [*ldflags]
-        self.ldflags_static_debug = [*ldflags_debug]
-
-        self._ldflags = {
-            (CCompiler.EXECUTABLE, None): self.ldflags_exe,
-            (CCompiler.EXECUTABLE, False): self.ldflags_exe,
-            (CCompiler.EXECUTABLE, True): self.ldflags_exe_debug,
-            (CCompiler.SHARED_OBJECT, None): self.ldflags_shared,
-            (CCompiler.SHARED_OBJECT, False): self.ldflags_shared,
-            (CCompiler.SHARED_OBJECT, True): self.ldflags_shared_debug,
-            (CCompiler.SHARED_LIBRARY, None): self.ldflags_static,
-            (CCompiler.SHARED_LIBRARY, False): self.ldflags_static,
-            (CCompiler.SHARED_LIBRARY, True): self.ldflags_static_debug,
-        }
-
-        self.initialized = True
-
-    # -- Worker methods ------------------------------------------------
-
-    @property
-    def out_extensions(self):
-        return {
-            **super().out_extensions,
-            **{
-                ext: self.res_extension
-                for ext in self._rc_extensions + self._mc_extensions
-            },
-        }
-
-    def compile(  # noqa: C901
-        self,
-        sources,
-        output_dir=None,
-        macros=None,
-        include_dirs=None,
-        debug=0,
-        extra_preargs=None,
-        extra_postargs=None,
-        depends=None,
-    ):
-        if not self.initialized:
-            self.initialize()
-        compile_info = self._setup_compile(
-            output_dir, macros, include_dirs, sources, depends, extra_postargs
+def __getattr__(name):
+    if name == '_get_vc_env':
+        warnings.warn(
+            "_get_vc_env is private; find an alternative (pypa/distutils#340)"
         )
-        macros, objects, extra_postargs, pp_opts, build = compile_info
-
-        compile_opts = extra_preargs or []
-        compile_opts.append('/c')
-        if debug:
-            compile_opts.extend(self.compile_options_debug)
-        else:
-            compile_opts.extend(self.compile_options)
-
-        add_cpp_opts = False
-
-        for obj in objects:
-            try:
-                src, ext = build[obj]
-            except KeyError:
-                continue
-            if debug:
-                # pass the full pathname to MSVC in debug mode,
-                # this allows the debugger to find the source file
-                # without asking the user to browse for it
-                src = os.path.abspath(src)
-
-            if ext in self._c_extensions:
-                input_opt = "/Tc" + src
-            elif ext in self._cpp_extensions:
-                input_opt = "/Tp" + src
-                add_cpp_opts = True
-            elif ext in self._rc_extensions:
-                # compile .RC to .RES file
-                input_opt = src
-                output_opt = "/fo" + obj
-                try:
-                    self.spawn([self.rc] + pp_opts + [output_opt, input_opt])
-                except DistutilsExecError as msg:
-                    raise CompileError(msg)
-                continue
-            elif ext in self._mc_extensions:
-                # Compile .MC to .RC file to .RES file.
-                #   * '-h dir' specifies the directory for the
-                #     generated include file
-                #   * '-r dir' specifies the target directory of the
-                #     generated RC file and the binary message resource
-                #     it includes
-                #
-                # For now (since there are no options to change this),
-                # we use the source-directory for the include file and
-                # the build directory for the RC file and message
-                # resources. This works at least for win32all.
-                h_dir = os.path.dirname(src)
-                rc_dir = os.path.dirname(obj)
-                try:
-                    # first compile .MC to .RC and .H file
-                    self.spawn([self.mc, '-h', h_dir, '-r', rc_dir, src])
-                    base, _ = os.path.splitext(os.path.basename(src))
-                    rc_file = os.path.join(rc_dir, base + '.rc')
-                    # then compile .RC to .RES file
-                    self.spawn([self.rc, "/fo" + obj, rc_file])
-
-                except DistutilsExecError as msg:
-                    raise CompileError(msg)
-                continue
-            else:
-                # how to handle this file?
-                raise CompileError(f"Don't know how to compile {src} to {obj}")
-
-            args = [self.cc] + compile_opts + pp_opts
-            if add_cpp_opts:
-                args.append('/EHsc')
-            args.extend((input_opt, "/Fo" + obj))
-            args.extend(extra_postargs)
-
-            try:
-                self.spawn(args)
-            except DistutilsExecError as msg:
-                raise CompileError(msg)
-
-        return objects
-
-    def create_static_lib(
-        self, objects, output_libname, output_dir=None, debug=0, target_lang=None
-    ):
-        if not self.initialized:
-            self.initialize()
-        objects, output_dir = self._fix_object_args(objects, output_dir)
-        output_filename = self.library_filename(output_libname, output_dir=output_dir)
-
-        if self._need_link(objects, output_filename):
-            lib_args = objects + ['/OUT:' + output_filename]
-            if debug:
-                pass  # XXX what goes here?
-            try:
-                log.debug('Executing "%s" %s', self.lib, ' '.join(lib_args))
-                self.spawn([self.lib] + lib_args)
-            except DistutilsExecError as msg:
-                raise LibError(msg)
-        else:
-            log.debug("skipping %s (up-to-date)", output_filename)
-
-    def link(
-        self,
-        target_desc,
-        objects,
-        output_filename,
-        output_dir=None,
-        libraries=None,
-        library_dirs=None,
-        runtime_library_dirs=None,
-        export_symbols=None,
-        debug=0,
-        extra_preargs=None,
-        extra_postargs=None,
-        build_temp=None,
-        target_lang=None,
-    ):
-        if not self.initialized:
-            self.initialize()
-        objects, output_dir = self._fix_object_args(objects, output_dir)
-        fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
-        libraries, library_dirs, runtime_library_dirs = fixed_args
-
-        if runtime_library_dirs:
-            self.warn(
-                "I don't know what to do with 'runtime_library_dirs': "
-                + str(runtime_library_dirs)
-            )
-
-        lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
-        if output_dir is not None:
-            output_filename = os.path.join(output_dir, output_filename)
-
-        if self._need_link(objects, output_filename):
-            ldflags = self._ldflags[target_desc, debug]
-
-            export_opts = ["/EXPORT:" + sym for sym in (export_symbols or [])]
-
-            ld_args = (
-                ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename]
-            )
-
-            # The MSVC linker generates .lib and .exp files, which cannot be
-            # suppressed by any linker switches. The .lib files may even be
-            # needed! Make sure they are generated in the temporary build
-            # directory. Since they have different names for debug and release
-            # builds, they can go into the same directory.
-            build_temp = os.path.dirname(objects[0])
-            if export_symbols is not None:
-                (dll_name, dll_ext) = os.path.splitext(
-                    os.path.basename(output_filename)
-                )
-                implib_file = os.path.join(build_temp, self.library_filename(dll_name))
-                ld_args.append('/IMPLIB:' + implib_file)
-
-            if extra_preargs:
-                ld_args[:0] = extra_preargs
-            if extra_postargs:
-                ld_args.extend(extra_postargs)
-
-            output_dir = os.path.dirname(os.path.abspath(output_filename))
-            self.mkpath(output_dir)
-            try:
-                log.debug('Executing "%s" %s', self.linker, ' '.join(ld_args))
-                self.spawn([self.linker] + ld_args)
-            except DistutilsExecError as msg:
-                raise LinkError(msg)
-        else:
-            log.debug("skipping %s (up-to-date)", output_filename)
-
-    def spawn(self, cmd):
-        env = dict(os.environ, PATH=self._paths)
-        with self._fallback_spawn(cmd, env) as fallback:
-            return super().spawn(cmd, env=env)
-        return fallback.value
-
-    @contextlib.contextmanager
-    def _fallback_spawn(self, cmd, env):
-        """
-        Discovered in pypa/distutils#15, some tools monkeypatch the compiler,
-        so the 'env' kwarg causes a TypeError. Detect this condition and
-        restore the legacy, unsafe behavior.
-        """
-        bag = type('Bag', (), {})()
-        try:
-            yield bag
-        except TypeError as exc:
-            if "unexpected keyword argument 'env'" not in str(exc):
-                raise
-        else:
-            return
-        warnings.warn("Fallback spawn triggered. Please update distutils monkeypatch.")
-        with mock.patch.dict('os.environ', env):
-            bag.value = super().spawn(cmd)
-
-    # -- Miscellaneous methods -----------------------------------------
-    # These are all used by the 'gen_lib_options() function, in
-    # ccompiler.py.
-
-    def library_dir_option(self, dir):
-        return "/LIBPATH:" + dir
-
-    def runtime_library_dir_option(self, dir):
-        raise DistutilsPlatformError(
-            "don't know how to set runtime library search path for MSVC"
-        )
-
-    def library_option(self, lib):
-        return self.library_filename(lib)
-
-    def find_library_file(self, dirs, lib, debug=0):
-        # Prefer a debugging library if found (and requested), but deal
-        # with it if we don't have one.
-        if debug:
-            try_names = [lib + "_d", lib]
-        else:
-            try_names = [lib]
-        for dir in dirs:
-            for name in try_names:
-                libfile = os.path.join(dir, self.library_filename(name))
-                if os.path.isfile(libfile):
-                    return libfile
-        else:
-            # Oops, didn't find it in *any* of 'dirs'
-            return None
+        return msvc._get_vc_env
+    raise AttributeError(name)
diff --git a/setuptools/_distutils/archive_util.py b/setuptools/_distutils/archive_util.py
index 7f9e1e00cc..4a7fb9c9e7 100644
--- a/setuptools/_distutils/archive_util.py
+++ b/setuptools/_distutils/archive_util.py
@@ -3,9 +3,10 @@
 Utility functions for creating archive files (tarballs, zip files,
 that sort of thing)."""
 
+from __future__ import annotations
+
 import os
-from warnings import warn
-import sys
+from typing import Literal, overload
 
 try:
     import zipfile
@@ -13,10 +14,10 @@
     zipfile = None
 
 
+from ._log import log
+from .dir_util import mkpath
 from .errors import DistutilsExecError
 from .spawn import spawn
-from .dir_util import mkpath
-from ._log import log
 
 try:
     from pwd import getpwnam
@@ -56,13 +57,17 @@ def _get_uid(name):
 
 
 def make_tarball(
-    base_name, base_dir, compress="gzip", verbose=0, dry_run=0, owner=None, group=None
-):
+    base_name: str,
+    base_dir: str | os.PathLike[str],
+    compress: Literal["gzip", "bzip2", "xz"] | None = "gzip",
+    verbose: bool = False,
+    owner: str | None = None,
+    group: str | None = None,
+) -> str:
     """Create a (possibly compressed) tar file from all the files under
     'base_dir'.
 
-    'compress' must be "gzip" (the default), "bzip2", "xz", "compress", or
-    None.  ("compress" will be deprecated in Python 3.2)
+    'compress' must be "gzip" (the default), "bzip2", "xz", or None.
 
     'owner' and 'group' can be used to define an owner and a group for the
     archive that is being built. If not provided, the current owner and group
@@ -78,22 +83,19 @@ def make_tarball(
         'bzip2': 'bz2',
         'xz': 'xz',
         None: '',
-        'compress': '',
     }
-    compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'xz': '.xz', 'compress': '.Z'}
+    compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'xz': '.xz'}
 
     # flags for compression program, each element of list will be an argument
     if compress is not None and compress not in compress_ext.keys():
         raise ValueError(
-            "bad value for 'compress': must be None, 'gzip', 'bzip2', "
-            "'xz' or 'compress'"
+            "bad value for 'compress': must be None, 'gzip', 'bzip2', 'xz'"
         )
 
     archive_name = base_name + '.tar'
-    if compress != 'compress':
-        archive_name += compress_ext.get(compress, '')
+    archive_name += compress_ext.get(compress, '')
 
-    mkpath(os.path.dirname(archive_name), dry_run=dry_run)
+    mkpath(os.path.dirname(archive_name))
 
     # creating the tarball
     import tarfile  # late import so Python build itself doesn't break
@@ -112,29 +114,20 @@ def _set_uid_gid(tarinfo):
             tarinfo.uname = owner
         return tarinfo
 
-    if not dry_run:
-        tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress])
-        try:
-            tar.add(base_dir, filter=_set_uid_gid)
-        finally:
-            tar.close()
-
-    # compression using `compress`
-    if compress == 'compress':
-        warn("'compress' is deprecated.", DeprecationWarning)
-        # the option varies depending on the platform
-        compressed_name = archive_name + compress_ext[compress]
-        if sys.platform == 'win32':
-            cmd = [compress, archive_name, compressed_name]
-        else:
-            cmd = [compress, '-f', archive_name]
-        spawn(cmd, dry_run=dry_run)
-        return compressed_name
+    tar = tarfile.open(archive_name, f'w|{tar_compression[compress]}')
+    try:
+        tar.add(base_dir, filter=_set_uid_gid)
+    finally:
+        tar.close()
 
     return archive_name
 
 
-def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):  # noqa: C901
+def make_zipfile(
+    base_name: str,
+    base_dir: str | os.PathLike[str],
+    verbose: bool = False,
+) -> str:
     """Create a zip file from all the files under 'base_dir'.
 
     The output zip file will be named 'base_name' + ".zip".  Uses either the
@@ -144,7 +137,7 @@ def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):  # noqa: C901
     file.
     """
     zip_filename = base_name + ".zip"
-    mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
+    mkpath(os.path.dirname(zip_filename))
 
     # If zipfile module is not available, try spawning an external
     # 'zip' command.
@@ -155,45 +148,39 @@ def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):  # noqa: C901
             zipoptions = "-rq"
 
         try:
-            spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run)
+            spawn(["zip", zipoptions, zip_filename, base_dir])
         except DistutilsExecError:
             # XXX really should distinguish between "couldn't find
             # external 'zip' command" and "zip failed".
             raise DistutilsExecError(
-                (
-                    "unable to create zip file '%s': "
-                    "could neither import the 'zipfile' module nor "
-                    "find a standalone zip utility"
-                )
-                % zip_filename
+                f"unable to create zip file '{zip_filename}': "
+                "could neither import the 'zipfile' module nor "
+                "find a standalone zip utility"
             )
 
     else:
         log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
 
-        if not dry_run:
-            try:
-                zip = zipfile.ZipFile(
-                    zip_filename, "w", compression=zipfile.ZIP_DEFLATED
-                )
-            except RuntimeError:
-                zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_STORED)
-
-            with zip:
-                if base_dir != os.curdir:
-                    path = os.path.normpath(os.path.join(base_dir, ''))
+        try:
+            zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED)
+        except RuntimeError:
+            zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_STORED)
+
+        with zip:
+            if base_dir != os.curdir:
+                path = os.path.normpath(os.path.join(base_dir, ''))
+                zip.write(path, path)
+                log.info("adding '%s'", path)
+            for dirpath, dirnames, filenames in os.walk(base_dir):
+                for name in dirnames:
+                    path = os.path.normpath(os.path.join(dirpath, name, ''))
                     zip.write(path, path)
                     log.info("adding '%s'", path)
-                for dirpath, dirnames, filenames in os.walk(base_dir):
-                    for name in dirnames:
-                        path = os.path.normpath(os.path.join(dirpath, name, ''))
+                for name in filenames:
+                    path = os.path.normpath(os.path.join(dirpath, name))
+                    if os.path.isfile(path):
                         zip.write(path, path)
                         log.info("adding '%s'", path)
-                    for name in filenames:
-                        path = os.path.normpath(os.path.join(dirpath, name))
-                        if os.path.isfile(path):
-                            zip.write(path, path)
-                            log.info("adding '%s'", path)
 
     return zip_filename
 
@@ -219,16 +206,35 @@ def check_archive_formats(formats):
     return None
 
 
+@overload
+def make_archive(
+    base_name: str,
+    format: str,
+    root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None,
+    base_dir: str | None = None,
+    verbose: bool = False,
+    owner: str | None = None,
+    group: str | None = None,
+) -> str: ...
+@overload
+def make_archive(
+    base_name: str | os.PathLike[str],
+    format: str,
+    root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+    base_dir: str | None = None,
+    verbose: bool = False,
+    owner: str | None = None,
+    group: str | None = None,
+) -> str: ...
 def make_archive(
-    base_name,
-    format,
-    root_dir=None,
-    base_dir=None,
-    verbose=0,
-    dry_run=0,
-    owner=None,
-    group=None,
-):
+    base_name: str | os.PathLike[str],
+    format: str,
+    root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None,
+    base_dir: str | None = None,
+    verbose: bool = False,
+    owner: str | None = None,
+    group: str | None = None,
+) -> str:
     """Create an archive file (eg. zip or tar).
 
     'base_name' is the name of the file to create, minus any format-specific
@@ -249,22 +255,20 @@ def make_archive(
     if root_dir is not None:
         log.debug("changing into '%s'", root_dir)
         base_name = os.path.abspath(base_name)
-        if not dry_run:
-            os.chdir(root_dir)
+        os.chdir(root_dir)
 
     if base_dir is None:
         base_dir = os.curdir
 
-    kwargs = {'dry_run': dry_run}
+    kwargs: dict[str, bool | None] = {}
 
     try:
         format_info = ARCHIVE_FORMATS[format]
     except KeyError:
-        raise ValueError("unknown archive format '%s'" % format)
+        raise ValueError(f"unknown archive format '{format}'")
 
     func = format_info[0]
-    for arg, val in format_info[1]:
-        kwargs[arg] = val
+    kwargs.update(format_info[1])
 
     if format != 'zip':
         kwargs['owner'] = owner
diff --git a/setuptools/_distutils/bcppcompiler.py b/setuptools/_distutils/bcppcompiler.py
deleted file mode 100644
index ba45ea2b95..0000000000
--- a/setuptools/_distutils/bcppcompiler.py
+++ /dev/null
@@ -1,401 +0,0 @@
-"""distutils.bcppcompiler
-
-Contains BorlandCCompiler, an implementation of the abstract CCompiler class
-for the Borland C++ compiler.
-"""
-
-# This implementation by Lyle Johnson, based on the original msvccompiler.py
-# module and using the directions originally published by Gordon Williams.
-
-# XXX looks like there's a LOT of overlap between these two classes:
-# someone should sit down and factor out the common code as
-# WindowsCCompiler!  --GPW
-
-
-import os
-import warnings
-
-from .errors import (
-    DistutilsExecError,
-    CompileError,
-    LibError,
-    LinkError,
-    UnknownFileError,
-)
-from .ccompiler import CCompiler, gen_preprocess_options
-from .file_util import write_file
-from .dep_util import newer
-from ._log import log
-
-
-warnings.warn(
-    "bcppcompiler is deprecated and slated to be removed "
-    "in the future. Please discontinue use or file an issue "
-    "with pypa/distutils describing your use case.",
-    DeprecationWarning,
-)
-
-
-class BCPPCompiler(CCompiler):
-    """Concrete class that implements an interface to the Borland C/C++
-    compiler, as defined by the CCompiler abstract class.
-    """
-
-    compiler_type = 'bcpp'
-
-    # Just set this so CCompiler's constructor doesn't barf.  We currently
-    # don't use the 'set_executables()' bureaucracy provided by CCompiler,
-    # as it really isn't necessary for this sort of single-compiler class.
-    # Would be nice to have a consistent interface with UnixCCompiler,
-    # though, so it's worth thinking about.
-    executables = {}
-
-    # Private class data (need to distinguish C from C++ source for compiler)
-    _c_extensions = ['.c']
-    _cpp_extensions = ['.cc', '.cpp', '.cxx']
-
-    # Needed for the filename generation methods provided by the
-    # base class, CCompiler.
-    src_extensions = _c_extensions + _cpp_extensions
-    obj_extension = '.obj'
-    static_lib_extension = '.lib'
-    shared_lib_extension = '.dll'
-    static_lib_format = shared_lib_format = '%s%s'
-    exe_extension = '.exe'
-
-    def __init__(self, verbose=0, dry_run=0, force=0):
-        super().__init__(verbose, dry_run, force)
-
-        # These executables are assumed to all be in the path.
-        # Borland doesn't seem to use any special registry settings to
-        # indicate their installation locations.
-
-        self.cc = "bcc32.exe"
-        self.linker = "ilink32.exe"
-        self.lib = "tlib.exe"
-
-        self.preprocess_options = None
-        self.compile_options = ['/tWM', '/O2', '/q', '/g0']
-        self.compile_options_debug = ['/tWM', '/Od', '/q', '/g0']
-
-        self.ldflags_shared = ['/Tpd', '/Gn', '/q', '/x']
-        self.ldflags_shared_debug = ['/Tpd', '/Gn', '/q', '/x']
-        self.ldflags_static = []
-        self.ldflags_exe = ['/Gn', '/q', '/x']
-        self.ldflags_exe_debug = ['/Gn', '/q', '/x', '/r']
-
-    # -- Worker methods ------------------------------------------------
-
-    def compile(  # noqa: C901
-        self,
-        sources,
-        output_dir=None,
-        macros=None,
-        include_dirs=None,
-        debug=0,
-        extra_preargs=None,
-        extra_postargs=None,
-        depends=None,
-    ):
-        macros, objects, extra_postargs, pp_opts, build = self._setup_compile(
-            output_dir, macros, include_dirs, sources, depends, extra_postargs
-        )
-        compile_opts = extra_preargs or []
-        compile_opts.append('-c')
-        if debug:
-            compile_opts.extend(self.compile_options_debug)
-        else:
-            compile_opts.extend(self.compile_options)
-
-        for obj in objects:
-            try:
-                src, ext = build[obj]
-            except KeyError:
-                continue
-            # XXX why do the normpath here?
-            src = os.path.normpath(src)
-            obj = os.path.normpath(obj)
-            # XXX _setup_compile() did a mkpath() too but before the normpath.
-            # Is it possible to skip the normpath?
-            self.mkpath(os.path.dirname(obj))
-
-            if ext == '.res':
-                # This is already a binary file -- skip it.
-                continue  # the 'for' loop
-            if ext == '.rc':
-                # This needs to be compiled to a .res file -- do it now.
-                try:
-                    self.spawn(["brcc32", "-fo", obj, src])
-                except DistutilsExecError as msg:
-                    raise CompileError(msg)
-                continue  # the 'for' loop
-
-            # The next two are both for the real compiler.
-            if ext in self._c_extensions:
-                input_opt = ""
-            elif ext in self._cpp_extensions:
-                input_opt = "-P"
-            else:
-                # Unknown file type -- no extra options.  The compiler
-                # will probably fail, but let it just in case this is a
-                # file the compiler recognizes even if we don't.
-                input_opt = ""
-
-            output_opt = "-o" + obj
-
-            # Compiler command line syntax is: "bcc32 [options] file(s)".
-            # Note that the source file names must appear at the end of
-            # the command line.
-            try:
-                self.spawn(
-                    [self.cc]
-                    + compile_opts
-                    + pp_opts
-                    + [input_opt, output_opt]
-                    + extra_postargs
-                    + [src]
-                )
-            except DistutilsExecError as msg:
-                raise CompileError(msg)
-
-        return objects
-
-    # compile ()
-
-    def create_static_lib(
-        self, objects, output_libname, output_dir=None, debug=0, target_lang=None
-    ):
-        (objects, output_dir) = self._fix_object_args(objects, output_dir)
-        output_filename = self.library_filename(output_libname, output_dir=output_dir)
-
-        if self._need_link(objects, output_filename):
-            lib_args = [output_filename, '/u'] + objects
-            if debug:
-                pass  # XXX what goes here?
-            try:
-                self.spawn([self.lib] + lib_args)
-            except DistutilsExecError as msg:
-                raise LibError(msg)
-        else:
-            log.debug("skipping %s (up-to-date)", output_filename)
-
-    # create_static_lib ()
-
-    def link(  # noqa: C901
-        self,
-        target_desc,
-        objects,
-        output_filename,
-        output_dir=None,
-        libraries=None,
-        library_dirs=None,
-        runtime_library_dirs=None,
-        export_symbols=None,
-        debug=0,
-        extra_preargs=None,
-        extra_postargs=None,
-        build_temp=None,
-        target_lang=None,
-    ):
-        # XXX this ignores 'build_temp'!  should follow the lead of
-        # msvccompiler.py
-
-        (objects, output_dir) = self._fix_object_args(objects, output_dir)
-        (libraries, library_dirs, runtime_library_dirs) = self._fix_lib_args(
-            libraries, library_dirs, runtime_library_dirs
-        )
-
-        if runtime_library_dirs:
-            log.warning(
-                "I don't know what to do with 'runtime_library_dirs': %s",
-                str(runtime_library_dirs),
-            )
-
-        if output_dir is not None:
-            output_filename = os.path.join(output_dir, output_filename)
-
-        if self._need_link(objects, output_filename):
-            # Figure out linker args based on type of target.
-            if target_desc == CCompiler.EXECUTABLE:
-                startup_obj = 'c0w32'
-                if debug:
-                    ld_args = self.ldflags_exe_debug[:]
-                else:
-                    ld_args = self.ldflags_exe[:]
-            else:
-                startup_obj = 'c0d32'
-                if debug:
-                    ld_args = self.ldflags_shared_debug[:]
-                else:
-                    ld_args = self.ldflags_shared[:]
-
-            # Create a temporary exports file for use by the linker
-            if export_symbols is None:
-                def_file = ''
-            else:
-                head, tail = os.path.split(output_filename)
-                modname, ext = os.path.splitext(tail)
-                temp_dir = os.path.dirname(objects[0])  # preserve tree structure
-                def_file = os.path.join(temp_dir, '%s.def' % modname)
-                contents = ['EXPORTS']
-                for sym in export_symbols or []:
-                    contents.append('  {}=_{}'.format(sym, sym))
-                self.execute(write_file, (def_file, contents), "writing %s" % def_file)
-
-            # Borland C++ has problems with '/' in paths
-            objects2 = map(os.path.normpath, objects)
-            # split objects in .obj and .res files
-            # Borland C++ needs them at different positions in the command line
-            objects = [startup_obj]
-            resources = []
-            for file in objects2:
-                (base, ext) = os.path.splitext(os.path.normcase(file))
-                if ext == '.res':
-                    resources.append(file)
-                else:
-                    objects.append(file)
-
-            for ell in library_dirs:
-                ld_args.append("/L%s" % os.path.normpath(ell))
-            ld_args.append("/L.")  # we sometimes use relative paths
-
-            # list of object files
-            ld_args.extend(objects)
-
-            # XXX the command-line syntax for Borland C++ is a bit wonky;
-            # certain filenames are jammed together in one big string, but
-            # comma-delimited.  This doesn't mesh too well with the
-            # Unix-centric attitude (with a DOS/Windows quoting hack) of
-            # 'spawn()', so constructing the argument list is a bit
-            # awkward.  Note that doing the obvious thing and jamming all
-            # the filenames and commas into one argument would be wrong,
-            # because 'spawn()' would quote any filenames with spaces in
-            # them.  Arghghh!.  Apparently it works fine as coded...
-
-            # name of dll/exe file
-            ld_args.extend([',', output_filename])
-            # no map file and start libraries
-            ld_args.append(',,')
-
-            for lib in libraries:
-                # see if we find it and if there is a bcpp specific lib
-                # (xxx_bcpp.lib)
-                libfile = self.find_library_file(library_dirs, lib, debug)
-                if libfile is None:
-                    ld_args.append(lib)
-                    # probably a BCPP internal library -- don't warn
-                else:
-                    # full name which prefers bcpp_xxx.lib over xxx.lib
-                    ld_args.append(libfile)
-
-            # some default libraries
-            ld_args.extend(('import32', 'cw32mt'))
-
-            # def file for export symbols
-            ld_args.extend([',', def_file])
-            # add resource files
-            ld_args.append(',')
-            ld_args.extend(resources)
-
-            if extra_preargs:
-                ld_args[:0] = extra_preargs
-            if extra_postargs:
-                ld_args.extend(extra_postargs)
-
-            self.mkpath(os.path.dirname(output_filename))
-            try:
-                self.spawn([self.linker] + ld_args)
-            except DistutilsExecError as msg:
-                raise LinkError(msg)
-
-        else:
-            log.debug("skipping %s (up-to-date)", output_filename)
-
-    # link ()
-
-    # -- Miscellaneous methods -----------------------------------------
-
-    def find_library_file(self, dirs, lib, debug=0):
-        # List of effective library names to try, in order of preference:
-        # xxx_bcpp.lib is better than xxx.lib
-        # and xxx_d.lib is better than xxx.lib if debug is set
-        #
-        # The "_bcpp" suffix is to handle a Python installation for people
-        # with multiple compilers (primarily Distutils hackers, I suspect
-        # ;-).  The idea is they'd have one static library for each
-        # compiler they care about, since (almost?) every Windows compiler
-        # seems to have a different format for static libraries.
-        if debug:
-            dlib = lib + "_d"
-            try_names = (dlib + "_bcpp", lib + "_bcpp", dlib, lib)
-        else:
-            try_names = (lib + "_bcpp", lib)
-
-        for dir in dirs:
-            for name in try_names:
-                libfile = os.path.join(dir, self.library_filename(name))
-                if os.path.exists(libfile):
-                    return libfile
-        else:
-            # Oops, didn't find it in *any* of 'dirs'
-            return None
-
-    # overwrite the one from CCompiler to support rc and res-files
-    def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
-        if output_dir is None:
-            output_dir = ''
-        obj_names = []
-        for src_name in source_filenames:
-            # use normcase to make sure '.rc' is really '.rc' and not '.RC'
-            (base, ext) = os.path.splitext(os.path.normcase(src_name))
-            if ext not in (self.src_extensions + ['.rc', '.res']):
-                raise UnknownFileError(
-                    "unknown file type '{}' (from '{}')".format(ext, src_name)
-                )
-            if strip_dir:
-                base = os.path.basename(base)
-            if ext == '.res':
-                # these can go unchanged
-                obj_names.append(os.path.join(output_dir, base + ext))
-            elif ext == '.rc':
-                # these need to be compiled to .res-files
-                obj_names.append(os.path.join(output_dir, base + '.res'))
-            else:
-                obj_names.append(os.path.join(output_dir, base + self.obj_extension))
-        return obj_names
-
-    # object_filenames ()
-
-    def preprocess(
-        self,
-        source,
-        output_file=None,
-        macros=None,
-        include_dirs=None,
-        extra_preargs=None,
-        extra_postargs=None,
-    ):
-        (_, macros, include_dirs) = self._fix_compile_args(None, macros, include_dirs)
-        pp_opts = gen_preprocess_options(macros, include_dirs)
-        pp_args = ['cpp32.exe'] + pp_opts
-        if output_file is not None:
-            pp_args.append('-o' + output_file)
-        if extra_preargs:
-            pp_args[:0] = extra_preargs
-        if extra_postargs:
-            pp_args.extend(extra_postargs)
-        pp_args.append(source)
-
-        # We need to preprocess: either we're being forced to, or the
-        # source file is newer than the target (or the target doesn't
-        # exist).
-        if self.force or output_file is None or newer(source, output_file):
-            if output_file:
-                self.mkpath(os.path.dirname(output_file))
-            try:
-                self.spawn(pp_args)
-            except DistutilsExecError as msg:
-                print(msg)
-                raise CompileError(msg)
-
-    # preprocess()
diff --git a/setuptools/_distutils/ccompiler.py b/setuptools/_distutils/ccompiler.py
index 1818fce901..58bc6a55e2 100644
--- a/setuptools/_distutils/ccompiler.py
+++ b/setuptools/_distutils/ccompiler.py
@@ -1,1254 +1,26 @@
-"""distutils.ccompiler
-
-Contains CCompiler, an abstract base class that defines the interface
-for the Distutils compiler abstraction model."""
-
-import sys
-import os
-import re
-import warnings
-
-from .errors import (
-    CompileError,
-    LinkError,
-    UnknownFileError,
-    DistutilsPlatformError,
-    DistutilsModuleError,
+from .compat.numpy import (  # noqa: F401
+    _default_compilers,
+    compiler_class,
 )
-from .spawn import spawn
-from .file_util import move_file
-from .dir_util import mkpath
-from .dep_util import newer_group
-from .util import split_quoted, execute
-from ._log import log
-
-
-class CCompiler:
-    """Abstract base class to define the interface that must be implemented
-    by real compiler classes.  Also has some utility methods used by
-    several compiler classes.
-
-    The basic idea behind a compiler abstraction class is that each
-    instance can be used for all the compile/link steps in building a
-    single project.  Thus, attributes common to all of those compile and
-    link steps -- include directories, macros to define, libraries to link
-    against, etc. -- are attributes of the compiler instance.  To allow for
-    variability in how individual files are treated, most of those
-    attributes may be varied on a per-compilation or per-link basis.
-    """
-
-    # 'compiler_type' is a class attribute that identifies this class.  It
-    # keeps code that wants to know what kind of compiler it's dealing with
-    # from having to import all possible compiler classes just to do an
-    # 'isinstance'.  In concrete CCompiler subclasses, 'compiler_type'
-    # should really, really be one of the keys of the 'compiler_class'
-    # dictionary (see below -- used by the 'new_compiler()' factory
-    # function) -- authors of new compiler interface classes are
-    # responsible for updating 'compiler_class'!
-    compiler_type = None
-
-    # XXX things not handled by this compiler abstraction model:
-    #   * client can't provide additional options for a compiler,
-    #     e.g. warning, optimization, debugging flags.  Perhaps this
-    #     should be the domain of concrete compiler abstraction classes
-    #     (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base
-    #     class should have methods for the common ones.
-    #   * can't completely override the include or library searchg
-    #     path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2".
-    #     I'm not sure how widely supported this is even by Unix
-    #     compilers, much less on other platforms.  And I'm even less
-    #     sure how useful it is; maybe for cross-compiling, but
-    #     support for that is a ways off.  (And anyways, cross
-    #     compilers probably have a dedicated binary with the
-    #     right paths compiled in.  I hope.)
-    #   * can't do really freaky things with the library list/library
-    #     dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against
-    #     different versions of libfoo.a in different locations.  I
-    #     think this is useless without the ability to null out the
-    #     library search path anyways.
-
-    # Subclasses that rely on the standard filename generation methods
-    # implemented below should override these; see the comment near
-    # those methods ('object_filenames()' et. al.) for details:
-    src_extensions = None  # list of strings
-    obj_extension = None  # string
-    static_lib_extension = None
-    shared_lib_extension = None  # string
-    static_lib_format = None  # format string
-    shared_lib_format = None  # prob. same as static_lib_format
-    exe_extension = None  # string
-
-    # Default language settings. language_map is used to detect a source
-    # file or Extension target language, checking source filenames.
-    # language_order is used to detect the language precedence, when deciding
-    # what language to use when mixing source types. For example, if some
-    # extension has two files with ".c" extension, and one with ".cpp", it
-    # is still linked as c++.
-    language_map = {
-        ".c": "c",
-        ".cc": "c++",
-        ".cpp": "c++",
-        ".cxx": "c++",
-        ".m": "objc",
-    }
-    language_order = ["c++", "objc", "c"]
-
-    include_dirs = []
-    """
-    include dirs specific to this compiler class
-    """
-
-    library_dirs = []
-    """
-    library dirs specific to this compiler class
-    """
-
-    def __init__(self, verbose=0, dry_run=0, force=0):
-        self.dry_run = dry_run
-        self.force = force
-        self.verbose = verbose
-
-        # 'output_dir': a common output directory for object, library,
-        # shared object, and shared library files
-        self.output_dir = None
-
-        # 'macros': a list of macro definitions (or undefinitions).  A
-        # macro definition is a 2-tuple (name, value), where the value is
-        # either a string or None (no explicit value).  A macro
-        # undefinition is a 1-tuple (name,).
-        self.macros = []
-
-        # 'include_dirs': a list of directories to search for include files
-        self.include_dirs = []
-
-        # 'libraries': a list of libraries to include in any link
-        # (library names, not filenames: eg. "foo" not "libfoo.a")
-        self.libraries = []
-
-        # 'library_dirs': a list of directories to search for libraries
-        self.library_dirs = []
-
-        # 'runtime_library_dirs': a list of directories to search for
-        # shared libraries/objects at runtime
-        self.runtime_library_dirs = []
-
-        # 'objects': a list of object files (or similar, such as explicitly
-        # named library files) to include on any link
-        self.objects = []
-
-        for key in self.executables.keys():
-            self.set_executable(key, self.executables[key])
-
-    def set_executables(self, **kwargs):
-        """Define the executables (and options for them) that will be run
-        to perform the various stages of compilation.  The exact set of
-        executables that may be specified here depends on the compiler
-        class (via the 'executables' class attribute), but most will have:
-          compiler      the C/C++ compiler
-          linker_so     linker used to create shared objects and libraries
-          linker_exe    linker used to create binary executables
-          archiver      static library creator
-
-        On platforms with a command-line (Unix, DOS/Windows), each of these
-        is a string that will be split into executable name and (optional)
-        list of arguments.  (Splitting the string is done similarly to how
-        Unix shells operate: words are delimited by spaces, but quotes and
-        backslashes can override this.  See
-        'distutils.util.split_quoted()'.)
-        """
-
-        # Note that some CCompiler implementation classes will define class
-        # attributes 'cpp', 'cc', etc. with hard-coded executable names;
-        # this is appropriate when a compiler class is for exactly one
-        # compiler/OS combination (eg. MSVCCompiler).  Other compiler
-        # classes (UnixCCompiler, in particular) are driven by information
-        # discovered at run-time, since there are many different ways to do
-        # basically the same things with Unix C compilers.
-
-        for key in kwargs:
-            if key not in self.executables:
-                raise ValueError(
-                    "unknown executable '%s' for class %s"
-                    % (key, self.__class__.__name__)
-                )
-            self.set_executable(key, kwargs[key])
-
-    def set_executable(self, key, value):
-        if isinstance(value, str):
-            setattr(self, key, split_quoted(value))
-        else:
-            setattr(self, key, value)
-
-    def _find_macro(self, name):
-        i = 0
-        for defn in self.macros:
-            if defn[0] == name:
-                return i
-            i += 1
-        return None
-
-    def _check_macro_definitions(self, definitions):
-        """Ensures that every element of 'definitions' is a valid macro
-        definition, ie. either (name,value) 2-tuple or a (name,) tuple.  Do
-        nothing if all definitions are OK, raise TypeError otherwise.
-        """
-        for defn in definitions:
-            if not (
-                isinstance(defn, tuple)
-                and (
-                    len(defn) in (1, 2)
-                    and (isinstance(defn[1], str) or defn[1] is None)
-                )
-                and isinstance(defn[0], str)
-            ):
-                raise TypeError(
-                    ("invalid macro definition '%s': " % defn)
-                    + "must be tuple (string,), (string, string), or "
-                    + "(string, None)"
-                )
-
-    # -- Bookkeeping methods -------------------------------------------
-
-    def define_macro(self, name, value=None):
-        """Define a preprocessor macro for all compilations driven by this
-        compiler object.  The optional parameter 'value' should be a
-        string; if it is not supplied, then the macro will be defined
-        without an explicit value and the exact outcome depends on the
-        compiler used (XXX true? does ANSI say anything about this?)
-        """
-        # Delete from the list of macro definitions/undefinitions if
-        # already there (so that this one will take precedence).
-        i = self._find_macro(name)
-        if i is not None:
-            del self.macros[i]
-
-        self.macros.append((name, value))
-
-    def undefine_macro(self, name):
-        """Undefine a preprocessor macro for all compilations driven by
-        this compiler object.  If the same macro is defined by
-        'define_macro()' and undefined by 'undefine_macro()' the last call
-        takes precedence (including multiple redefinitions or
-        undefinitions).  If the macro is redefined/undefined on a
-        per-compilation basis (ie. in the call to 'compile()'), then that
-        takes precedence.
-        """
-        # Delete from the list of macro definitions/undefinitions if
-        # already there (so that this one will take precedence).
-        i = self._find_macro(name)
-        if i is not None:
-            del self.macros[i]
-
-        undefn = (name,)
-        self.macros.append(undefn)
-
-    def add_include_dir(self, dir):
-        """Add 'dir' to the list of directories that will be searched for
-        header files.  The compiler is instructed to search directories in
-        the order in which they are supplied by successive calls to
-        'add_include_dir()'.
-        """
-        self.include_dirs.append(dir)
-
-    def set_include_dirs(self, dirs):
-        """Set the list of directories that will be searched to 'dirs' (a
-        list of strings).  Overrides any preceding calls to
-        'add_include_dir()'; subsequence calls to 'add_include_dir()' add
-        to the list passed to 'set_include_dirs()'.  This does not affect
-        any list of standard include directories that the compiler may
-        search by default.
-        """
-        self.include_dirs = dirs[:]
-
-    def add_library(self, libname):
-        """Add 'libname' to the list of libraries that will be included in
-        all links driven by this compiler object.  Note that 'libname'
-        should *not* be the name of a file containing a library, but the
-        name of the library itself: the actual filename will be inferred by
-        the linker, the compiler, or the compiler class (depending on the
-        platform).
-
-        The linker will be instructed to link against libraries in the
-        order they were supplied to 'add_library()' and/or
-        'set_libraries()'.  It is perfectly valid to duplicate library
-        names; the linker will be instructed to link against libraries as
-        many times as they are mentioned.
-        """
-        self.libraries.append(libname)
-
-    def set_libraries(self, libnames):
-        """Set the list of libraries to be included in all links driven by
-        this compiler object to 'libnames' (a list of strings).  This does
-        not affect any standard system libraries that the linker may
-        include by default.
-        """
-        self.libraries = libnames[:]
-
-    def add_library_dir(self, dir):
-        """Add 'dir' to the list of directories that will be searched for
-        libraries specified to 'add_library()' and 'set_libraries()'.  The
-        linker will be instructed to search for libraries in the order they
-        are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.
-        """
-        self.library_dirs.append(dir)
-
-    def set_library_dirs(self, dirs):
-        """Set the list of library search directories to 'dirs' (a list of
-        strings).  This does not affect any standard library search path
-        that the linker may search by default.
-        """
-        self.library_dirs = dirs[:]
-
-    def add_runtime_library_dir(self, dir):
-        """Add 'dir' to the list of directories that will be searched for
-        shared libraries at runtime.
-        """
-        self.runtime_library_dirs.append(dir)
-
-    def set_runtime_library_dirs(self, dirs):
-        """Set the list of directories to search for shared libraries at
-        runtime to 'dirs' (a list of strings).  This does not affect any
-        standard search path that the runtime linker may search by
-        default.
-        """
-        self.runtime_library_dirs = dirs[:]
-
-    def add_link_object(self, object):
-        """Add 'object' to the list of object files (or analogues, such as
-        explicitly named library files or the output of "resource
-        compilers") to be included in every link driven by this compiler
-        object.
-        """
-        self.objects.append(object)
-
-    def set_link_objects(self, objects):
-        """Set the list of object files (or analogues) to be included in
-        every link to 'objects'.  This does not affect any standard object
-        files that the linker may include by default (such as system
-        libraries).
-        """
-        self.objects = objects[:]
-
-    # -- Private utility methods --------------------------------------
-    # (here for the convenience of subclasses)
-
-    # Helper method to prep compiler in subclass compile() methods
-
-    def _setup_compile(self, outdir, macros, incdirs, sources, depends, extra):
-        """Process arguments and decide which source files to compile."""
-        outdir, macros, incdirs = self._fix_compile_args(outdir, macros, incdirs)
-
-        if extra is None:
-            extra = []
-
-        # Get the list of expected output (object) files
-        objects = self.object_filenames(sources, strip_dir=0, output_dir=outdir)
-        assert len(objects) == len(sources)
-
-        pp_opts = gen_preprocess_options(macros, incdirs)
-
-        build = {}
-        for i in range(len(sources)):
-            src = sources[i]
-            obj = objects[i]
-            ext = os.path.splitext(src)[1]
-            self.mkpath(os.path.dirname(obj))
-            build[obj] = (src, ext)
-
-        return macros, objects, extra, pp_opts, build
-
-    def _get_cc_args(self, pp_opts, debug, before):
-        # works for unixccompiler, cygwinccompiler
-        cc_args = pp_opts + ['-c']
-        if debug:
-            cc_args[:0] = ['-g']
-        if before:
-            cc_args[:0] = before
-        return cc_args
-
-    def _fix_compile_args(self, output_dir, macros, include_dirs):
-        """Typecheck and fix-up some of the arguments to the 'compile()'
-        method, and return fixed-up values.  Specifically: if 'output_dir'
-        is None, replaces it with 'self.output_dir'; ensures that 'macros'
-        is a list, and augments it with 'self.macros'; ensures that
-        'include_dirs' is a list, and augments it with 'self.include_dirs'.
-        Guarantees that the returned values are of the correct type,
-        i.e. for 'output_dir' either string or None, and for 'macros' and
-        'include_dirs' either list or None.
-        """
-        if output_dir is None:
-            output_dir = self.output_dir
-        elif not isinstance(output_dir, str):
-            raise TypeError("'output_dir' must be a string or None")
-
-        if macros is None:
-            macros = self.macros
-        elif isinstance(macros, list):
-            macros = macros + (self.macros or [])
-        else:
-            raise TypeError("'macros' (if supplied) must be a list of tuples")
-
-        if include_dirs is None:
-            include_dirs = list(self.include_dirs)
-        elif isinstance(include_dirs, (list, tuple)):
-            include_dirs = list(include_dirs) + (self.include_dirs or [])
-        else:
-            raise TypeError("'include_dirs' (if supplied) must be a list of strings")
-
-        # add include dirs for class
-        include_dirs += self.__class__.include_dirs
-
-        return output_dir, macros, include_dirs
-
-    def _prep_compile(self, sources, output_dir, depends=None):
-        """Decide which source files must be recompiled.
-
-        Determine the list of object files corresponding to 'sources',
-        and figure out which ones really need to be recompiled.
-        Return a list of all object files and a dictionary telling
-        which source files can be skipped.
-        """
-        # Get the list of expected output (object) files
-        objects = self.object_filenames(sources, output_dir=output_dir)
-        assert len(objects) == len(sources)
-
-        # Return an empty dict for the "which source files can be skipped"
-        # return value to preserve API compatibility.
-        return objects, {}
-
-    def _fix_object_args(self, objects, output_dir):
-        """Typecheck and fix up some arguments supplied to various methods.
-        Specifically: ensure that 'objects' is a list; if output_dir is
-        None, replace with self.output_dir.  Return fixed versions of
-        'objects' and 'output_dir'.
-        """
-        if not isinstance(objects, (list, tuple)):
-            raise TypeError("'objects' must be a list or tuple of strings")
-        objects = list(objects)
-
-        if output_dir is None:
-            output_dir = self.output_dir
-        elif not isinstance(output_dir, str):
-            raise TypeError("'output_dir' must be a string or None")
-
-        return (objects, output_dir)
-
-    def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs):
-        """Typecheck and fix up some of the arguments supplied to the
-        'link_*' methods.  Specifically: ensure that all arguments are
-        lists, and augment them with their permanent versions
-        (eg. 'self.libraries' augments 'libraries').  Return a tuple with
-        fixed versions of all arguments.
-        """
-        if libraries is None:
-            libraries = self.libraries
-        elif isinstance(libraries, (list, tuple)):
-            libraries = list(libraries) + (self.libraries or [])
-        else:
-            raise TypeError("'libraries' (if supplied) must be a list of strings")
-
-        if library_dirs is None:
-            library_dirs = self.library_dirs
-        elif isinstance(library_dirs, (list, tuple)):
-            library_dirs = list(library_dirs) + (self.library_dirs or [])
-        else:
-            raise TypeError("'library_dirs' (if supplied) must be a list of strings")
-
-        # add library dirs for class
-        library_dirs += self.__class__.library_dirs
-
-        if runtime_library_dirs is None:
-            runtime_library_dirs = self.runtime_library_dirs
-        elif isinstance(runtime_library_dirs, (list, tuple)):
-            runtime_library_dirs = list(runtime_library_dirs) + (
-                self.runtime_library_dirs or []
-            )
-        else:
-            raise TypeError(
-                "'runtime_library_dirs' (if supplied) " "must be a list of strings"
-            )
-
-        return (libraries, library_dirs, runtime_library_dirs)
-
-    def _need_link(self, objects, output_file):
-        """Return true if we need to relink the files listed in 'objects'
-        to recreate 'output_file'.
-        """
-        if self.force:
-            return True
-        else:
-            if self.dry_run:
-                newer = newer_group(objects, output_file, missing='newer')
-            else:
-                newer = newer_group(objects, output_file)
-            return newer
-
-    def detect_language(self, sources):
-        """Detect the language of a given file, or list of files. Uses
-        language_map, and language_order to do the job.
-        """
-        if not isinstance(sources, list):
-            sources = [sources]
-        lang = None
-        index = len(self.language_order)
-        for source in sources:
-            base, ext = os.path.splitext(source)
-            extlang = self.language_map.get(ext)
-            try:
-                extindex = self.language_order.index(extlang)
-                if extindex < index:
-                    lang = extlang
-                    index = extindex
-            except ValueError:
-                pass
-        return lang
-
-    # -- Worker methods ------------------------------------------------
-    # (must be implemented by subclasses)
-
-    def preprocess(
-        self,
-        source,
-        output_file=None,
-        macros=None,
-        include_dirs=None,
-        extra_preargs=None,
-        extra_postargs=None,
-    ):
-        """Preprocess a single C/C++ source file, named in 'source'.
-        Output will be written to file named 'output_file', or stdout if
-        'output_file' not supplied.  'macros' is a list of macro
-        definitions as for 'compile()', which will augment the macros set
-        with 'define_macro()' and 'undefine_macro()'.  'include_dirs' is a
-        list of directory names that will be added to the default list.
-
-        Raises PreprocessError on failure.
-        """
-        pass
-
-    def compile(
-        self,
-        sources,
-        output_dir=None,
-        macros=None,
-        include_dirs=None,
-        debug=0,
-        extra_preargs=None,
-        extra_postargs=None,
-        depends=None,
-    ):
-        """Compile one or more source files.
-
-        'sources' must be a list of filenames, most likely C/C++
-        files, but in reality anything that can be handled by a
-        particular compiler and compiler class (eg. MSVCCompiler can
-        handle resource files in 'sources').  Return a list of object
-        filenames, one per source filename in 'sources'.  Depending on
-        the implementation, not all source files will necessarily be
-        compiled, but all corresponding object filenames will be
-        returned.
-
-        If 'output_dir' is given, object files will be put under it, while
-        retaining their original path component.  That is, "foo/bar.c"
-        normally compiles to "foo/bar.o" (for a Unix implementation); if
-        'output_dir' is "build", then it would compile to
-        "build/foo/bar.o".
-
-        'macros', if given, must be a list of macro definitions.  A macro
-        definition is either a (name, value) 2-tuple or a (name,) 1-tuple.
-        The former defines a macro; if the value is None, the macro is
-        defined without an explicit value.  The 1-tuple case undefines a
-        macro.  Later definitions/redefinitions/ undefinitions take
-        precedence.
-
-        'include_dirs', if given, must be a list of strings, the
-        directories to add to the default include file search path for this
-        compilation only.
-
-        'debug' is a boolean; if true, the compiler will be instructed to
-        output debug symbols in (or alongside) the object file(s).
-
-        'extra_preargs' and 'extra_postargs' are implementation- dependent.
-        On platforms that have the notion of a command-line (e.g. Unix,
-        DOS/Windows), they are most likely lists of strings: extra
-        command-line arguments to prepend/append to the compiler command
-        line.  On other platforms, consult the implementation class
-        documentation.  In any event, they are intended as an escape hatch
-        for those occasions when the abstract compiler framework doesn't
-        cut the mustard.
-
-        'depends', if given, is a list of filenames that all targets
-        depend on.  If a source file is older than any file in
-        depends, then the source file will be recompiled.  This
-        supports dependency tracking, but only at a coarse
-        granularity.
-
-        Raises CompileError on failure.
-        """
-        # A concrete compiler class can either override this method
-        # entirely or implement _compile().
-        macros, objects, extra_postargs, pp_opts, build = self._setup_compile(
-            output_dir, macros, include_dirs, sources, depends, extra_postargs
-        )
-        cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
-
-        for obj in objects:
-            try:
-                src, ext = build[obj]
-            except KeyError:
-                continue
-            self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
-
-        # Return *all* object filenames, not just the ones we just built.
-        return objects
-
-    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
-        """Compile 'src' to product 'obj'."""
-        # A concrete compiler class that does not override compile()
-        # should implement _compile().
-        pass
-
-    def create_static_lib(
-        self, objects, output_libname, output_dir=None, debug=0, target_lang=None
-    ):
-        """Link a bunch of stuff together to create a static library file.
-        The "bunch of stuff" consists of the list of object files supplied
-        as 'objects', the extra object files supplied to
-        'add_link_object()' and/or 'set_link_objects()', the libraries
-        supplied to 'add_library()' and/or 'set_libraries()', and the
-        libraries supplied as 'libraries' (if any).
-
-        'output_libname' should be a library name, not a filename; the
-        filename will be inferred from the library name.  'output_dir' is
-        the directory where the library file will be put.
-
-        'debug' is a boolean; if true, debugging information will be
-        included in the library (note that on most platforms, it is the
-        compile step where this matters: the 'debug' flag is included here
-        just for consistency).
-
-        'target_lang' is the target language for which the given objects
-        are being compiled. This allows specific linkage time treatment of
-        certain languages.
-
-        Raises LibError on failure.
-        """
-        pass
-
-    # values for target_desc parameter in link()
-    SHARED_OBJECT = "shared_object"
-    SHARED_LIBRARY = "shared_library"
-    EXECUTABLE = "executable"
-
-    def link(
-        self,
-        target_desc,
-        objects,
-        output_filename,
-        output_dir=None,
-        libraries=None,
-        library_dirs=None,
-        runtime_library_dirs=None,
-        export_symbols=None,
-        debug=0,
-        extra_preargs=None,
-        extra_postargs=None,
-        build_temp=None,
-        target_lang=None,
-    ):
-        """Link a bunch of stuff together to create an executable or
-        shared library file.
-
-        The "bunch of stuff" consists of the list of object files supplied
-        as 'objects'.  'output_filename' should be a filename.  If
-        'output_dir' is supplied, 'output_filename' is relative to it
-        (i.e. 'output_filename' can provide directory components if
-        needed).
-
-        'libraries' is a list of libraries to link against.  These are
-        library names, not filenames, since they're translated into
-        filenames in a platform-specific way (eg. "foo" becomes "libfoo.a"
-        on Unix and "foo.lib" on DOS/Windows).  However, they can include a
-        directory component, which means the linker will look in that
-        specific directory rather than searching all the normal locations.
-
-        'library_dirs', if supplied, should be a list of directories to
-        search for libraries that were specified as bare library names
-        (ie. no directory component).  These are on top of the system
-        default and those supplied to 'add_library_dir()' and/or
-        'set_library_dirs()'.  'runtime_library_dirs' is a list of
-        directories that will be embedded into the shared library and used
-        to search for other shared libraries that *it* depends on at
-        run-time.  (This may only be relevant on Unix.)
-
-        'export_symbols' is a list of symbols that the shared library will
-        export.  (This appears to be relevant only on Windows.)
-
-        'debug' is as for 'compile()' and 'create_static_lib()', with the
-        slight distinction that it actually matters on most platforms (as
-        opposed to 'create_static_lib()', which includes a 'debug' flag
-        mostly for form's sake).
-
-        'extra_preargs' and 'extra_postargs' are as for 'compile()' (except
-        of course that they supply command-line arguments for the
-        particular linker being used).
-
-        'target_lang' is the target language for which the given objects
-        are being compiled. This allows specific linkage time treatment of
-        certain languages.
-
-        Raises LinkError on failure.
-        """
-        raise NotImplementedError
-
-    # Old 'link_*()' methods, rewritten to use the new 'link()' method.
-
-    def link_shared_lib(
-        self,
-        objects,
-        output_libname,
-        output_dir=None,
-        libraries=None,
-        library_dirs=None,
-        runtime_library_dirs=None,
-        export_symbols=None,
-        debug=0,
-        extra_preargs=None,
-        extra_postargs=None,
-        build_temp=None,
-        target_lang=None,
-    ):
-        self.link(
-            CCompiler.SHARED_LIBRARY,
-            objects,
-            self.library_filename(output_libname, lib_type='shared'),
-            output_dir,
-            libraries,
-            library_dirs,
-            runtime_library_dirs,
-            export_symbols,
-            debug,
-            extra_preargs,
-            extra_postargs,
-            build_temp,
-            target_lang,
-        )
-
-    def link_shared_object(
-        self,
-        objects,
-        output_filename,
-        output_dir=None,
-        libraries=None,
-        library_dirs=None,
-        runtime_library_dirs=None,
-        export_symbols=None,
-        debug=0,
-        extra_preargs=None,
-        extra_postargs=None,
-        build_temp=None,
-        target_lang=None,
-    ):
-        self.link(
-            CCompiler.SHARED_OBJECT,
-            objects,
-            output_filename,
-            output_dir,
-            libraries,
-            library_dirs,
-            runtime_library_dirs,
-            export_symbols,
-            debug,
-            extra_preargs,
-            extra_postargs,
-            build_temp,
-            target_lang,
-        )
-
-    def link_executable(
-        self,
-        objects,
-        output_progname,
-        output_dir=None,
-        libraries=None,
-        library_dirs=None,
-        runtime_library_dirs=None,
-        debug=0,
-        extra_preargs=None,
-        extra_postargs=None,
-        target_lang=None,
-    ):
-        self.link(
-            CCompiler.EXECUTABLE,
-            objects,
-            self.executable_filename(output_progname),
-            output_dir,
-            libraries,
-            library_dirs,
-            runtime_library_dirs,
-            None,
-            debug,
-            extra_preargs,
-            extra_postargs,
-            None,
-            target_lang,
-        )
-
-    # -- Miscellaneous methods -----------------------------------------
-    # These are all used by the 'gen_lib_options() function; there is
-    # no appropriate default implementation so subclasses should
-    # implement all of these.
-
-    def library_dir_option(self, dir):
-        """Return the compiler option to add 'dir' to the list of
-        directories searched for libraries.
-        """
-        raise NotImplementedError
-
-    def runtime_library_dir_option(self, dir):
-        """Return the compiler option to add 'dir' to the list of
-        directories searched for runtime libraries.
-        """
-        raise NotImplementedError
-
-    def library_option(self, lib):
-        """Return the compiler option to add 'lib' to the list of libraries
-        linked into the shared library or executable.
-        """
-        raise NotImplementedError
-
-    def has_function(  # noqa: C901
-        self,
-        funcname,
-        includes=None,
-        include_dirs=None,
-        libraries=None,
-        library_dirs=None,
-    ):
-        """Return a boolean indicating whether funcname is provided as
-        a symbol on the current platform.  The optional arguments can
-        be used to augment the compilation environment.
-
-        The libraries argument is a list of flags to be passed to the
-        linker to make additional symbol definitions available for
-        linking.
-
-        The includes and include_dirs arguments are deprecated.
-        Usually, supplying include files with function declarations
-        will cause function detection to fail even in cases where the
-        symbol is available for linking.
-
-        """
-        # this can't be included at module scope because it tries to
-        # import math which might not be available at that point - maybe
-        # the necessary logic should just be inlined?
-        import tempfile
-
-        if includes is None:
-            includes = []
-        else:
-            warnings.warn("includes is deprecated", DeprecationWarning)
-        if include_dirs is None:
-            include_dirs = []
-        else:
-            warnings.warn("include_dirs is deprecated", DeprecationWarning)
-        if libraries is None:
-            libraries = []
-        if library_dirs is None:
-            library_dirs = []
-        fd, fname = tempfile.mkstemp(".c", funcname, text=True)
-        f = os.fdopen(fd, "w")
-        try:
-            for incl in includes:
-                f.write("""#include "%s"\n""" % incl)
-            if not includes:
-                # Use "char func(void);" as the prototype to follow
-                # what autoconf does.  This prototype does not match
-                # any well-known function the compiler might recognize
-                # as a builtin, so this ends up as a true link test.
-                # Without a fake prototype, the test would need to
-                # know the exact argument types, and the has_function
-                # interface does not provide that level of information.
-                f.write(
-                    """\
-#ifdef __cplusplus
-extern "C"
-#endif
-char %s(void);
-"""
-                    % funcname
-                )
-            f.write(
-                """\
-int main (int argc, char **argv) {
-    %s();
-    return 0;
-}
-"""
-                % funcname
-            )
-        finally:
-            f.close()
-        try:
-            objects = self.compile([fname], include_dirs=include_dirs)
-        except CompileError:
-            return False
-        finally:
-            os.remove(fname)
-
-        try:
-            self.link_executable(
-                objects, "a.out", libraries=libraries, library_dirs=library_dirs
-            )
-        except (LinkError, TypeError):
-            return False
-        else:
-            os.remove(
-                self.executable_filename("a.out", output_dir=self.output_dir or '')
-            )
-        finally:
-            for fn in objects:
-                os.remove(fn)
-        return True
-
-    def find_library_file(self, dirs, lib, debug=0):
-        """Search the specified list of directories for a static or shared
-        library file 'lib' and return the full path to that file.  If
-        'debug' true, look for a debugging version (if that makes sense on
-        the current platform).  Return None if 'lib' wasn't found in any of
-        the specified directories.
-        """
-        raise NotImplementedError
-
-    # -- Filename generation methods -----------------------------------
-
-    # The default implementation of the filename generating methods are
-    # prejudiced towards the Unix/DOS/Windows view of the world:
-    #   * object files are named by replacing the source file extension
-    #     (eg. .c/.cpp -> .o/.obj)
-    #   * library files (shared or static) are named by plugging the
-    #     library name and extension into a format string, eg.
-    #     "lib%s.%s" % (lib_name, ".a") for Unix static libraries
-    #   * executables are named by appending an extension (possibly
-    #     empty) to the program name: eg. progname + ".exe" for
-    #     Windows
-    #
-    # To reduce redundant code, these methods expect to find
-    # several attributes in the current object (presumably defined
-    # as class attributes):
-    #   * src_extensions -
-    #     list of C/C++ source file extensions, eg. ['.c', '.cpp']
-    #   * obj_extension -
-    #     object file extension, eg. '.o' or '.obj'
-    #   * static_lib_extension -
-    #     extension for static library files, eg. '.a' or '.lib'
-    #   * shared_lib_extension -
-    #     extension for shared library/object files, eg. '.so', '.dll'
-    #   * static_lib_format -
-    #     format string for generating static library filenames,
-    #     eg. 'lib%s.%s' or '%s.%s'
-    #   * shared_lib_format
-    #     format string for generating shared library filenames
-    #     (probably same as static_lib_format, since the extension
-    #     is one of the intended parameters to the format string)
-    #   * exe_extension -
-    #     extension for executable files, eg. '' or '.exe'
-
-    def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
-        if output_dir is None:
-            output_dir = ''
-        return list(
-            self._make_out_path(output_dir, strip_dir, src_name)
-            for src_name in source_filenames
-        )
-
-    @property
-    def out_extensions(self):
-        return dict.fromkeys(self.src_extensions, self.obj_extension)
-
-    def _make_out_path(self, output_dir, strip_dir, src_name):
-        base, ext = os.path.splitext(src_name)
-        base = self._make_relative(base)
-        try:
-            new_ext = self.out_extensions[ext]
-        except LookupError:
-            raise UnknownFileError(
-                "unknown file type '{}' (from '{}')".format(ext, src_name)
-            )
-        if strip_dir:
-            base = os.path.basename(base)
-        return os.path.join(output_dir, base + new_ext)
-
-    @staticmethod
-    def _make_relative(base):
-        """
-        In order to ensure that a filename always honors the
-        indicated output_dir, make sure it's relative.
-        Ref python/cpython#37775.
-        """
-        # Chop off the drive
-        no_drive = os.path.splitdrive(base)[1]
-        # If abs, chop off leading /
-        return no_drive[os.path.isabs(no_drive) :]
-
-    def shared_object_filename(self, basename, strip_dir=0, output_dir=''):
-        assert output_dir is not None
-        if strip_dir:
-            basename = os.path.basename(basename)
-        return os.path.join(output_dir, basename + self.shared_lib_extension)
-
-    def executable_filename(self, basename, strip_dir=0, output_dir=''):
-        assert output_dir is not None
-        if strip_dir:
-            basename = os.path.basename(basename)
-        return os.path.join(output_dir, basename + (self.exe_extension or ''))
-
-    def library_filename(
-        self, libname, lib_type='static', strip_dir=0, output_dir=''  # or 'shared'
-    ):
-        assert output_dir is not None
-        expected = '"static", "shared", "dylib", "xcode_stub"'
-        if lib_type not in eval(expected):
-            raise ValueError(f"'lib_type' must be {expected}")
-        fmt = getattr(self, lib_type + "_lib_format")
-        ext = getattr(self, lib_type + "_lib_extension")
-
-        dir, base = os.path.split(libname)
-        filename = fmt % (base, ext)
-        if strip_dir:
-            dir = ''
-
-        return os.path.join(output_dir, dir, filename)
-
-    # -- Utility methods -----------------------------------------------
-
-    def announce(self, msg, level=1):
-        log.debug(msg)
-
-    def debug_print(self, msg):
-        from distutils.debug import DEBUG
-
-        if DEBUG:
-            print(msg)
-
-    def warn(self, msg):
-        sys.stderr.write("warning: %s\n" % msg)
-
-    def execute(self, func, args, msg=None, level=1):
-        execute(func, args, msg, self.dry_run)
-
-    def spawn(self, cmd, **kwargs):
-        spawn(cmd, dry_run=self.dry_run, **kwargs)
-
-    def move_file(self, src, dst):
-        return move_file(src, dst, dry_run=self.dry_run)
-
-    def mkpath(self, name, mode=0o777):
-        mkpath(name, mode, dry_run=self.dry_run)
-
-
-# Map a sys.platform/os.name ('posix', 'nt') to the default compiler
-# type for that platform. Keys are interpreted as re match
-# patterns. Order is important; platform mappings are preferred over
-# OS names.
-_default_compilers = (
-    # Platform string mappings
-    # on a cygwin built python we can use gcc like an ordinary UNIXish
-    # compiler
-    ('cygwin.*', 'unix'),
-    # OS name mappings
-    ('posix', 'unix'),
-    ('nt', 'msvc'),
+from .compilers.C import base
+from .compilers.C.base import (
+    gen_lib_options,
+    gen_preprocess_options,
+    get_default_compiler,
+    new_compiler,
+    show_compilers,
 )
+from .compilers.C.errors import CompileError, LinkError
 
+__all__ = [
+    'CompileError',
+    'LinkError',
+    'gen_lib_options',
+    'gen_preprocess_options',
+    'get_default_compiler',
+    'new_compiler',
+    'show_compilers',
+]
 
-def get_default_compiler(osname=None, platform=None):
-    """Determine the default compiler to use for the given platform.
-
-    osname should be one of the standard Python OS names (i.e. the
-    ones returned by os.name) and platform the common value
-    returned by sys.platform for the platform in question.
-
-    The default values are os.name and sys.platform in case the
-    parameters are not given.
-    """
-    if osname is None:
-        osname = os.name
-    if platform is None:
-        platform = sys.platform
-    for pattern, compiler in _default_compilers:
-        if (
-            re.match(pattern, platform) is not None
-            or re.match(pattern, osname) is not None
-        ):
-            return compiler
-    # Default to Unix compiler
-    return 'unix'
-
-
-# Map compiler types to (module_name, class_name) pairs -- ie. where to
-# find the code that implements an interface to this compiler.  (The module
-# is assumed to be in the 'distutils' package.)
-compiler_class = {
-    'unix': ('unixccompiler', 'UnixCCompiler', "standard UNIX-style compiler"),
-    'msvc': ('_msvccompiler', 'MSVCCompiler', "Microsoft Visual C++"),
-    'cygwin': (
-        'cygwinccompiler',
-        'CygwinCCompiler',
-        "Cygwin port of GNU C Compiler for Win32",
-    ),
-    'mingw32': (
-        'cygwinccompiler',
-        'Mingw32CCompiler',
-        "Mingw32 port of GNU C Compiler for Win32",
-    ),
-    'bcpp': ('bcppcompiler', 'BCPPCompiler', "Borland C++ Compiler"),
-}
-
-
-def show_compilers():
-    """Print list of available compilers (used by the "--help-compiler"
-    options to "build", "build_ext", "build_clib").
-    """
-    # XXX this "knows" that the compiler option it's describing is
-    # "--compiler", which just happens to be the case for the three
-    # commands that use it.
-    from distutils.fancy_getopt import FancyGetopt
-
-    compilers = []
-    for compiler in compiler_class.keys():
-        compilers.append(("compiler=" + compiler, None, compiler_class[compiler][2]))
-    compilers.sort()
-    pretty_printer = FancyGetopt(compilers)
-    pretty_printer.print_help("List of available compilers:")
-
-
-def new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0):
-    """Generate an instance of some CCompiler subclass for the supplied
-    platform/compiler combination.  'plat' defaults to 'os.name'
-    (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler
-    for that platform.  Currently only 'posix' and 'nt' are supported, and
-    the default compilers are "traditional Unix interface" (UnixCCompiler
-    class) and Visual C++ (MSVCCompiler class).  Note that it's perfectly
-    possible to ask for a Unix compiler object under Windows, and a
-    Microsoft compiler object under Unix -- if you supply a value for
-    'compiler', 'plat' is ignored.
-    """
-    if plat is None:
-        plat = os.name
-
-    try:
-        if compiler is None:
-            compiler = get_default_compiler(plat)
-
-        (module_name, class_name, long_description) = compiler_class[compiler]
-    except KeyError:
-        msg = "don't know how to compile C/C++ code on platform '%s'" % plat
-        if compiler is not None:
-            msg = msg + " with '%s' compiler" % compiler
-        raise DistutilsPlatformError(msg)
-
-    try:
-        module_name = "distutils." + module_name
-        __import__(module_name)
-        module = sys.modules[module_name]
-        klass = vars(module)[class_name]
-    except ImportError:
-        raise DistutilsModuleError(
-            "can't compile C/C++ code: unable to load module '%s'" % module_name
-        )
-    except KeyError:
-        raise DistutilsModuleError(
-            "can't compile C/C++ code: unable to find class '%s' "
-            "in module '%s'" % (class_name, module_name)
-        )
-
-    # XXX The None is necessary to preserve backwards compatibility
-    # with classes that expect verbose to be the first positional
-    # argument.
-    return klass(None, dry_run, force)
-
-
-def gen_preprocess_options(macros, include_dirs):
-    """Generate C pre-processor options (-D, -U, -I) as used by at least
-    two types of compilers: the typical Unix compiler and Visual C++.
-    'macros' is the usual thing, a list of 1- or 2-tuples, where (name,)
-    means undefine (-U) macro 'name', and (name,value) means define (-D)
-    macro 'name' to 'value'.  'include_dirs' is just a list of directory
-    names to be added to the header file search path (-I).  Returns a list
-    of command-line options suitable for either Unix compilers or Visual
-    C++.
-    """
-    # XXX it would be nice (mainly aesthetic, and so we don't generate
-    # stupid-looking command lines) to go over 'macros' and eliminate
-    # redundant definitions/undefinitions (ie. ensure that only the
-    # latest mention of a particular macro winds up on the command
-    # line).  I don't think it's essential, though, since most (all?)
-    # Unix C compilers only pay attention to the latest -D or -U
-    # mention of a macro on their command line.  Similar situation for
-    # 'include_dirs'.  I'm punting on both for now.  Anyways, weeding out
-    # redundancies like this should probably be the province of
-    # CCompiler, since the data structures used are inherited from it
-    # and therefore common to all CCompiler classes.
-    pp_opts = []
-    for macro in macros:
-        if not (isinstance(macro, tuple) and 1 <= len(macro) <= 2):
-            raise TypeError(
-                "bad macro definition '%s': "
-                "each element of 'macros' list must be a 1- or 2-tuple" % macro
-            )
-
-        if len(macro) == 1:  # undefine this macro
-            pp_opts.append("-U%s" % macro[0])
-        elif len(macro) == 2:
-            if macro[1] is None:  # define with no explicit value
-                pp_opts.append("-D%s" % macro[0])
-            else:
-                # XXX *don't* need to be clever about quoting the
-                # macro value here, because we're going to avoid the
-                # shell at all costs when we spawn the command!
-                pp_opts.append("-D%s=%s" % macro)
-
-    for dir in include_dirs:
-        pp_opts.append("-I%s" % dir)
-    return pp_opts
-
-
-def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries):
-    """Generate linker options for searching library directories and
-    linking with specific libraries.  'libraries' and 'library_dirs' are,
-    respectively, lists of library names (not filenames!) and search
-    directories.  Returns a list of command-line options suitable for use
-    with some compiler (depending on the two format strings passed in).
-    """
-    lib_opts = []
-
-    for dir in library_dirs:
-        lib_opts.append(compiler.library_dir_option(dir))
-
-    for dir in runtime_library_dirs:
-        opt = compiler.runtime_library_dir_option(dir)
-        if isinstance(opt, list):
-            lib_opts = lib_opts + opt
-        else:
-            lib_opts.append(opt)
-
-    # XXX it's important that we *not* remove redundant library mentions!
-    # sometimes you really do have to say "-lfoo -lbar -lfoo" in order to
-    # resolve all symbols.  I just hope we never have to say "-lfoo obj.o
-    # -lbar" to get things to work -- that's certainly a possibility, but a
-    # pretty nasty way to arrange your C code.
 
-    for lib in libraries:
-        (lib_dir, lib_name) = os.path.split(lib)
-        if lib_dir:
-            lib_file = compiler.find_library_file([lib_dir], lib_name)
-            if lib_file:
-                lib_opts.append(lib_file)
-            else:
-                compiler.warn(
-                    "no library file corresponding to " "'%s' found (skipping)" % lib
-                )
-        else:
-            lib_opts.append(compiler.library_option(lib))
-    return lib_opts
+CCompiler = base.Compiler
diff --git a/setuptools/_distutils/cmd.py b/setuptools/_distutils/cmd.py
index 3860c3ff1e..530cc108d4 100644
--- a/setuptools/_distutils/cmd.py
+++ b/setuptools/_distutils/cmd.py
@@ -4,14 +4,31 @@
 in the distutils.command package.
 """
 
-import sys
+from __future__ import annotations
+
+import logging
 import os
 import re
-import logging
+import sys
+from abc import abstractmethod
+from collections.abc import Callable, MutableSequence
+from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, overload
 
-from .errors import DistutilsOptionError
-from . import util, dir_util, file_util, archive_util, dep_util
+from . import _modified, archive_util, dir_util, file_util, util
 from ._log import log
+from .errors import DistutilsOptionError
+
+if TYPE_CHECKING:
+    # type-only import because of mutual dependence between these classes
+    from distutils.dist import Distribution
+
+    from typing_extensions import TypeVarTuple, Unpack
+
+    _Ts = TypeVarTuple("_Ts")
+
+_StrPathT = TypeVar("_StrPathT", bound="str | os.PathLike[str]")
+_BytesPathT = TypeVar("_BytesPathT", bound="bytes | os.PathLike[bytes]")
+_CommandT = TypeVar("_CommandT", bound="Command")
 
 
 class Command:
@@ -44,11 +61,18 @@ class Command:
     # 'sub_commands' is usually defined at the *end* of a class, because
     # predicates can be unbound methods, so they must already have been
     # defined.  The canonical example is the "install" command.
-    sub_commands = []
+    sub_commands: ClassVar[  # Any to work around variance issues
+        list[tuple[str, Callable[[Any], bool] | None]]
+    ] = []
+
+    user_options: ClassVar[
+        # Specifying both because list is invariant. Avoids mypy override assignment issues
+        list[tuple[str, str, str]] | list[tuple[str, str | None, str]]
+    ] = []
 
     # -- Creation/initialization methods -------------------------------
 
-    def __init__(self, dist):
+    def __init__(self, dist: Distribution) -> None:
         """Create and initialize a new Command object.  Most importantly,
         invokes the 'initialize_options()' method, which is the real
         initializer and depends on the actual command being
@@ -67,13 +91,8 @@ def __init__(self, dist):
 
         # Per-command versions of the global flags, so that the user can
         # customize Distutils' behaviour command-by-command and let some
-        # commands fall back on the Distribution's behaviour.  None means
-        # "not defined, check self.distribution's copy", while 0 or 1 mean
-        # false and true (duh).  Note that this means figuring out the real
-        # value of each flag is a touch complicated -- hence "self._dry_run"
-        # will be handled by __getattr__, below.
-        # XXX This needs to be fixed.
-        self._dry_run = None
+        # commands fall back on the Distribution's behaviour. None means
+        # "not defined, check self.distribution's copy".
 
         # verbose is largely ignored, but needs to be set for
         # backwards compatibility (I think)?
@@ -87,29 +106,18 @@ def __init__(self, dist):
 
         # The 'help' flag is just used for command-line parsing, so
         # none of that complicated bureaucracy is needed.
-        self.help = 0
+        self.help = False
 
         # 'finalized' records whether or not 'finalize_options()' has been
         # called.  'finalize_options()' itself should not pay attention to
         # this flag: it is the business of 'ensure_finalized()', which
         # always calls 'finalize_options()', to respect/update it.
-        self.finalized = 0
-
-    # XXX A more explicit way to customize dry_run would be better.
-    def __getattr__(self, attr):
-        if attr == 'dry_run':
-            myval = getattr(self, "_" + attr)
-            if myval is None:
-                return getattr(self.distribution, attr)
-            else:
-                return myval
-        else:
-            raise AttributeError(attr)
+        self.finalized = False
 
-    def ensure_finalized(self):
+    def ensure_finalized(self) -> None:
         if not self.finalized:
             self.finalize_options()
-        self.finalized = 1
+        self.finalized = True
 
     # Subclasses must define:
     #   initialize_options()
@@ -124,7 +132,8 @@ def ensure_finalized(self):
     #     run the command: do whatever it is we're here to do,
     #     controlled by the command's various option values
 
-    def initialize_options(self):
+    @abstractmethod
+    def initialize_options(self) -> None:
         """Set default values for all the options that this command
         supports.  Note that these defaults may be overridden by other
         commands, by the setup script, by config files, or by the
@@ -135,10 +144,11 @@ def initialize_options(self):
         This method must be implemented by all command classes.
         """
         raise RuntimeError(
-            "abstract method -- subclass %s must override" % self.__class__
+            f"abstract method -- subclass {self.__class__} must override"
         )
 
-    def finalize_options(self):
+    @abstractmethod
+    def finalize_options(self) -> None:
         """Set final values for all the options that this command supports.
         This is always called as late as possible, ie.  after any option
         assignments from the command-line or from other commands have been
@@ -150,14 +160,14 @@ def finalize_options(self):
         This method must be implemented by all command classes.
         """
         raise RuntimeError(
-            "abstract method -- subclass %s must override" % self.__class__
+            f"abstract method -- subclass {self.__class__} must override"
         )
 
     def dump_options(self, header=None, indent=""):
         from distutils.fancy_getopt import longopt_xlate
 
         if header is None:
-            header = "command options for '%s':" % self.get_command_name()
+            header = f"command options for '{self.get_command_name()}':"
         self.announce(indent + header, level=logging.INFO)
         indent = indent + "  "
         for option, _, _ in self.user_options:
@@ -165,9 +175,10 @@ def dump_options(self, header=None, indent=""):
             if option[-1] == "=":
                 option = option[:-1]
             value = getattr(self, option)
-            self.announce(indent + "{} = {}".format(option, value), level=logging.INFO)
+            self.announce(indent + f"{option} = {value}", level=logging.INFO)
 
-    def run(self):
+    @abstractmethod
+    def run(self) -> None:
         """A command's raison d'etre: carry out the action it exists to
         perform, controlled by the options initialized in
         'initialize_options()', customized by other commands, the setup
@@ -178,13 +189,13 @@ def run(self):
         This method must be implemented by all command classes.
         """
         raise RuntimeError(
-            "abstract method -- subclass %s must override" % self.__class__
+            f"abstract method -- subclass {self.__class__} must override"
         )
 
-    def announce(self, msg, level=logging.DEBUG):
+    def announce(self, msg: object, level: int = logging.DEBUG) -> None:
         log.log(level, msg)
 
-    def debug_print(self, msg):
+    def debug_print(self, msg: object) -> None:
         """Print 'msg' to stdout if the global DEBUG (taken from the
         DISTUTILS_DEBUG environment variable) flag is true.
         """
@@ -213,18 +224,16 @@ def _ensure_stringlike(self, option, what, default=None):
             setattr(self, option, default)
             return default
         elif not isinstance(val, str):
-            raise DistutilsOptionError(
-                "'{}' must be a {} (got `{}`)".format(option, what, val)
-            )
+            raise DistutilsOptionError(f"'{option}' must be a {what} (got `{val}`)")
         return val
 
-    def ensure_string(self, option, default=None):
+    def ensure_string(self, option: str, default: str | None = None) -> None:
         """Ensure that 'option' is a string; if not defined, set it to
         'default'.
         """
         self._ensure_stringlike(option, "string", default)
 
-    def ensure_string_list(self, option):
+    def ensure_string_list(self, option: str) -> None:
         r"""Ensure that 'option' is a list of strings.  If 'option' is
         currently a string, we split it either on /,\s*/ or /\s+/, so
         "foo bar baz", "foo,bar,baz", and "foo,   bar baz" all become
@@ -242,7 +251,7 @@ def ensure_string_list(self, option):
                 ok = False
             if not ok:
                 raise DistutilsOptionError(
-                    "'{}' must be a list of strings (got {!r})".format(option, val)
+                    f"'{option}' must be a list of strings (got {val!r})"
                 )
 
     def _ensure_tested_string(self, option, tester, what, error_fmt, default=None):
@@ -252,13 +261,13 @@ def _ensure_tested_string(self, option, tester, what, error_fmt, default=None):
                 ("error in '%s' option: " + error_fmt) % (option, val)
             )
 
-    def ensure_filename(self, option):
+    def ensure_filename(self, option: str) -> None:
         """Ensure that 'option' is the name of an existing file."""
         self._ensure_tested_string(
             option, os.path.isfile, "filename", "'%s' does not exist or is not a file"
         )
 
-    def ensure_dirname(self, option):
+    def ensure_dirname(self, option: str) -> None:
         self._ensure_tested_string(
             option,
             os.path.isdir,
@@ -268,13 +277,15 @@ def ensure_dirname(self, option):
 
     # -- Convenience methods for commands ------------------------------
 
-    def get_command_name(self):
+    def get_command_name(self) -> str:
         if hasattr(self, 'command_name'):
             return self.command_name
         else:
             return self.__class__.__name__
 
-    def set_undefined_options(self, src_cmd, *option_pairs):
+    def set_undefined_options(
+        self, src_cmd: str, *option_pairs: tuple[str, str]
+    ) -> None:
         """Set the values of any "undefined" options from corresponding
         option values in some other command object.  "Undefined" here means
         "is None", which is the convention used to indicate that an option
@@ -295,7 +306,9 @@ def set_undefined_options(self, src_cmd, *option_pairs):
             if getattr(self, dst_option) is None:
                 setattr(self, dst_option, getattr(src_cmd_obj, src_option))
 
-    def get_finalized_command(self, command, create=1):
+    # NOTE: Because distutils is private to Setuptools and not all commands are exposed here,
+    # not every possible command is enumerated in the signature.
+    def get_finalized_command(self, command: str, create: bool = True) -> Command:
         """Wrapper around Distribution's 'get_command_obj()' method: find
         (create if necessary and 'create' is true) the command object for
         'command', call its 'ensure_finalized()' method, and return the
@@ -307,17 +320,27 @@ def get_finalized_command(self, command, create=1):
 
     # XXX rename to 'get_reinitialized_command()'? (should do the
     # same in dist.py, if so)
-    def reinitialize_command(self, command, reinit_subcommands=0):
+    @overload
+    def reinitialize_command(
+        self, command: str, reinit_subcommands: bool = False
+    ) -> Command: ...
+    @overload
+    def reinitialize_command(
+        self, command: _CommandT, reinit_subcommands: bool = False
+    ) -> _CommandT: ...
+    def reinitialize_command(
+        self, command: str | Command, reinit_subcommands=False
+    ) -> Command:
         return self.distribution.reinitialize_command(command, reinit_subcommands)
 
-    def run_command(self, command):
+    def run_command(self, command: str) -> None:
         """Run some other command: uses the 'run_command()' method of
         Distribution, which creates and finalizes the command object if
         necessary and then invokes its 'run()' method.
         """
         self.distribution.run_command(command)
 
-    def get_sub_commands(self):
+    def get_sub_commands(self) -> list[str]:
         """Determine the sub-commands that are relevant in the current
         distribution (ie., that need to be run).  This is based on the
         'sub_commands' class attribute: each tuple in that list may include
@@ -332,18 +355,50 @@ def get_sub_commands(self):
 
     # -- External world manipulation -----------------------------------
 
-    def warn(self, msg):
+    def warn(self, msg: object) -> None:
         log.warning("warning: %s: %s\n", self.get_command_name(), msg)
 
-    def execute(self, func, args, msg=None, level=1):
-        util.execute(func, args, msg, dry_run=self.dry_run)
+    def execute(
+        self,
+        func: Callable[[Unpack[_Ts]], object],
+        args: tuple[Unpack[_Ts]],
+        msg: object = None,
+        level: int = 1,
+    ) -> None:
+        util.execute(func, args, msg)
 
-    def mkpath(self, name, mode=0o777):
-        dir_util.mkpath(name, mode, dry_run=self.dry_run)
+    def mkpath(self, name: str, mode: int = 0o777) -> None:
+        dir_util.mkpath(name, mode)
 
+    @overload
+    def copy_file(
+        self,
+        infile: str | os.PathLike[str],
+        outfile: _StrPathT,
+        preserve_mode: bool = True,
+        preserve_times: bool = True,
+        link: str | None = None,
+        level: int = 1,
+    ) -> tuple[_StrPathT | str, bool]: ...
+    @overload
     def copy_file(
-        self, infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1
-    ):
+        self,
+        infile: bytes | os.PathLike[bytes],
+        outfile: _BytesPathT,
+        preserve_mode: bool = True,
+        preserve_times: bool = True,
+        link: str | None = None,
+        level: int = 1,
+    ) -> tuple[_BytesPathT | bytes, bool]: ...
+    def copy_file(
+        self,
+        infile: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+        outfile: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+        preserve_mode: bool = True,
+        preserve_times: bool = True,
+        link: str | None = None,
+        level: int = 1,
+    ) -> tuple[str | os.PathLike[str] | bytes | os.PathLike[bytes], bool]:
         """Copy a file respecting verbose, dry-run and force flags.  (The
         former two default to whatever is in the Distribution object, and
         the latter defaults to false for commands that don't define it.)"""
@@ -354,18 +409,17 @@ def copy_file(
             preserve_times,
             not self.force,
             link,
-            dry_run=self.dry_run,
         )
 
     def copy_tree(
         self,
-        infile,
-        outfile,
-        preserve_mode=1,
-        preserve_times=1,
-        preserve_symlinks=0,
-        level=1,
-    ):
+        infile: str | os.PathLike[str],
+        outfile: str,
+        preserve_mode: bool = True,
+        preserve_times: bool = True,
+        preserve_symlinks: bool = False,
+        level: int = 1,
+    ) -> list[str]:
         """Copy an entire directory tree respecting verbose, dry-run,
         and force flags.
         """
@@ -376,35 +430,81 @@ def copy_tree(
             preserve_times,
             preserve_symlinks,
             not self.force,
-            dry_run=self.dry_run,
         )
 
-    def move_file(self, src, dst, level=1):
+    @overload
+    def move_file(
+        self, src: str | os.PathLike[str], dst: _StrPathT, level: int = 1
+    ) -> _StrPathT | str: ...
+    @overload
+    def move_file(
+        self, src: bytes | os.PathLike[bytes], dst: _BytesPathT, level: int = 1
+    ) -> _BytesPathT | bytes: ...
+    def move_file(
+        self,
+        src: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+        dst: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+        level: int = 1,
+    ) -> str | os.PathLike[str] | bytes | os.PathLike[bytes]:
         """Move a file respecting dry-run flag."""
-        return file_util.move_file(src, dst, dry_run=self.dry_run)
+        return file_util.move_file(src, dst)
 
-    def spawn(self, cmd, search_path=1, level=1):
+    def spawn(
+        self, cmd: MutableSequence[str], search_path: bool = True, level: int = 1
+    ) -> None:
         """Spawn an external command respecting dry-run flag."""
         from distutils.spawn import spawn
 
-        spawn(cmd, search_path, dry_run=self.dry_run)
+        spawn(cmd, search_path)
 
+    @overload
+    def make_archive(
+        self,
+        base_name: str,
+        format: str,
+        root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None,
+        base_dir: str | None = None,
+        owner: str | None = None,
+        group: str | None = None,
+    ) -> str: ...
+    @overload
     def make_archive(
-        self, base_name, format, root_dir=None, base_dir=None, owner=None, group=None
-    ):
+        self,
+        base_name: str | os.PathLike[str],
+        format: str,
+        root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+        base_dir: str | None = None,
+        owner: str | None = None,
+        group: str | None = None,
+    ) -> str: ...
+    def make_archive(
+        self,
+        base_name: str | os.PathLike[str],
+        format: str,
+        root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None,
+        base_dir: str | None = None,
+        owner: str | None = None,
+        group: str | None = None,
+    ) -> str:
         return archive_util.make_archive(
             base_name,
             format,
             root_dir,
             base_dir,
-            dry_run=self.dry_run,
             owner=owner,
             group=group,
         )
 
     def make_file(
-        self, infiles, outfile, func, args, exec_msg=None, skip_msg=None, level=1
-    ):
+        self,
+        infiles: str | list[str] | tuple[str, ...],
+        outfile: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+        func: Callable[[Unpack[_Ts]], object],
+        args: tuple[Unpack[_Ts]],
+        exec_msg: object = None,
+        skip_msg: object = None,
+        level: int = 1,
+    ) -> None:
         """Special case of 'execute()' for operations that process one or
         more input files and generate one output file.  Works just like
         'execute()', except the operation is skipped and a different
@@ -414,7 +514,7 @@ def make_file(
         timestamp checks.
         """
         if skip_msg is None:
-            skip_msg = "skipping %s (inputs unchanged)" % outfile
+            skip_msg = f"skipping {outfile} (inputs unchanged)"
 
         # Allow 'infiles' to be a single string
         if isinstance(infiles, str):
@@ -428,7 +528,7 @@ def make_file(
         # If 'outfile' must be regenerated (either because it doesn't
         # exist, is out-of-date, or the 'force' flag is true) then
         # perform the action that presumably regenerates it
-        if self.force or dep_util.newer_group(infiles, outfile):
+        if self.force or _modified.newer_group(infiles, outfile):
             self.execute(func, args, exec_msg, level)
         # Otherwise, print the "skip" message
         else:
diff --git a/setuptools/_distutils/command/__init__.py b/setuptools/_distutils/command/__init__.py
index 028dcfa0fc..0f8a1692ba 100644
--- a/setuptools/_distutils/command/__init__.py
+++ b/setuptools/_distutils/command/__init__.py
@@ -3,7 +3,7 @@
 Package containing implementation of all the standard Distutils
 commands."""
 
-__all__ = [  # noqa: F822
+__all__ = [
     'build',
     'build_py',
     'build_ext',
@@ -16,10 +16,8 @@
     'install_scripts',
     'install_data',
     'sdist',
-    'register',
     'bdist',
     'bdist_dumb',
     'bdist_rpm',
     'check',
-    'upload',
 ]
diff --git a/setuptools/_distutils/command/_framework_compat.py b/setuptools/_distutils/command/_framework_compat.py
index cffa27cb08..00d34bc7d8 100644
--- a/setuptools/_distutils/command/_framework_compat.py
+++ b/setuptools/_distutils/command/_framework_compat.py
@@ -2,15 +2,14 @@
 Backward compatibility for homebrew builds on macOS.
 """
 
-
-import sys
-import os
 import functools
+import os
 import subprocess
+import sys
 import sysconfig
 
 
-@functools.lru_cache()
+@functools.lru_cache
 def enabled():
     """
     Only enabled for Python 3.9 framework homebrew builds
@@ -38,7 +37,7 @@ def enabled():
 )
 
 
-@functools.lru_cache()
+@functools.lru_cache
 def vars():
     if not enabled():
         return {}
diff --git a/setuptools/_distutils/command/bdist.py b/setuptools/_distutils/command/bdist.py
index 6329039ce4..07811aab27 100644
--- a/setuptools/_distutils/command/bdist.py
+++ b/setuptools/_distutils/command/bdist.py
@@ -3,30 +3,43 @@
 Implements the Distutils 'bdist' command (create a built [binary]
 distribution)."""
 
+from __future__ import annotations
+
 import os
 import warnings
+from collections.abc import Callable
+from typing import TYPE_CHECKING, ClassVar
 
 from ..core import Command
-from ..errors import DistutilsPlatformError, DistutilsOptionError
+from ..errors import DistutilsOptionError, DistutilsPlatformError
 from ..util import get_platform
 
+if TYPE_CHECKING:
+    from typing_extensions import deprecated
+else:
+
+    def deprecated(message):
+        return lambda fn: fn
+
 
 def show_formats():
     """Print list of available formats (arguments to "--format" option)."""
     from ..fancy_getopt import FancyGetopt
 
-    formats = []
-    for format in bdist.format_commands:
-        formats.append(("formats=" + format, None, bdist.format_commands[format][1]))
+    formats = [
+        ("formats=" + format, None, bdist.format_commands[format][1])
+        for format in bdist.format_commands
+    ]
     pretty_printer = FancyGetopt(formats)
     pretty_printer.print_help("List of available distribution formats:")
 
 
-class ListCompat(dict):
+class ListCompat(dict[str, tuple[str, str]]):
     # adapter to allow for Setuptools compatibility in format_commands
-    def append(self, item):
+    @deprecated("format_commands is now a dict. append is deprecated.")
+    def append(self, item: object) -> None:
         warnings.warn(
-            """format_commands is now a dict. append is deprecated.""",
+            "format_commands is now a dict. append is deprecated.",
             DeprecationWarning,
             stacklevel=2,
         )
@@ -41,52 +54,50 @@ class bdist(Command):
             'plat-name=',
             'p',
             "platform name to embed in generated filenames "
-            "(default: %s)" % get_platform(),
+            f"[default: {get_platform()}]",
         ),
         ('formats=', None, "formats for distribution (comma-separated list)"),
         (
             'dist-dir=',
             'd',
-            "directory to put final built distributions in " "[default: dist]",
+            "directory to put final built distributions in [default: dist]",
         ),
         ('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
         (
             'owner=',
             'u',
-            "Owner name used when creating a tar file" " [default: current user]",
+            "Owner name used when creating a tar file [default: current user]",
         ),
         (
             'group=',
             'g',
-            "Group name used when creating a tar file" " [default: current group]",
+            "Group name used when creating a tar file [default: current group]",
         ),
     ]
 
-    boolean_options = ['skip-build']
+    boolean_options: ClassVar[list[str]] = ['skip-build']
 
-    help_options = [
+    help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [
         ('help-formats', None, "lists available distribution formats", show_formats),
     ]
 
     # The following commands do not take a format option from bdist
-    no_format_option = ('bdist_rpm',)
+    no_format_option: ClassVar[tuple[str, ...]] = ('bdist_rpm',)
 
     # This won't do in reality: will need to distinguish RPM-ish Linux,
     # Debian-ish Linux, Solaris, FreeBSD, ..., Windows, Mac OS.
-    default_format = {'posix': 'gztar', 'nt': 'zip'}
+    default_format: ClassVar[dict[str, str]] = {'posix': 'gztar', 'nt': 'zip'}
 
     # Define commands in preferred order for the --help-formats option
-    format_commands = ListCompat(
-        {
-            'rpm': ('bdist_rpm', "RPM distribution"),
-            'gztar': ('bdist_dumb', "gzip'ed tar file"),
-            'bztar': ('bdist_dumb', "bzip2'ed tar file"),
-            'xztar': ('bdist_dumb', "xz'ed tar file"),
-            'ztar': ('bdist_dumb', "compressed tar file"),
-            'tar': ('bdist_dumb', "tar file"),
-            'zip': ('bdist_dumb', "ZIP file"),
-        }
-    )
+    format_commands = ListCompat({
+        'rpm': ('bdist_rpm', "RPM distribution"),
+        'gztar': ('bdist_dumb', "gzip'ed tar file"),
+        'bztar': ('bdist_dumb', "bzip2'ed tar file"),
+        'xztar': ('bdist_dumb', "xz'ed tar file"),
+        'ztar': ('bdist_dumb', "compressed tar file"),
+        'tar': ('bdist_dumb', "tar file"),
+        'zip': ('bdist_dumb', "ZIP file"),
+    })
 
     # for compatibility until consumers only reference format_commands
     format_command = format_commands
@@ -96,11 +107,11 @@ def initialize_options(self):
         self.plat_name = None
         self.formats = None
         self.dist_dir = None
-        self.skip_build = 0
+        self.skip_build = False
         self.group = None
         self.owner = None
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         # have to finalize 'plat_name' before 'bdist_base'
         if self.plat_name is None:
             if self.skip_build:
@@ -122,20 +133,20 @@ def finalize_options(self):
             except KeyError:
                 raise DistutilsPlatformError(
                     "don't know how to create built distributions "
-                    "on platform %s" % os.name
+                    f"on platform {os.name}"
                 )
 
         if self.dist_dir is None:
             self.dist_dir = "dist"
 
-    def run(self):
+    def run(self) -> None:
         # Figure out which sub-commands we need to run.
         commands = []
         for format in self.formats:
             try:
                 commands.append(self.format_commands[format][0])
             except KeyError:
-                raise DistutilsOptionError("invalid format '%s'" % format)
+                raise DistutilsOptionError(f"invalid format '{format}'")
 
         # Reinitialize and run each command.
         for i in range(len(self.formats)):
@@ -152,5 +163,5 @@ def run(self):
             # If we're going to need to run this command again, tell it to
             # keep its temporary files around so subsequent runs go faster.
             if cmd_name in commands[i + 1 :]:
-                sub_cmd.keep_temp = 1
+                sub_cmd.keep_temp = True
             self.run_command(cmd_name)
diff --git a/setuptools/_distutils/command/bdist_dumb.py b/setuptools/_distutils/command/bdist_dumb.py
index 01dd79079b..c49ef253b4 100644
--- a/setuptools/_distutils/command/bdist_dumb.py
+++ b/setuptools/_distutils/command/bdist_dumb.py
@@ -5,12 +5,14 @@
 $exec_prefix)."""
 
 import os
+from distutils._log import log
+from typing import ClassVar
+
 from ..core import Command
-from ..util import get_platform
-from ..dir_util import remove_tree, ensure_relative
+from ..dir_util import ensure_relative, remove_tree
 from ..errors import DistutilsPlatformError
 from ..sysconfig import get_python_version
-from distutils._log import log
+from ..util import get_platform
 
 
 class bdist_dumb(Command):
@@ -22,39 +24,38 @@ class bdist_dumb(Command):
             'plat-name=',
             'p',
             "platform name to embed in generated filenames "
-            "(default: %s)" % get_platform(),
+            f"[default: {get_platform()}]",
         ),
         (
             'format=',
             'f',
-            "archive format to create (tar, gztar, bztar, xztar, " "ztar, zip)",
+            "archive format to create (tar, gztar, bztar, xztar, ztar, zip)",
         ),
         (
             'keep-temp',
             'k',
-            "keep the pseudo-installation tree around after "
-            + "creating the distribution archive",
+            "keep the pseudo-installation tree around after creating the distribution archive",
         ),
         ('dist-dir=', 'd', "directory to put final built distributions in"),
         ('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
         (
             'relative',
             None,
-            "build the archive using relative paths " "(default: false)",
+            "build the archive using relative paths [default: false]",
         ),
         (
             'owner=',
             'u',
-            "Owner name used when creating a tar file" " [default: current user]",
+            "Owner name used when creating a tar file [default: current user]",
         ),
         (
             'group=',
             'g',
-            "Group name used when creating a tar file" " [default: current group]",
+            "Group name used when creating a tar file [default: current group]",
         ),
     ]
 
-    boolean_options = ['keep-temp', 'skip-build', 'relative']
+    boolean_options: ClassVar[list[str]] = ['keep-temp', 'skip-build', 'relative']
 
     default_format = {'posix': 'gztar', 'nt': 'zip'}
 
@@ -62,10 +63,10 @@ def initialize_options(self):
         self.bdist_dir = None
         self.plat_name = None
         self.format = None
-        self.keep_temp = 0
+        self.keep_temp = False
         self.dist_dir = None
         self.skip_build = None
-        self.relative = 0
+        self.relative = False
         self.owner = None
         self.group = None
 
@@ -80,7 +81,7 @@ def finalize_options(self):
             except KeyError:
                 raise DistutilsPlatformError(
                     "don't know how to create dumb built distributions "
-                    "on platform %s" % os.name
+                    f"on platform {os.name}"
                 )
 
         self.set_undefined_options(
@@ -94,19 +95,17 @@ def run(self):
         if not self.skip_build:
             self.run_command('build')
 
-        install = self.reinitialize_command('install', reinit_subcommands=1)
+        install = self.reinitialize_command('install', reinit_subcommands=True)
         install.root = self.bdist_dir
         install.skip_build = self.skip_build
-        install.warn_dir = 0
+        install.warn_dir = False
 
         log.info("installing to %s", self.bdist_dir)
         self.run_command('install')
 
         # And make an archive relative to the root of the
         # pseudo-installation tree.
-        archive_basename = "{}.{}".format(
-            self.distribution.get_fullname(), self.plat_name
-        )
+        archive_basename = f"{self.distribution.get_fullname()}.{self.plat_name}"
 
         pseudoinstall_root = os.path.join(self.dist_dir, archive_basename)
         if not self.relative:
@@ -117,8 +116,7 @@ def run(self):
             ):
                 raise DistutilsPlatformError(
                     "can't make a dumb built distribution where "
-                    "base and platbase are different (%s, %s)"
-                    % (repr(install.install_base), repr(install.install_platbase))
+                    f"base and platbase are different ({install.install_base!r}, {install.install_platbase!r})"
                 )
             else:
                 archive_root = os.path.join(
@@ -140,4 +138,4 @@ def run(self):
         self.distribution.dist_files.append(('bdist_dumb', pyversion, filename))
 
         if not self.keep_temp:
-            remove_tree(self.bdist_dir, dry_run=self.dry_run)
+            remove_tree(self.bdist_dir)
diff --git a/setuptools/_distutils/command/bdist_rpm.py b/setuptools/_distutils/command/bdist_rpm.py
index 3ed608b479..dfa5f99dda 100644
--- a/setuptools/_distutils/command/bdist_rpm.py
+++ b/setuptools/_distutils/command/bdist_rpm.py
@@ -3,21 +3,22 @@
 Implements the Distutils 'bdist_rpm' command (create RPM source and binary
 distributions)."""
 
+import os
 import subprocess
 import sys
-import os
+from distutils._log import log
+from typing import ClassVar
 
 from ..core import Command
 from ..debug import DEBUG
-from ..file_util import write_file
 from ..errors import (
+    DistutilsExecError,
+    DistutilsFileError,
     DistutilsOptionError,
     DistutilsPlatformError,
-    DistutilsFileError,
-    DistutilsExecError,
 )
+from ..file_util import write_file
 from ..sysconfig import get_python_version
-from distutils._log import log
 
 
 class bdist_rpm(Command):
@@ -34,13 +35,13 @@ class bdist_rpm(Command):
         (
             'dist-dir=',
             'd',
-            "directory to put final RPM files in " "(and .spec files if --spec-only)",
+            "directory to put final RPM files in (and .spec files if --spec-only)",
         ),
         (
             'python=',
             None,
             "path to Python interpreter to hard-code in the .spec file "
-            "(default: \"python\")",
+            "[default: \"python\"]",
         ),
         (
             'fix-python',
@@ -75,7 +76,7 @@ class bdist_rpm(Command):
         (
             'packager=',
             None,
-            "RPM packager (eg. \"Jane Doe \") " "[default: vendor]",
+            "RPM packager (eg. \"Jane Doe \") [default: vendor]",
         ),
         ('doc-files=', None, "list of documentation files (space or comma-separated)"),
         ('changelog=', None, "RPM changelog"),
@@ -136,7 +137,7 @@ class bdist_rpm(Command):
         ('quiet', 'q', "Run the INSTALL phase of RPM building in quiet mode"),
     ]
 
-    boolean_options = [
+    boolean_options: ClassVar[list[str]] = [
         'keep-temp',
         'use-rpm-opt-flags',
         'rpm3-mode',
@@ -144,7 +145,7 @@ class bdist_rpm(Command):
         'quiet',
     ]
 
-    negative_opt = {
+    negative_opt: ClassVar[dict[str, str]] = {
         'no-keep-temp': 'keep-temp',
         'no-rpm-opt-flags': 'use-rpm-opt-flags',
         'rpm2-mode': 'rpm3-mode',
@@ -187,15 +188,15 @@ def initialize_options(self):
         self.build_requires = None
         self.obsoletes = None
 
-        self.keep_temp = 0
-        self.use_rpm_opt_flags = 1
-        self.rpm3_mode = 1
-        self.no_autoreq = 0
+        self.keep_temp = False
+        self.use_rpm_opt_flags = True
+        self.rpm3_mode = True
+        self.no_autoreq = False
 
         self.force_arch = None
-        self.quiet = 0
+        self.quiet = False
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         self.set_undefined_options('bdist', ('bdist_base', 'bdist_base'))
         if self.rpm_base is None:
             if not self.rpm3_mode:
@@ -214,7 +215,7 @@ def finalize_options(self):
 
         if os.name != 'posix':
             raise DistutilsPlatformError(
-                "don't know how to create RPM " "distributions on platform %s" % os.name
+                f"don't know how to create RPM distributions on platform {os.name}"
             )
         if self.binary_only and self.source_only:
             raise DistutilsOptionError(
@@ -223,17 +224,16 @@ def finalize_options(self):
 
         # don't pass CFLAGS to pure python distributions
         if not self.distribution.has_ext_modules():
-            self.use_rpm_opt_flags = 0
+            self.use_rpm_opt_flags = False
 
         self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
         self.finalize_package_data()
 
-    def finalize_package_data(self):
+    def finalize_package_data(self) -> None:
         self.ensure_string('group', "Development/Libraries")
         self.ensure_string(
             'vendor',
-            "%s <%s>"
-            % (self.distribution.get_contact(), self.distribution.get_contact_email()),
+            f"{self.distribution.get_contact()} <{self.distribution.get_contact_email()}>",
         )
         self.ensure_string('packager')
         self.ensure_string_list('doc_files')
@@ -275,7 +275,7 @@ def finalize_package_data(self):
 
         self.ensure_string('force_arch')
 
-    def run(self):  # noqa: C901
+    def run(self) -> None:  # noqa: C901
         if DEBUG:
             print("before _get_package_data():")
             print("vendor =", self.vendor)
@@ -296,9 +296,9 @@ def run(self):  # noqa: C901
 
         # Spec file goes into 'dist_dir' if '--spec-only specified',
         # build/rpm. otherwise.
-        spec_path = os.path.join(spec_dir, "%s.spec" % self.distribution.get_name())
+        spec_path = os.path.join(spec_dir, f"{self.distribution.get_name()}.spec")
         self.execute(
-            write_file, (spec_path, self._make_spec_file()), "writing '%s'" % spec_path
+            write_file, (spec_path, self._make_spec_file()), f"writing '{spec_path}'"
         )
 
         if self.spec_only:  # stop if requested
@@ -323,7 +323,7 @@ def run(self):  # noqa: C901
             if os.path.exists(self.icon):
                 self.copy_file(self.icon, source_dir)
             else:
-                raise DistutilsFileError("icon file '%s' does not exist" % self.icon)
+                raise DistutilsFileError(f"icon file '{self.icon}' does not exist")
 
         # build package
         log.info("building RPMs")
@@ -335,9 +335,9 @@ def run(self):  # noqa: C901
             rpm_cmd.append('-bb')
         else:
             rpm_cmd.append('-ba')
-        rpm_cmd.extend(['--define', '__python %s' % self.python])
+        rpm_cmd.extend(['--define', f'__python {self.python}'])
         if self.rpm3_mode:
-            rpm_cmd.extend(['--define', '_topdir %s' % os.path.abspath(self.rpm_base)])
+            rpm_cmd.extend(['--define', f'_topdir {os.path.abspath(self.rpm_base)}'])
         if not self.keep_temp:
             rpm_cmd.append('--clean')
 
@@ -352,11 +352,7 @@ def run(self):  # noqa: C901
         nvr_string = "%{name}-%{version}-%{release}"
         src_rpm = nvr_string + ".src.rpm"
         non_src_rpm = "%{arch}/" + nvr_string + ".%{arch}.rpm"
-        q_cmd = r"rpm -q --qf '{} {}\n' --specfile '{}'".format(
-            src_rpm,
-            non_src_rpm,
-            spec_path,
-        )
+        q_cmd = rf"rpm -q --qf '{src_rpm} {non_src_rpm}\n' --specfile '{spec_path}'"
 
         out = os.popen(q_cmd)
         try:
@@ -375,35 +371,36 @@ def run(self):  # noqa: C901
 
             status = out.close()
             if status:
-                raise DistutilsExecError("Failed to execute: %s" % repr(q_cmd))
+                raise DistutilsExecError(f"Failed to execute: {q_cmd!r}")
 
         finally:
             out.close()
 
         self.spawn(rpm_cmd)
 
-        if not self.dry_run:
-            if self.distribution.has_ext_modules():
-                pyversion = get_python_version()
-            else:
-                pyversion = 'any'
-
-            if not self.binary_only:
-                srpm = os.path.join(rpm_dir['SRPMS'], source_rpm)
-                assert os.path.exists(srpm)
-                self.move_file(srpm, self.dist_dir)
-                filename = os.path.join(self.dist_dir, source_rpm)
-                self.distribution.dist_files.append(('bdist_rpm', pyversion, filename))
-
-            if not self.source_only:
-                for rpm in binary_rpms:
-                    rpm = os.path.join(rpm_dir['RPMS'], rpm)
-                    if os.path.exists(rpm):
-                        self.move_file(rpm, self.dist_dir)
-                        filename = os.path.join(self.dist_dir, os.path.basename(rpm))
-                        self.distribution.dist_files.append(
-                            ('bdist_rpm', pyversion, filename)
-                        )
+        if self.distribution.has_ext_modules():
+            pyversion = get_python_version()
+        else:
+            pyversion = 'any'
+
+        if not self.binary_only:
+            srpm = os.path.join(rpm_dir['SRPMS'], source_rpm)
+            assert os.path.exists(srpm)
+            self.move_file(srpm, self.dist_dir)
+            filename = os.path.join(self.dist_dir, source_rpm)
+            self.distribution.dist_files.append(('bdist_rpm', pyversion, filename))
+
+        if not self.source_only:
+            for rpm in binary_rpms:
+                rpm = os.path.join(rpm_dir['RPMS'], rpm)
+                if os.path.exists(rpm):
+                    self.move_file(rpm, self.dist_dir)
+                    filename = os.path.join(self.dist_dir, os.path.basename(rpm))
+                    self.distribution.dist_files.append((
+                        'bdist_rpm',
+                        pyversion,
+                        filename,
+                    ))
 
     def _dist_path(self, path):
         return os.path.join(self.dist_dir, os.path.basename(path))
@@ -428,14 +425,14 @@ def _make_spec_file(self):  # noqa: C901
         # Generate a potential replacement value for __os_install_post (whilst
         # normalizing the whitespace to simplify the test for whether the
         # invocation of brp-python-bytecompile passes in __python):
-        vendor_hook = '\n'.join(
-            ['  %s \\' % line.strip() for line in vendor_hook.splitlines()]
-        )
+        vendor_hook = '\n'.join([
+            f'  {line.strip()} \\' for line in vendor_hook.splitlines()
+        ])
         problem = "brp-python-bytecompile \\\n"
         fixed = "brp-python-bytecompile %{__python} \\\n"
         fixed_hook = vendor_hook.replace(problem, fixed)
         if fixed_hook != vendor_hook:
-            spec_file.append('# Workaround for http://bugs.python.org/issue14443')
+            spec_file.append('# Workaround for https://bugs.python.org/issue14443')
             spec_file.append('%define __os_install_post ' + fixed_hook + '\n')
 
         # put locale summaries into spec file
@@ -445,13 +442,11 @@ def _make_spec_file(self):  # noqa: C901
         #    spec_file.append('Summary(%s): %s' % (locale,
         #                                          self.summaries[locale]))
 
-        spec_file.extend(
-            [
-                'Name: %{name}',
-                'Version: %{version}',
-                'Release: %{release}',
-            ]
-        )
+        spec_file.extend([
+            'Name: %{name}',
+            'Version: %{version}',
+            'Release: %{release}',
+        ])
 
         # XXX yuck! this filename is available from the "sdist" command,
         # but only after it has run: and we create the spec file before
@@ -461,21 +456,19 @@ def _make_spec_file(self):  # noqa: C901
         else:
             spec_file.append('Source0: %{name}-%{unmangled_version}.tar.gz')
 
-        spec_file.extend(
-            [
-                'License: ' + (self.distribution.get_license() or "UNKNOWN"),
-                'Group: ' + self.group,
-                'BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot',
-                'Prefix: %{_prefix}',
-            ]
-        )
+        spec_file.extend([
+            'License: ' + (self.distribution.get_license() or "UNKNOWN"),
+            'Group: ' + self.group,
+            'BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot',
+            'Prefix: %{_prefix}',
+        ])
 
         if not self.force_arch:
             # noarch if no extension modules
             if not self.distribution.has_ext_modules():
                 spec_file.append('BuildArch: noarch')
         else:
-            spec_file.append('BuildArch: %s' % self.force_arch)
+            spec_file.append(f'BuildArch: {self.force_arch}')
 
         for field in (
             'Vendor',
@@ -489,7 +482,7 @@ def _make_spec_file(self):  # noqa: C901
             if isinstance(val, list):
                 spec_file.append('{}: {}'.format(field, ' '.join(val)))
             elif val is not None:
-                spec_file.append('{}: {}'.format(field, val))
+                spec_file.append(f'{field}: {val}')
 
         if self.distribution.get_url():
             spec_file.append('Url: ' + self.distribution.get_url())
@@ -506,13 +499,11 @@ def _make_spec_file(self):  # noqa: C901
         if self.no_autoreq:
             spec_file.append('AutoReq: 0')
 
-        spec_file.extend(
-            [
-                '',
-                '%description',
-                self.distribution.get_long_description() or "",
-            ]
-        )
+        spec_file.extend([
+            '',
+            '%description',
+            self.distribution.get_long_description() or "",
+        ])
 
         # put locale descriptions into spec file
         # XXX again, suppressed because config file syntax doesn't
@@ -526,8 +517,8 @@ def _make_spec_file(self):  # noqa: C901
 
         # rpm scripts
         # figure out default build script
-        def_setup_call = "{} {}".format(self.python, os.path.basename(sys.argv[0]))
-        def_build = "%s build" % def_setup_call
+        def_setup_call = f"{self.python} {os.path.basename(sys.argv[0])}"
+        def_build = f"{def_setup_call} build"
         if self.use_rpm_opt_flags:
             def_build = 'env CFLAGS="$RPM_OPT_FLAGS" ' + def_build
 
@@ -537,9 +528,7 @@ def _make_spec_file(self):  # noqa: C901
         # that we open and interpolate into the spec file, but the defaults
         # are just text that we drop in as-is.  Hmmm.
 
-        install_cmd = (
-            '%s install -O1 --root=$RPM_BUILD_ROOT ' '--record=INSTALLED_FILES'
-        ) % def_setup_call
+        install_cmd = f'{def_setup_call} install -O1 --root=$RPM_BUILD_ROOT --record=INSTALLED_FILES'
 
         script_options = [
             ('prep', 'prep_script', "%setup -n %{name}-%{unmangled_version}"),
@@ -558,12 +547,10 @@ def _make_spec_file(self):  # noqa: C901
             # use 'default' as contents of script
             val = getattr(self, attr)
             if val or default:
-                spec_file.extend(
-                    [
-                        '',
-                        '%' + rpm_opt,
-                    ]
-                )
+                spec_file.extend([
+                    '',
+                    '%' + rpm_opt,
+                ])
                 if val:
                     with open(val) as f:
                         spec_file.extend(f.read().split('\n'))
@@ -571,24 +558,20 @@ def _make_spec_file(self):  # noqa: C901
                     spec_file.append(default)
 
         # files section
-        spec_file.extend(
-            [
-                '',
-                '%files -f INSTALLED_FILES',
-                '%defattr(-,root,root)',
-            ]
-        )
+        spec_file.extend([
+            '',
+            '%files -f INSTALLED_FILES',
+            '%defattr(-,root,root)',
+        ])
 
         if self.doc_files:
             spec_file.append('%doc ' + ' '.join(self.doc_files))
 
         if self.changelog:
-            spec_file.extend(
-                [
-                    '',
-                    '%changelog',
-                ]
-            )
+            spec_file.extend([
+                '',
+                '%changelog',
+            ])
             spec_file.extend(self.changelog)
 
         return spec_file
diff --git a/setuptools/_distutils/command/build.py b/setuptools/_distutils/command/build.py
index cc9b367ef9..6a8303a954 100644
--- a/setuptools/_distutils/command/build.py
+++ b/setuptools/_distutils/command/build.py
@@ -2,19 +2,20 @@
 
 Implements the Distutils 'build' command."""
 
-import sys
+from __future__ import annotations
+
 import os
+import sys
+import sysconfig
+from collections.abc import Callable
+from typing import ClassVar
+
+from ..ccompiler import show_compilers
 from ..core import Command
 from ..errors import DistutilsOptionError
 from ..util import get_platform
 
 
-def show_compilers():
-    from ..ccompiler import show_compilers
-
-    show_compilers()
-
-
 class build(Command):
     description = "build everything needed to install"
 
@@ -25,16 +26,14 @@ class build(Command):
         (
             'build-lib=',
             None,
-            "build directory for all distribution (defaults to either "
-            + "build-purelib or build-platlib",
+            "build directory for all distribution (defaults to either build-purelib or build-platlib",
         ),
         ('build-scripts=', None, "build directory for scripts"),
         ('build-temp=', 't', "temporary build directory"),
         (
             'plat-name=',
             'p',
-            "platform name to build for, if supported "
-            "(default: %s)" % get_platform(),
+            f"platform name to build for, if supported [default: {get_platform()}]",
         ),
         ('compiler=', 'c', "specify the compiler type"),
         ('parallel=', 'j', "number of parallel build jobs"),
@@ -43,9 +42,9 @@ class build(Command):
         ('executable=', 'e', "specify final destination interpreter path (build.py)"),
     ]
 
-    boolean_options = ['debug', 'force']
+    boolean_options: ClassVar[list[str]] = ['debug', 'force']
 
-    help_options = [
+    help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [
         ('help-compiler', None, "list available compilers", show_compilers),
     ]
 
@@ -61,11 +60,11 @@ def initialize_options(self):
         self.compiler = None
         self.plat_name = None
         self.debug = None
-        self.force = 0
+        self.force = False
         self.executable = None
         self.parallel = None
 
-    def finalize_options(self):  # noqa: C901
+    def finalize_options(self) -> None:  # noqa: C901
         if self.plat_name is None:
             self.plat_name = get_platform()
         else:
@@ -78,7 +77,11 @@ def finalize_options(self):  # noqa: C901
                     "using './configure --help' on your platform)"
                 )
 
-        plat_specifier = ".{}-{}".format(self.plat_name, sys.implementation.cache_tag)
+        plat_specifier = f".{self.plat_name}-{sys.implementation.cache_tag}"
+
+        # Python 3.13+ with --disable-gil shouldn't share build directories
+        if sysconfig.get_config_var('Py_GIL_DISABLED'):
+            plat_specifier += 't'
 
         # Make it so Python 2.x and Python 2.x with --with-pydebug don't
         # share the same build directories. Doing so confuses the build
@@ -109,7 +112,8 @@ def finalize_options(self):  # noqa: C901
             self.build_temp = os.path.join(self.build_base, 'temp' + plat_specifier)
         if self.build_scripts is None:
             self.build_scripts = os.path.join(
-                self.build_base, 'scripts-%d.%d' % sys.version_info[:2]
+                self.build_base,
+                f'scripts-{sys.version_info.major}.{sys.version_info.minor}',
             )
 
         if self.executable is None and sys.executable:
@@ -121,7 +125,7 @@ def finalize_options(self):  # noqa: C901
             except ValueError:
                 raise DistutilsOptionError("parallel should be an integer")
 
-    def run(self):
+    def run(self) -> None:
         # Run all relevant sub-commands.  This will be some subset of:
         #  - build_py      - pure Python modules
         #  - build_clib    - standalone C libraries
diff --git a/setuptools/_distutils/command/build_clib.py b/setuptools/_distutils/command/build_clib.py
index b3f679b67d..8de5df239c 100644
--- a/setuptools/_distutils/command/build_clib.py
+++ b/setuptools/_distutils/command/build_clib.py
@@ -4,7 +4,6 @@
 that is included in the module distribution and needed by an extension
 module."""
 
-
 # XXX this module has *lots* of code ripped-off quite transparently from
 # build_ext.py -- not surprisingly really, as the work required to build
 # a static library from a collection of C source files is not really all
@@ -13,24 +12,23 @@
 # necessary refactoring to account for the overlap in code between the
 # two modules, mainly because a number of subtle details changed in the
 # cut 'n paste.  Sigh.
+from __future__ import annotations
 
 import os
+from collections.abc import Callable
+from distutils._log import log
+from typing import ClassVar
+
+from ..ccompiler import new_compiler, show_compilers
 from ..core import Command
 from ..errors import DistutilsSetupError
 from ..sysconfig import customize_compiler
-from distutils._log import log
-
-
-def show_compilers():
-    from ..ccompiler import show_compilers
-
-    show_compilers()
 
 
 class build_clib(Command):
     description = "build C/C++ libraries used by Python extensions"
 
-    user_options = [
+    user_options: ClassVar[list[tuple[str, str, str]]] = [
         ('build-clib=', 'b', "directory to build C/C++ libraries to"),
         ('build-temp=', 't', "directory to put temporary build by-products"),
         ('debug', 'g', "compile with debugging information"),
@@ -38,9 +36,9 @@ class build_clib(Command):
         ('compiler=', 'c', "specify the compiler type"),
     ]
 
-    boolean_options = ['debug', 'force']
+    boolean_options: ClassVar[list[str]] = ['debug', 'force']
 
-    help_options = [
+    help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [
         ('help-compiler', None, "list available compilers", show_compilers),
     ]
 
@@ -56,10 +54,10 @@ def initialize_options(self):
         self.define = None
         self.undef = None
         self.debug = None
-        self.force = 0
+        self.force = False
         self.compiler = None
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         # This might be confusing: both build-clib and build-temp default
         # to build-temp as defined by the "build" command.  This is because
         # I think that C libraries are really just temporary build
@@ -86,16 +84,11 @@ def finalize_options(self):
         # XXX same as for build_ext -- what about 'self.define' and
         # 'self.undef' ?
 
-    def run(self):
+    def run(self) -> None:
         if not self.libraries:
             return
 
-        # Yech -- this is cut 'n pasted from build_ext.py!
-        from ..ccompiler import new_compiler
-
-        self.compiler = new_compiler(
-            compiler=self.compiler, dry_run=self.dry_run, force=self.force
-        )
+        self.compiler = new_compiler(compiler=self.compiler, force=self.force)
         customize_compiler(self.compiler)
 
         if self.include_dirs is not None:
@@ -110,7 +103,7 @@ def run(self):
 
         self.build_libraries(self.libraries)
 
-    def check_library_list(self, libraries):
+    def check_library_list(self, libraries) -> None:
         """Ensure that the list of libraries is valid.
 
         `library` is presumably provided as a command option 'libraries'.
@@ -137,8 +130,7 @@ def check_library_list(self, libraries):
 
             if '/' in name or (os.sep != '/' and os.sep in name):
                 raise DistutilsSetupError(
-                    "bad library name '%s': "
-                    "may not contain directory separators" % lib[0]
+                    f"bad library name '{lib[0]}': may not contain directory separators"
                 )
 
             if not isinstance(build_info, dict):
@@ -154,7 +146,7 @@ def get_library_names(self):
             return None
 
         lib_names = []
-        for lib_name, build_info in self.libraries:
+        for lib_name, _build_info in self.libraries:
             lib_names.append(lib_name)
         return lib_names
 
@@ -165,22 +157,22 @@ def get_source_files(self):
             sources = build_info.get('sources')
             if sources is None or not isinstance(sources, (list, tuple)):
                 raise DistutilsSetupError(
-                    "in 'libraries' option (library '%s'), "
+                    f"in 'libraries' option (library '{lib_name}'), "
                     "'sources' must be present and must be "
-                    "a list of source filenames" % lib_name
+                    "a list of source filenames"
                 )
 
             filenames.extend(sources)
         return filenames
 
-    def build_libraries(self, libraries):
+    def build_libraries(self, libraries) -> None:
         for lib_name, build_info in libraries:
             sources = build_info.get('sources')
             if sources is None or not isinstance(sources, (list, tuple)):
                 raise DistutilsSetupError(
-                    "in 'libraries' option (library '%s'), "
+                    f"in 'libraries' option (library '{lib_name}'), "
                     "'sources' must be present and must be "
-                    "a list of source filenames" % lib_name
+                    "a list of source filenames"
                 )
             sources = list(sources)
 
diff --git a/setuptools/_distutils/command/build_ext.py b/setuptools/_distutils/command/build_ext.py
index fbeec342c0..df623d7e0e 100644
--- a/setuptools/_distutils/command/build_ext.py
+++ b/setuptools/_distutils/command/build_ext.py
@@ -4,40 +4,37 @@
 modules (currently limited to C extensions, should accommodate C++
 extensions ASAP)."""
 
+from __future__ import annotations
+
 import contextlib
 import os
 import re
 import sys
+from collections.abc import Callable
+from distutils._log import log
+from site import USER_BASE
+from typing import ClassVar
+
+from .._modified import newer_group
+from ..ccompiler import new_compiler, show_compilers
 from ..core import Command
 from ..errors import (
-    DistutilsOptionError,
-    DistutilsSetupError,
     CCompilerError,
-    DistutilsError,
     CompileError,
+    DistutilsError,
+    DistutilsOptionError,
     DistutilsPlatformError,
+    DistutilsSetupError,
 )
-from ..sysconfig import customize_compiler, get_python_version
-from ..sysconfig import get_config_h_filename
-from ..dep_util import newer_group
 from ..extension import Extension
-from ..util import get_platform
-from distutils._log import log
-from . import py37compat
-
-from site import USER_BASE
+from ..sysconfig import customize_compiler, get_config_h_filename, get_python_version
+from ..util import get_platform, is_freethreaded, is_mingw
 
 # An extension name is just a dot-separated list of Python NAMEs (ie.
 # the same as a fully-qualified module name).
 extension_name_re = re.compile(r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$')
 
 
-def show_compilers():
-    from ..ccompiler import show_compilers
-
-    show_compilers()
-
-
 class build_ext(Command):
     description = "build C/C++ extensions (compile/link to build directory)"
 
@@ -59,7 +56,7 @@ class build_ext(Command):
     #     takes care of both command-line and client options
     #     in between initialize_options() and finalize_options())
 
-    sep_by = " (separated by '%s')" % os.pathsep
+    sep_by = f" (separated by '{os.pathsep}')"
     user_options = [
         ('build-lib=', 'b', "directory for compiled extension modules"),
         ('build-temp=', 't', "directory for temporary files (build by-products)"),
@@ -67,13 +64,13 @@ class build_ext(Command):
             'plat-name=',
             'p',
             "platform name to cross-compile for, if supported "
-            "(default: %s)" % get_platform(),
+            f"[default: {get_platform()}]",
         ),
         (
             'inplace',
             'i',
             "ignore build-lib and put compiled extensions into the source "
-            + "directory alongside your pure Python modules",
+            "directory alongside your pure Python modules",
         ),
         (
             'include-dirs=',
@@ -100,9 +97,15 @@ class build_ext(Command):
         ('user', None, "add user include, library and rpath"),
     ]
 
-    boolean_options = ['inplace', 'debug', 'force', 'swig-cpp', 'user']
+    boolean_options: ClassVar[list[str]] = [
+        'inplace',
+        'debug',
+        'force',
+        'swig-cpp',
+        'user',
+    ]
 
-    help_options = [
+    help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [
         ('help-compiler', None, "list available compilers", show_compilers),
     ]
 
@@ -111,7 +114,7 @@ def initialize_options(self):
         self.build_lib = None
         self.plat_name = None
         self.build_temp = None
-        self.inplace = 0
+        self.inplace = False
         self.package = None
 
         self.include_dirs = None
@@ -130,7 +133,32 @@ def initialize_options(self):
         self.user = None
         self.parallel = None
 
-    def finalize_options(self):  # noqa: C901
+    @staticmethod
+    def _python_lib_dir(sysconfig):
+        """
+        Resolve Python's library directory for building extensions
+        that rely on a shared Python library.
+
+        See python/cpython#44264 and python/cpython#48686
+        """
+        if not sysconfig.get_config_var('Py_ENABLE_SHARED'):
+            return
+
+        if sysconfig.python_build:
+            yield '.'
+            return
+
+        if sys.platform == 'zos':
+            # On z/OS, a user is not required to install Python to
+            # a predetermined path, but can use Python portably
+            installed_dir = sysconfig.get_config_var('base')
+            lib_dir = sysconfig.get_config_var('platlibdir')
+            yield os.path.join(installed_dir, lib_dir)
+        else:
+            # building third party extensions
+            yield sysconfig.get_config_var('LIBDIR')
+
+    def finalize_options(self) -> None:  # noqa: C901
         from distutils import sysconfig
 
         self.set_undefined_options(
@@ -152,7 +180,7 @@ def finalize_options(self):  # noqa: C901
         # Make sure Python's include directories (for Python.h, pyconfig.h,
         # etc.) are in the include search path.
         py_include = sysconfig.get_python_inc()
-        plat_py_include = sysconfig.get_python_inc(plat_specific=1)
+        plat_py_include = sysconfig.get_python_inc(plat_specific=True)
         if self.include_dirs is None:
             self.include_dirs = self.distribution.include_dirs or []
         if isinstance(self.include_dirs, str):
@@ -189,7 +217,7 @@ def finalize_options(self):  # noqa: C901
         # for extensions under windows use different directories
         # for Release and Debug builds.
         # also Python's library directory must be appended to library_dirs
-        if os.name == 'nt':
+        if os.name == 'nt' and not is_mingw():
             # the 'libs' directory is for binary installs - we assume that
             # must be the *native* platform.  But we don't really support
             # cross-compiling via a binary install anyway, so we let it go.
@@ -231,16 +259,7 @@ def finalize_options(self):  # noqa: C901
                 # building python standard extensions
                 self.library_dirs.append('.')
 
-        # For building extensions with a shared Python library,
-        # Python's library directory must be appended to library_dirs
-        # See Issues: #1600860, #4366
-        if sysconfig.get_config_var('Py_ENABLE_SHARED'):
-            if not sysconfig.python_build:
-                # building third party extensions
-                self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
-            else:
-                # building python standard extensions
-                self.library_dirs.append('.')
+        self.library_dirs.extend(self._python_lib_dir(sysconfig))
 
         # The argument parsing will result in self.define being a string, but
         # it has to be a list of 2-tuples.  All the preprocessor symbols
@@ -278,9 +297,7 @@ def finalize_options(self):  # noqa: C901
             except ValueError:
                 raise DistutilsOptionError("parallel should be an integer")
 
-    def run(self):  # noqa: C901
-        from ..ccompiler import new_compiler
-
+    def run(self) -> None:  # noqa: C901
         # 'self.extensions', as supplied by setup.py, is a list of
         # Extension instances.  See the documentation for Extension (in
         # distutils.extension) for details.
@@ -309,7 +326,6 @@ def run(self):  # noqa: C901
         self.compiler = new_compiler(
             compiler=self.compiler,
             verbose=self.verbose,
-            dry_run=self.dry_run,
             force=self.force,
         )
         customize_compiler(self.compiler)
@@ -319,6 +335,12 @@ def run(self):  # noqa: C901
         if os.name == 'nt' and self.plat_name != get_platform():
             self.compiler.initialize(self.plat_name)
 
+        # The official Windows free threaded Python installer doesn't set
+        # Py_GIL_DISABLED because its pyconfig.h is shared with the
+        # default build, so define it here (pypa/setuptools#4662).
+        if os.name == 'nt' and is_freethreaded():
+            self.compiler.define_macro('Py_GIL_DISABLED', '1')
+
         # And make sure that any compile/link-related options (which might
         # come from the command-line or from the setup script) are set in
         # that CCompiler object -- that way, they automatically apply to
@@ -344,7 +366,7 @@ def run(self):  # noqa: C901
         # Now actually compile and link everything.
         self.build_extensions()
 
-    def check_extensions_list(self, extensions):  # noqa: C901
+    def check_extensions_list(self, extensions) -> None:  # noqa: C901
         """Ensure that the list of extensions (presumably provided as a
         command option 'extensions') is valid, i.e. it is a list of
         Extension objects.  We also support the old-style list of 2-tuples,
@@ -412,9 +434,7 @@ def check_extensions_list(self, extensions):  # noqa: C901
             # Medium-easy stuff: same syntax/semantics, different names.
             ext.runtime_library_dirs = build_info.get('rpath')
             if 'def_file' in build_info:
-                log.warning(
-                    "'def_file' element of build info dict " "no longer supported"
-                )
+                log.warning("'def_file' element of build info dict no longer supported")
 
             # Non-trivial stuff: 'macros' split into 'define_macros'
             # and 'undef_macros'.
@@ -425,8 +445,7 @@ def check_extensions_list(self, extensions):  # noqa: C901
                 for macro in macros:
                     if not (isinstance(macro, tuple) and len(macro) in (1, 2)):
                         raise DistutilsSetupError(
-                            "'macros' element of build info dict "
-                            "must be 1- or 2-tuple"
+                            "'macros' element of build info dict must be 1- or 2-tuple"
                         )
                     if len(macro) == 1:
                         ext.undef_macros.append(macro[0])
@@ -453,12 +472,9 @@ def get_outputs(self):
         # And build the list of output (built) filenames.  Note that this
         # ignores the 'inplace' flag, and assumes everything goes in the
         # "build" tree.
-        outputs = []
-        for ext in self.extensions:
-            outputs.append(self.get_ext_fullpath(ext.name))
-        return outputs
+        return [self.get_ext_fullpath(ext.name) for ext in self.extensions]
 
-    def build_extensions(self):
+    def build_extensions(self) -> None:
         # First, sanity-check the 'extensions' list
         self.check_extensions_list(self.extensions)
         if self.parallel:
@@ -499,15 +515,15 @@ def _filter_build_errors(self, ext):
         except (CCompilerError, DistutilsError, CompileError) as e:
             if not ext.optional:
                 raise
-            self.warn('building extension "{}" failed: {}'.format(ext.name, e))
+            self.warn(f'building extension "{ext.name}" failed: {e}')
 
-    def build_extension(self, ext):
+    def build_extension(self, ext) -> None:
         sources = ext.sources
         if sources is None or not isinstance(sources, (list, tuple)):
             raise DistutilsSetupError(
-                "in 'ext_modules' option (extension '%s'), "
+                f"in 'ext_modules' option (extension '{ext.name}'), "
                 "'sources' must be present and must be "
-                "a list of source filenames" % ext.name
+                "a list of source filenames"
             )
         # sort to make the resulting .so file build reproducible
         sources = sorted(sources)
@@ -629,8 +645,7 @@ def swig_sources(self, sources, extension):
 
         # Do not override commandline arguments
         if not self.swig_opts:
-            for o in extension.swig_opts:
-                swig_cmd.append(o)
+            swig_cmd.extend(extension.swig_opts)
 
         for source in swig_sources:
             target = swig_targets[source]
@@ -651,20 +666,19 @@ def find_swig(self):
             # Windows (or so I presume!).  If we find it there, great;
             # if not, act like Unix and assume it's in the PATH.
             for vers in ("1.3", "1.2", "1.1"):
-                fn = os.path.join("c:\\swig%s" % vers, "swig.exe")
+                fn = os.path.join(f"c:\\swig{vers}", "swig.exe")
                 if os.path.isfile(fn):
                     return fn
             else:
                 return "swig.exe"
         else:
             raise DistutilsPlatformError(
-                "I don't know how to find (much less run) SWIG "
-                "on platform '%s'" % os.name
+                f"I don't know how to find (much less run) SWIG on platform '{os.name}'"
             )
 
     # -- Name generators -----------------------------------------------
     # (extension names, filenames, whatever)
-    def get_ext_fullpath(self, ext_name):
+    def get_ext_fullpath(self, ext_name: str) -> str:
         """Returns the path of the filename for a given extension.
 
         The file is located in `build_lib` or directly in the package
@@ -691,7 +705,7 @@ def get_ext_fullpath(self, ext_name):
         #   package_dir/filename
         return os.path.join(package_dir, filename)
 
-    def get_ext_fullname(self, ext_name):
+    def get_ext_fullname(self, ext_name: str) -> str:
         """Returns the fullname of a given extension name.
 
         Adds the `package.` prefix"""
@@ -700,7 +714,7 @@ def get_ext_fullname(self, ext_name):
         else:
             return self.package + '.' + ext_name
 
-    def get_ext_filename(self, ext_name):
+    def get_ext_filename(self, ext_name: str) -> str:
         r"""Convert the name of an extension (eg. "foo.bar") into the name
         of the file from which it will be loaded (eg. "foo/bar.so", or
         "foo\bar.pyd").
@@ -711,13 +725,13 @@ def get_ext_filename(self, ext_name):
         ext_suffix = get_config_var('EXT_SUFFIX')
         return os.path.join(*ext_path) + ext_suffix
 
-    def get_export_symbols(self, ext):
+    def get_export_symbols(self, ext: Extension) -> list[str]:
         """Return the list of symbols that a shared extension has to
         export.  This either uses 'ext.export_symbols' or, if it's not
         provided, "PyInit_" + module_name.  Only relevant on Windows, where
         the .pyd file (DLL) must export the module "PyInit_" function.
         """
-        name = ext.name.split('.')[-1]
+        name = self._get_module_name_for_symbol(ext)
         try:
             # Unicode module name support as defined in PEP-489
             # https://peps.python.org/pep-0489/#export-hook-name
@@ -732,7 +746,16 @@ def get_export_symbols(self, ext):
             ext.export_symbols.append(initfunc_name)
         return ext.export_symbols
 
-    def get_libraries(self, ext):  # noqa: C901
+    def _get_module_name_for_symbol(self, ext):
+        # Package name should be used for `__init__` modules
+        # https://github.com/python/cpython/issues/80074
+        # https://github.com/pypa/setuptools/issues/4826
+        parts = ext.name.split(".")
+        if parts[-1] == "__init__" and len(parts) >= 2:
+            return parts[-2]
+        return parts[-1]
+
+    def get_libraries(self, ext: Extension) -> list[str]:  # noqa: C901
         """Return the list of libraries to link against when building a
         shared extension.  On most platforms, this is just 'ext.libraries';
         on Windows, we add the Python library (eg. python20.dll).
@@ -742,7 +765,7 @@ def get_libraries(self, ext):  # noqa: C901
         # pyconfig.h that MSVC groks.  The other Windows compilers all seem
         # to need it mentioned explicitly, though, so that's what we do.
         # Append '_d' to the python import library on debug builds.
-        if sys.platform == "win32":
+        if sys.platform == "win32" and not is_mingw():
             from .._msvccompiler import MSVCCompiler
 
             if not isinstance(self.compiler, MSVCCompiler):
@@ -772,7 +795,7 @@ def get_libraries(self, ext):  # noqa: C901
                 # A native build on an Android device or on Cygwin
                 if hasattr(sys, 'getandroidapilevel'):
                     link_libpython = True
-                elif sys.platform == 'cygwin':
+                elif sys.platform == 'cygwin' or is_mingw():
                     link_libpython = True
                 elif '_PYTHON_HOST_PLATFORM' in os.environ:
                     # We are cross-compiling for one of the relevant platforms
@@ -785,4 +808,4 @@ def get_libraries(self, ext):  # noqa: C901
                 ldversion = get_config_var('LDVERSION')
                 return ext.libraries + ['python' + ldversion]
 
-        return ext.libraries + py37compat.pythonlib()
+        return ext.libraries
diff --git a/setuptools/_distutils/command/build_py.py b/setuptools/_distutils/command/build_py.py
index d9df95922f..d6ec7d10d2 100644
--- a/setuptools/_distutils/command/build_py.py
+++ b/setuptools/_distutils/command/build_py.py
@@ -2,15 +2,16 @@
 
 Implements the Distutils 'build_py' command."""
 
-import os
+import glob
 import importlib.util
+import os
 import sys
-import glob
+from distutils._log import log
+from typing import ClassVar
 
 from ..core import Command
-from ..errors import DistutilsOptionError, DistutilsFileError
+from ..errors import DistutilsFileError, DistutilsOptionError
 from ..util import convert_path
-from distutils._log import log
 
 
 class build_py(Command):
@@ -29,8 +30,8 @@ class build_py(Command):
         ('force', 'f', "forcibly build everything (ignore file timestamps)"),
     ]
 
-    boolean_options = ['compile', 'force']
-    negative_opt = {'no-compile': 'compile'}
+    boolean_options: ClassVar[list[str]] = ['compile', 'force']
+    negative_opt: ClassVar[dict[str, str]] = {'no-compile': 'compile'}
 
     def initialize_options(self):
         self.build_lib = None
@@ -38,11 +39,11 @@ def initialize_options(self):
         self.package = None
         self.package_data = None
         self.package_dir = None
-        self.compile = 0
+        self.compile = False
         self.optimize = 0
         self.force = None
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         self.set_undefined_options(
             'build', ('build_lib', 'build_lib'), ('force', 'force')
         )
@@ -67,7 +68,7 @@ def finalize_options(self):
             except (ValueError, AssertionError):
                 raise DistutilsOptionError("optimize must be 0, 1, or 2")
 
-    def run(self):
+    def run(self) -> None:
         # XXX copy_file by default preserves atime and mtime.  IMHO this is
         # the right thing to do, but perhaps it should be an option -- in
         # particular, a site administrator might want installed files to
@@ -95,7 +96,7 @@ def run(self):
             self.build_packages()
             self.build_package_data()
 
-        self.byte_compile(self.get_outputs(include_bytecode=0))
+        self.byte_compile(self.get_outputs(include_bytecode=False))
 
     def get_data_files(self):
         """Generate list of '(package,src_dir,build_dir,filenames)' tuples"""
@@ -129,14 +130,14 @@ def find_data_files(self, package, src_dir):
                 os.path.join(glob.escape(src_dir), convert_path(pattern))
             )
             # Files that match more than one pattern are only added once
-            files.extend(
-                [fn for fn in filelist if fn not in files and os.path.isfile(fn)]
-            )
+            files.extend([
+                fn for fn in filelist if fn not in files and os.path.isfile(fn)
+            ])
         return files
 
-    def build_package_data(self):
+    def build_package_data(self) -> None:
         """Copy data files into build directory"""
-        for package, src_dir, build_dir, filenames in self.data_files:
+        for _package, src_dir, build_dir, filenames in self.data_files:
             for filename in filenames:
                 target = os.path.join(build_dir, filename)
                 self.mkpath(os.path.dirname(target))
@@ -191,12 +192,12 @@ def check_package(self, package, package_dir):
         if package_dir != "":
             if not os.path.exists(package_dir):
                 raise DistutilsFileError(
-                    "package directory '%s' does not exist" % package_dir
+                    f"package directory '{package_dir}' does not exist"
                 )
             if not os.path.isdir(package_dir):
                 raise DistutilsFileError(
-                    "supposed package directory '%s' exists, "
-                    "but is not a directory" % package_dir
+                    f"supposed package directory '{package_dir}' exists, "
+                    "but is not a directory"
                 )
 
         # Directories without __init__.py are namespace packages (PEP 420).
@@ -228,7 +229,7 @@ def find_package_modules(self, package, package_dir):
                 module = os.path.splitext(os.path.basename(f))[0]
                 modules.append((package, module, f))
             else:
-                self.debug_print("excluding %s" % setup_script)
+                self.debug_print(f"excluding {setup_script}")
         return modules
 
     def find_modules(self):
@@ -264,7 +265,7 @@ def find_modules(self):
                 (package_dir, checked) = packages[package]
             except KeyError:
                 package_dir = self.get_package_dir(package)
-                checked = 0
+                checked = False
 
             if not checked:
                 init_py = self.check_package(package, package_dir)
@@ -306,10 +307,10 @@ def get_module_outfile(self, build_dir, package, module):
         outfile_path = [build_dir] + list(package) + [module + ".py"]
         return os.path.join(*outfile_path)
 
-    def get_outputs(self, include_bytecode=1):
+    def get_outputs(self, include_bytecode: bool = True) -> list[str]:
         modules = self.find_all_modules()
         outputs = []
-        for package, module, module_file in modules:
+        for package, module, _module_file in modules:
             package = package.split('.')
             filename = self.get_module_outfile(self.build_lib, package, module)
             outputs.append(filename)
@@ -347,9 +348,9 @@ def build_module(self, module, module_file, package):
         outfile = self.get_module_outfile(self.build_lib, package, module)
         dir = os.path.dirname(outfile)
         self.mkpath(dir)
-        return self.copy_file(module_file, outfile, preserve_mode=0)
+        return self.copy_file(module_file, outfile, preserve_mode=False)
 
-    def build_modules(self):
+    def build_modules(self) -> None:
         modules = self.find_modules()
         for package, module, module_file in modules:
             # Now "build" the module -- ie. copy the source file to
@@ -358,7 +359,7 @@ def build_modules(self):
             # under self.build_lib.)
             self.build_module(module, module_file, package)
 
-    def build_packages(self):
+    def build_packages(self) -> None:
         for package in self.packages:
             # Get list of (package, module, module_file) tuples based on
             # scanning the package directory.  'package' is only included
@@ -378,7 +379,7 @@ def build_packages(self):
                 assert package == package_
                 self.build_module(module, module_file, package)
 
-    def byte_compile(self, files):
+    def byte_compile(self, files) -> None:
         if sys.dont_write_bytecode:
             self.warn('byte-compiling is disabled, skipping.')
             return
@@ -393,14 +394,11 @@ def byte_compile(self, files):
         # method of the "install_lib" command, except for the determination
         # of the 'prefix' string.  Hmmm.
         if self.compile:
-            byte_compile(
-                files, optimize=0, force=self.force, prefix=prefix, dry_run=self.dry_run
-            )
+            byte_compile(files, optimize=0, force=self.force, prefix=prefix)
         if self.optimize > 0:
             byte_compile(
                 files,
                 optimize=self.optimize,
                 force=self.force,
                 prefix=prefix,
-                dry_run=self.dry_run,
             )
diff --git a/setuptools/_distutils/command/build_scripts.py b/setuptools/_distutils/command/build_scripts.py
index ce222f1e52..0b551d11be 100644
--- a/setuptools/_distutils/command/build_scripts.py
+++ b/setuptools/_distutils/command/build_scripts.py
@@ -4,13 +4,14 @@
 
 import os
 import re
+import tokenize
+from distutils._log import log
 from stat import ST_MODE
-from distutils import sysconfig
+from typing import ClassVar
+
+from .._modified import newer
 from ..core import Command
-from ..dep_util import newer
 from ..util import convert_path
-from distutils._log import log
-import tokenize
 
 shebang_pattern = re.compile('^#!.*python[0-9.]*([ \t].*)?$')
 """
@@ -24,13 +25,13 @@
 class build_scripts(Command):
     description = "\"build\" scripts (copy and fixup #! line)"
 
-    user_options = [
+    user_options: ClassVar[list[tuple[str, str, str]]] = [
         ('build-dir=', 'd', "directory to \"build\" (copy) to"),
         ('force', 'f', "forcibly build everything (ignore file timestamps"),
         ('executable=', 'e', "specify final destination interpreter path"),
     ]
 
-    boolean_options = ['force']
+    boolean_options: ClassVar[list[str]] = ['force']
 
     def initialize_options(self):
         self.build_dir = None
@@ -74,7 +75,7 @@ def copy_scripts(self):
 
         return outfiles, updated_files
 
-    def _copy_script(self, script, outfiles, updated_files):  # noqa: C901
+    def _copy_script(self, script, outfiles, updated_files):
         shebang_match = None
         script = convert_path(script)
         outfile = os.path.join(self.build_dir, os.path.basename(script))
@@ -86,41 +87,24 @@ def _copy_script(self, script, outfiles, updated_files):  # noqa: C901
 
         # Always open the file, but ignore failures in dry-run mode
         # in order to attempt to copy directly.
-        try:
-            f = tokenize.open(script)
-        except OSError:
-            if not self.dry_run:
-                raise
-            f = None
-        else:
-            first_line = f.readline()
-            if not first_line:
-                self.warn("%s is an empty file (skipping)" % script)
-                return
+        f = tokenize.open(script)
 
-            shebang_match = shebang_pattern.match(first_line)
+        first_line = f.readline()
+        if not first_line:
+            self.warn(f"{script} is an empty file (skipping)")
+            return
+
+        shebang_match = shebang_pattern.match(first_line)
 
         updated_files.append(outfile)
         if shebang_match:
             log.info("copying and adjusting %s -> %s", script, self.build_dir)
-            if not self.dry_run:
-                if not sysconfig.python_build:
-                    executable = self.executable
-                else:
-                    executable = os.path.join(
-                        sysconfig.get_config_var("BINDIR"),
-                        "python%s%s"
-                        % (
-                            sysconfig.get_config_var("VERSION"),
-                            sysconfig.get_config_var("EXE"),
-                        ),
-                    )
-                post_interp = shebang_match.group(1) or ''
-                shebang = "#!" + executable + post_interp + "\n"
-                self._validate_shebang(shebang, f.encoding)
-                with open(outfile, "w", encoding=f.encoding) as outf:
-                    outf.write(shebang)
-                    outf.writelines(f.readlines())
+            post_interp = shebang_match.group(1) or ''
+            shebang = "#!" + self.executable + post_interp + "\n"
+            self._validate_shebang(shebang, f.encoding)
+            with open(outfile, "w", encoding=f.encoding) as outf:
+                outf.write(shebang)
+                outf.writelines(f.readlines())
             if f:
                 f.close()
         else:
@@ -136,10 +120,6 @@ def _change_modes(self, outfiles):
             self._change_mode(file)
 
     def _change_mode(self, file):
-        if self.dry_run:
-            log.info("changing mode of %s", file)
-            return
-
         oldmode = os.stat(file)[ST_MODE] & 0o7777
         newmode = (oldmode | 0o555) & 0o7777
         if newmode != oldmode:
@@ -156,9 +136,7 @@ def _validate_shebang(shebang, encoding):
         try:
             shebang.encode('utf-8')
         except UnicodeEncodeError:
-            raise ValueError(
-                "The shebang ({!r}) is not encodable " "to utf-8".format(shebang)
-            )
+            raise ValueError(f"The shebang ({shebang!r}) is not encodable to utf-8")
 
         # If the script is encoded to a custom encoding (use a
         # #coding:xxx cookie), the shebang has to be encodable to
@@ -167,6 +145,6 @@ def _validate_shebang(shebang, encoding):
             shebang.encode(encoding)
         except UnicodeEncodeError:
             raise ValueError(
-                "The shebang ({!r}) is not encodable "
-                "to the script encoding ({})".format(shebang, encoding)
+                f"The shebang ({shebang!r}) is not encodable "
+                f"to the script encoding ({encoding})"
             )
diff --git a/setuptools/_distutils/command/check.py b/setuptools/_distutils/command/check.py
index 575e49fb4b..58a823dd39 100644
--- a/setuptools/_distutils/command/check.py
+++ b/setuptools/_distutils/command/check.py
@@ -2,16 +2,18 @@
 
 Implements the Distutils 'check' command.
 """
+
 import contextlib
+from typing import ClassVar
 
 from ..core import Command
 from ..errors import DistutilsSetupError
 
 with contextlib.suppress(ImportError):
-    import docutils.utils
-    import docutils.parsers.rst
     import docutils.frontend
     import docutils.nodes
+    import docutils.parsers.rst
+    import docutils.utils
 
     class SilentReporter(docutils.utils.Reporter):
         def __init__(
@@ -20,7 +22,7 @@ def __init__(
             report_level,
             halt_level,
             stream=None,
-            debug=0,
+            debug=False,
             encoding='ascii',
             error_handler='replace',
         ):
@@ -32,7 +34,7 @@ def __init__(
         def system_message(self, level, message, *children, **kwargs):
             self.messages.append((level, message, children, kwargs))
             return docutils.nodes.system_message(
-                message, level=level, type=self.levels[level], *children, **kwargs
+                message, *children, level=level, type=self.levels[level], **kwargs
             )
 
 
@@ -40,26 +42,23 @@ class check(Command):
     """This command checks the meta-data of the package."""
 
     description = "perform some checks on the package"
-    user_options = [
+    user_options: ClassVar[list[tuple[str, str, str]]] = [
         ('metadata', 'm', 'Verify meta-data'),
         (
             'restructuredtext',
             'r',
-            (
-                'Checks if long string meta-data syntax '
-                'are reStructuredText-compliant'
-            ),
+            'Checks if long string meta-data syntax are reStructuredText-compliant',
         ),
         ('strict', 's', 'Will exit with an error if a check fails'),
     ]
 
-    boolean_options = ['metadata', 'restructuredtext', 'strict']
+    boolean_options: ClassVar[list[str]] = ['metadata', 'restructuredtext', 'strict']
 
     def initialize_options(self):
         """Sets default values for options."""
-        self.restructuredtext = 0
+        self.restructuredtext = False
         self.metadata = 1
-        self.strict = 0
+        self.strict = False
         self._warnings = 0
 
     def finalize_options(self):
@@ -99,13 +98,12 @@ def check_metadata(self):
         """
         metadata = self.distribution.metadata
 
-        missing = []
-        for attr in 'name', 'version':
-            if not getattr(metadata, attr, None):
-                missing.append(attr)
+        missing = [
+            attr for attr in ('name', 'version') if not getattr(metadata, attr, None)
+        ]
 
         if missing:
-            self.warn("missing required meta-data: %s" % ', '.join(missing))
+            self.warn("missing required meta-data: {}".format(', '.join(missing)))
 
     def check_restructuredtext(self):
         """Checks if the long string fields are reST-compliant."""
@@ -115,7 +113,7 @@ def check_restructuredtext(self):
             if line is None:
                 warning = warning[1]
             else:
-                warning = '{} (line {})'.format(warning[1], line)
+                warning = f'{warning[1]} (line {line})'
             self.warn(warning)
 
     def _check_rst_data(self, data):
@@ -143,9 +141,12 @@ def _check_rst_data(self, data):
         document.note_source(source_path, -1)
         try:
             parser.parse(data, document)
-        except AttributeError as e:
-            reporter.messages.append(
-                (-1, 'Could not finish the parsing: %s.' % e, '', {})
-            )
+        except (AttributeError, TypeError) as e:
+            reporter.messages.append((
+                -1,
+                f'Could not finish the parsing: {e}.',
+                '',
+                {},
+            ))
 
         return reporter.messages
diff --git a/setuptools/_distutils/command/clean.py b/setuptools/_distutils/command/clean.py
index 9413f7cfcb..fc1711be8e 100644
--- a/setuptools/_distutils/command/clean.py
+++ b/setuptools/_distutils/command/clean.py
@@ -5,31 +5,33 @@
 # contributed by Bastian Kleineidam , added 2000-03-18
 
 import os
+from distutils._log import log
+from typing import ClassVar
+
 from ..core import Command
 from ..dir_util import remove_tree
-from distutils._log import log
 
 
 class clean(Command):
     description = "clean up temporary files from 'build' command"
     user_options = [
-        ('build-base=', 'b', "base build directory (default: 'build.build-base')"),
+        ('build-base=', 'b', "base build directory [default: 'build.build-base']"),
         (
             'build-lib=',
             None,
-            "build directory for all modules (default: 'build.build-lib')",
+            "build directory for all modules [default: 'build.build-lib']",
         ),
-        ('build-temp=', 't', "temporary build directory (default: 'build.build-temp')"),
+        ('build-temp=', 't', "temporary build directory [default: 'build.build-temp']"),
         (
             'build-scripts=',
             None,
-            "build directory for scripts (default: 'build.build-scripts')",
+            "build directory for scripts [default: 'build.build-scripts']",
         ),
         ('bdist-base=', None, "temporary directory for built distributions"),
         ('all', 'a', "remove all build output, not just temporary by-products"),
     ]
 
-    boolean_options = ['all']
+    boolean_options: ClassVar[list[str]] = ['all']
 
     def initialize_options(self):
         self.build_base = None
@@ -53,7 +55,7 @@ def run(self):
         # remove the build/temp. directory (unless it's already
         # gone)
         if os.path.exists(self.build_temp):
-            remove_tree(self.build_temp, dry_run=self.dry_run)
+            remove_tree(self.build_temp)
         else:
             log.debug("'%s' does not exist -- can't clean it", self.build_temp)
 
@@ -61,15 +63,14 @@ def run(self):
             # remove build directories
             for directory in (self.build_lib, self.bdist_base, self.build_scripts):
                 if os.path.exists(directory):
-                    remove_tree(directory, dry_run=self.dry_run)
+                    remove_tree(directory)
                 else:
                     log.warning("'%s' does not exist -- can't clean it", directory)
 
         # just for the heck of it, try to remove the base build directory:
         # we might have emptied it right now, but if not we don't care
-        if not self.dry_run:
-            try:
-                os.rmdir(self.build_base)
-                log.info("removing '%s'", self.build_base)
-            except OSError:
-                pass
+        try:
+            os.rmdir(self.build_base)
+            log.info("removing '%s'", self.build_base)
+        except OSError:
+            pass
diff --git a/setuptools/_distutils/command/command_template b/setuptools/_distutils/command/command_template
index 6106819db8..a4a751ad3c 100644
--- a/setuptools/_distutils/command/command_template
+++ b/setuptools/_distutils/command/command_template
@@ -8,18 +8,18 @@ Implements the Distutils 'x' command.
 __revision__ = "$Id$"
 
 from distutils.core import Command
+from typing import ClassVar
 
 
 class x(Command):
-
     # Brief (40-50 characters) description of the command
     description = ""
 
     # List of option tuples: long name, short name (None if no short
     # name), and help string.
-    user_options = [('', '',
-                     ""),
-                   ]
+    user_options: ClassVar[list[tuple[str, str, str]]] = [
+        ('', '', ""),
+    ]
 
     def initialize_options(self):
         self. = None
diff --git a/setuptools/_distutils/command/config.py b/setuptools/_distutils/command/config.py
index 494d97d16f..9818418f26 100644
--- a/setuptools/_distutils/command/config.py
+++ b/setuptools/_distutils/command/config.py
@@ -9,13 +9,18 @@
 this header file lives".
 """
 
+from __future__ import annotations
+
 import os
+import pathlib
 import re
+from collections.abc import Sequence
+from distutils._log import log
 
+from ..ccompiler import CCompiler, CompileError, LinkError, new_compiler
 from ..core import Command
 from ..errors import DistutilsExecError
 from ..sysconfig import customize_compiler
-from distutils._log import log
 
 LANG_EXT = {"c": ".c", "c++": ".cxx"}
 
@@ -84,14 +89,8 @@ def _check_compiler(self):
         """Check that 'self.compiler' really is a CCompiler object;
         if not, make it one.
         """
-        # We do this late, and only on-demand, because this is an expensive
-        # import.
-        from ..ccompiler import CCompiler, new_compiler
-
         if not isinstance(self.compiler, CCompiler):
-            self.compiler = new_compiler(
-                compiler=self.compiler, dry_run=self.dry_run, force=1
-            )
+            self.compiler = new_compiler(compiler=self.compiler, force=True)
             customize_compiler(self.compiler)
             if self.include_dirs:
                 self.compiler.set_include_dirs(self.include_dirs)
@@ -102,10 +101,10 @@ def _check_compiler(self):
 
     def _gen_temp_sourcefile(self, body, headers, lang):
         filename = "_configtest" + LANG_EXT[lang]
-        with open(filename, "w") as file:
+        with open(filename, "w", encoding='utf-8') as file:
             if headers:
                 for header in headers:
-                    file.write("#include <%s>\n" % header)
+                    file.write(f"#include <{header}>\n")
                 file.write("\n")
             file.write(body)
             if body[-1] != "\n":
@@ -122,7 +121,7 @@ def _preprocess(self, body, headers, include_dirs, lang):
     def _compile(self, body, headers, include_dirs, lang):
         src = self._gen_temp_sourcefile(body, headers, lang)
         if self.dump_source:
-            dump_file(src, "compiling '%s':" % src)
+            dump_file(src, f"compiling '{src}':")
         (obj,) = self.compiler.object_filenames([src])
         self.temp_files.extend([src, obj])
         self.compiler.compile([src], include_dirs=include_dirs)
@@ -156,14 +155,6 @@ def _clean(self, *filenames):
             except OSError:
                 pass
 
-    # XXX these ignore the dry-run flag: what to do, what to do? even if
-    # you want a dry-run build, you still need some sort of configuration
-    # info.  My inclination is to make it up to the real config command to
-    # consult 'dry_run', and assume a default (minimal) configuration if
-    # true.  The problem with trying to do it here is that you'd have to
-    # return either true or false from all the 'try' methods, neither of
-    # which is correct.
-
     # XXX need access to the header search path and maybe default macros.
 
     def try_cpp(self, body=None, headers=None, include_dirs=None, lang="c"):
@@ -173,8 +164,6 @@ def try_cpp(self, body=None, headers=None, include_dirs=None, lang="c"):
         preprocessor succeeded, false if there were any errors.
         ('body' probably isn't of much use, but what the heck.)
         """
-        from ..ccompiler import CompileError
-
         self._check_compiler()
         ok = True
         try:
@@ -199,15 +188,8 @@ def search_cpp(self, pattern, body=None, headers=None, include_dirs=None, lang="
         if isinstance(pattern, str):
             pattern = re.compile(pattern)
 
-        with open(out) as file:
-            match = False
-            while True:
-                line = file.readline()
-                if line == '':
-                    break
-                if pattern.search(line):
-                    match = True
-                    break
+        with open(out, encoding='utf-8') as file:
+            match = any(pattern.search(line) for line in file)
 
         self._clean()
         return match
@@ -216,8 +198,6 @@ def try_compile(self, body, headers=None, include_dirs=None, lang="c"):
         """Try to compile a source file built from 'body' and 'headers'.
         Return true on success, false otherwise.
         """
-        from ..ccompiler import CompileError
-
         self._check_compiler()
         try:
             self._compile(body, headers, include_dirs, lang)
@@ -242,8 +222,6 @@ def try_link(
         'headers', to executable form.  Return true on success, false
         otherwise.
         """
-        from ..ccompiler import CompileError, LinkError
-
         self._check_compiler()
         try:
             self._link(body, headers, include_dirs, libraries, library_dirs, lang)
@@ -268,8 +246,6 @@ def try_run(
         built from 'body' and 'headers'.  Return true on success, false
         otherwise.
         """
-        from ..ccompiler import CompileError, LinkError
-
         self._check_compiler()
         try:
             src, obj, exe = self._link(
@@ -295,8 +271,8 @@ def check_func(
         include_dirs=None,
         libraries=None,
         library_dirs=None,
-        decl=0,
-        call=0,
+        decl=False,
+        call=False,
     ):
         """Determine if function 'func' is available by constructing a
         source file that refers to 'func', and compiles and links it.
@@ -314,12 +290,12 @@ def check_func(
         self._check_compiler()
         body = []
         if decl:
-            body.append("int %s ();" % func)
+            body.append(f"int {func} ();")
         body.append("int main () {")
         if call:
-            body.append("  %s();" % func)
+            body.append(f"  {func}();")
         else:
-            body.append("  %s;" % func)
+            body.append(f"  {func};")
         body.append("}")
         body = "\n".join(body) + "\n"
 
@@ -331,7 +307,7 @@ def check_lib(
         library_dirs=None,
         headers=None,
         include_dirs=None,
-        other_libraries=[],
+        other_libraries: Sequence[str] = [],
     ):
         """Determine if 'library' is available to be linked against,
         without actually checking that any particular symbols are provided
@@ -346,7 +322,7 @@ def check_lib(
             "int main (void) { }",
             headers,
             include_dirs,
-            [library] + other_libraries,
+            [library] + list(other_libraries),
             library_dirs,
         )
 
@@ -369,8 +345,4 @@ def dump_file(filename, head=None):
         log.info('%s', filename)
     else:
         log.info(head)
-    file = open(filename)
-    try:
-        log.info(file.read())
-    finally:
-        file.close()
+    log.info(pathlib.Path(filename).read_text(encoding='utf-8'))
diff --git a/setuptools/_distutils/command/install.py b/setuptools/_distutils/command/install.py
index a7ac4e6077..dc17e56a80 100644
--- a/setuptools/_distutils/command/install.py
+++ b/setuptools/_distutils/command/install.py
@@ -2,25 +2,25 @@
 
 Implements the Distutils 'install' command."""
 
-import sys
-import os
+from __future__ import annotations
+
+import collections
 import contextlib
-import sysconfig
 import itertools
-
+import os
+import sys
+import sysconfig
 from distutils._log import log
+from site import USER_BASE, USER_SITE
+from typing import ClassVar
+
 from ..core import Command
 from ..debug import DEBUG
-from ..sysconfig import get_config_vars
-from ..file_util import write_file
-from ..util import convert_path, subst_vars, change_root
-from ..util import get_platform
 from ..errors import DistutilsOptionError, DistutilsPlatformError
+from ..file_util import write_file
+from ..sysconfig import get_config_vars
+from ..util import change_root, convert_path, get_platform, subst_vars
 from . import _framework_compat as fw
-from .. import _collections
-
-from site import USER_BASE
-from site import USER_SITE
 
 HAS_USER_SITE = True
 
@@ -144,7 +144,7 @@ def _resolve_scheme(name):
     try:
         resolved = sysconfig.get_preferred_scheme(key)
     except Exception:
-        resolved = fw.scheme(_pypy_hack(name))
+        resolved = fw.scheme(name)
     return resolved
 
 
@@ -161,7 +161,7 @@ def _inject_headers(name, scheme):
     """
     # Bypass the preferred scheme, which may not
     # have defined headers.
-    fallback = _load_scheme(_pypy_hack(name))
+    fallback = _load_scheme(name)
     scheme.setdefault('headers', fallback['headers'])
     return scheme
 
@@ -171,14 +171,6 @@ def _scheme_attrs(scheme):
     return {f'install_{key}': scheme[key] for key in SCHEME_KEYS}
 
 
-def _pypy_hack(name):
-    PY37 = sys.version_info < (3, 8)
-    old_pypy = hasattr(sys, 'pypy_version_info') and PY37
-    prefix = not name.endswith(('_user', '_home'))
-    pypy_name = 'pypy' + '_nt' * (os.name == 'nt')
-    return pypy_name if old_pypy and prefix else name
-
-
 class install(Command):
     description = "install everything from build directory"
 
@@ -196,8 +188,7 @@ class install(Command):
         (
             'install-platbase=',
             None,
-            "base installation directory for platform-specific files "
-            + "(instead of --exec-prefix or --home)",
+            "base installation directory for platform-specific files (instead of --exec-prefix or --home)",
         ),
         ('root=', None, "install everything relative to this alternate root directory"),
         # Or, explicitly set the installation scheme
@@ -214,8 +205,7 @@ class install(Command):
         (
             'install-lib=',
             None,
-            "installation directory for all module distributions "
-            + "(overrides --install-purelib and --install-platlib)",
+            "installation directory for all module distributions (overrides --install-purelib and --install-platlib)",
         ),
         ('install-headers=', None, "installation directory for C/C++ headers"),
         ('install-scripts=', None, "installation directory for Python scripts"),
@@ -242,31 +232,33 @@ class install(Command):
         ('record=', None, "filename in which to record list of installed files"),
     ]
 
-    boolean_options = ['compile', 'force', 'skip-build']
+    boolean_options: ClassVar[list[str]] = ['compile', 'force', 'skip-build']
 
     if HAS_USER_SITE:
-        user_options.append(
-            ('user', None, "install in user site-package '%s'" % USER_SITE)
-        )
+        user_options.append((
+            'user',
+            None,
+            f"install in user site-package '{USER_SITE}'",
+        ))
         boolean_options.append('user')
 
-    negative_opt = {'no-compile': 'compile'}
+    negative_opt: ClassVar[dict[str, str]] = {'no-compile': 'compile'}
 
-    def initialize_options(self):
+    def initialize_options(self) -> None:
         """Initializes options."""
         # High-level options: these select both an installation base
         # and scheme.
-        self.prefix = None
-        self.exec_prefix = None
-        self.home = None
-        self.user = 0
+        self.prefix: str | None = None
+        self.exec_prefix: str | None = None
+        self.home: str | None = None
+        self.user = False
 
         # These select only the installation base; it's up to the user to
         # specify the installation scheme (currently, that means supplying
         # the --install-{platlib,purelib,scripts,data} options).
         self.install_base = None
         self.install_platbase = None
-        self.root = None
+        self.root: str | None = None
 
         # These options are the actual installation directories; if not
         # supplied by the user, they are filled in using the installation
@@ -275,7 +267,7 @@ def initialize_options(self):
         self.install_purelib = None  # for pure module distributions
         self.install_platlib = None  # non-pure (dists w/ extensions)
         self.install_headers = None  # for C/C++ headers
-        self.install_lib = None  # set to either purelib or platlib
+        self.install_lib: str | None = None  # set to either purelib or platlib
         self.install_scripts = None
         self.install_data = None
         self.install_userbase = USER_BASE
@@ -294,7 +286,7 @@ def initialize_options(self):
         # 'install_path_file' is always true unless some outsider meddles
         # with it.
         self.extra_path = None
-        self.install_path_file = 1
+        self.install_path_file = True
 
         # 'force' forces installation, even if target files are not
         # out-of-date.  'skip_build' skips running the "build" command,
@@ -302,9 +294,9 @@ def initialize_options(self):
         # a user option, it's just there so the bdist_* commands can turn
         # it off) determines whether we warn about installing to a
         # directory not in sys.path.
-        self.force = 0
-        self.skip_build = 0
-        self.warn_dir = 1
+        self.force = False
+        self.skip_build = False
+        self.warn_dir = True
 
         # These are only here as a conduit from the 'build' command to the
         # 'install_*' commands that do the real work.  ('build_base' isn't
@@ -329,7 +321,7 @@ def initialize_options(self):
     # party Python modules on various platforms given a wide
     # array of user input is decided.  Yes, it's quite complex!)
 
-    def finalize_options(self):  # noqa: C901
+    def finalize_options(self) -> None:  # noqa: C901
         """Finalizes options."""
         # This method (and its helpers, like 'finalize_unix()',
         # 'finalize_other()', and 'select_scheme()') is where the default
@@ -349,8 +341,7 @@ def finalize_options(self):  # noqa: C901
             self.install_base or self.install_platbase
         ):
             raise DistutilsOptionError(
-                "must supply either prefix/exec-prefix/home or "
-                + "install-base/install-platbase -- not both"
+                "must supply either prefix/exec-prefix/home or install-base/install-platbase -- not both"
             )
 
         if self.home and (self.prefix or self.exec_prefix):
@@ -410,8 +401,8 @@ def finalize_options(self):  # noqa: C901
             'dist_version': self.distribution.get_version(),
             'dist_fullname': self.distribution.get_fullname(),
             'py_version': py_version,
-            'py_version_short': '%d.%d' % sys.version_info[:2],
-            'py_version_nodot': '%d%d' % sys.version_info[:2],
+            'py_version_short': f'{sys.version_info.major}.{sys.version_info.minor}',
+            'py_version_nodot': f'{sys.version_info.major}{sys.version_info.minor}',
             'sys_prefix': prefix,
             'prefix': prefix,
             'sys_exec_prefix': exec_prefix,
@@ -432,8 +423,11 @@ def finalize_options(self):  # noqa: C901
             local_vars['userbase'] = self.install_userbase
             local_vars['usersite'] = self.install_usersite
 
-        self.config_vars = _collections.DictStack(
-            [fw.vars(), compat_vars, sysconfig.get_config_vars(), local_vars]
+        self.config_vars = collections.ChainMap(
+            local_vars,
+            sysconfig.get_config_vars(),
+            compat_vars,
+            fw.vars(),
         )
 
         self.expand_basedirs()
@@ -510,7 +504,7 @@ def finalize_options(self):  # noqa: C901
         # Punt on doc directories for now -- after all, we're punting on
         # documentation completely!
 
-    def dump_dirs(self, msg):
+    def dump_dirs(self, msg) -> None:
         """Dumps the list of user options."""
         if not DEBUG:
             return
@@ -530,7 +524,7 @@ def dump_dirs(self, msg):
                 val = getattr(self, opt_name)
             log.debug("  %s: %s", opt_name, val)
 
-    def finalize_unix(self):
+    def finalize_unix(self) -> None:
         """Finalizes options for posix platforms."""
         if self.install_base is not None or self.install_platbase is not None:
             incomplete_scheme = (
@@ -579,7 +573,7 @@ def finalize_unix(self):
             self.install_platbase = self.exec_prefix
             self.select_scheme("posix_prefix")
 
-    def finalize_other(self):
+    def finalize_other(self) -> None:
         """Finalizes options for non-posix platforms"""
         if self.user:
             if self.install_userbase is None:
@@ -598,10 +592,10 @@ def finalize_other(self):
                 self.select_scheme(os.name)
             except KeyError:
                 raise DistutilsPlatformError(
-                    "I don't know how to install stuff on '%s'" % os.name
+                    f"I don't know how to install stuff on '{os.name}'"
                 )
 
-    def select_scheme(self, name):
+    def select_scheme(self, name) -> None:
         _select_scheme(self, name)
 
     def _expand_attrs(self, attrs):
@@ -613,31 +607,29 @@ def _expand_attrs(self, attrs):
                 val = subst_vars(val, self.config_vars)
                 setattr(self, attr, val)
 
-    def expand_basedirs(self):
+    def expand_basedirs(self) -> None:
         """Calls `os.path.expanduser` on install_base, install_platbase and
         root."""
         self._expand_attrs(['install_base', 'install_platbase', 'root'])
 
-    def expand_dirs(self):
+    def expand_dirs(self) -> None:
         """Calls `os.path.expanduser` on install dirs."""
-        self._expand_attrs(
-            [
-                'install_purelib',
-                'install_platlib',
-                'install_lib',
-                'install_headers',
-                'install_scripts',
-                'install_data',
-            ]
-        )
-
-    def convert_paths(self, *names):
+        self._expand_attrs([
+            'install_purelib',
+            'install_platlib',
+            'install_lib',
+            'install_headers',
+            'install_scripts',
+            'install_data',
+        ])
+
+    def convert_paths(self, *names) -> None:
         """Call `convert_path` over `names`."""
         for name in names:
             attr = "install_" + name
             setattr(self, attr, convert_path(getattr(self, attr)))
 
-    def handle_extra_path(self):
+    def handle_extra_path(self) -> None:
         """Set `path_file` and `extra_dirs` using `extra_path`."""
         if self.extra_path is None:
             self.extra_path = self.distribution.extra_path
@@ -672,20 +664,20 @@ def handle_extra_path(self):
         self.path_file = path_file
         self.extra_dirs = extra_dirs
 
-    def change_roots(self, *names):
+    def change_roots(self, *names) -> None:
         """Change the install directories pointed by name using root."""
         for name in names:
             attr = "install_" + name
             setattr(self, attr, change_root(self.root, getattr(self, attr)))
 
-    def create_home_path(self):
+    def create_home_path(self) -> None:
         """Create directories under ~."""
         if not self.user:
             return
         home = convert_path(os.path.expanduser("~"))
-        for name, path in self.config_vars.items():
+        for path in self.config_vars.values():
             if str(path).startswith(home) and not os.path.isdir(path):
-                self.debug_print("os.makedirs('%s', 0o700)" % path)
+                self.debug_print(f"os.makedirs('{path}', 0o700)")
                 os.makedirs(path, 0o700)
 
     # -- Command execution methods -------------------------------------
@@ -701,7 +693,7 @@ def run(self):
             # internally, and not to sys.path, so we don't check the platform
             # matches what we are running.
             if self.warn_dir and build_plat != get_platform():
-                raise DistutilsPlatformError("Can't install when " "cross-compiling")
+                raise DistutilsPlatformError("Can't install when cross-compiling")
 
         # Run all sub-commands (at least those that need to be run)
         for cmd_name in self.get_sub_commands():
@@ -720,7 +712,7 @@ def run(self):
             self.execute(
                 write_file,
                 (self.record, outputs),
-                "writing list of installed files to '%s'" % self.record,
+                f"writing list of installed files to '{self.record}'",
             )
 
         sys_path = map(os.path.normpath, sys.path)
@@ -745,10 +737,10 @@ def create_path_file(self):
         filename = os.path.join(self.install_libbase, self.path_file + ".pth")
         if self.install_path_file:
             self.execute(
-                write_file, (filename, [self.extra_dirs]), "creating %s" % filename
+                write_file, (filename, [self.extra_dirs]), f"creating {filename}"
             )
         else:
-            self.warn("path file '%s' not created" % filename)
+            self.warn(f"path file '{filename}' not created")
 
     # -- Reporting methods ---------------------------------------------
 
diff --git a/setuptools/_distutils/command/install_data.py b/setuptools/_distutils/command/install_data.py
index 7ba35eef82..4ad186e8ec 100644
--- a/setuptools/_distutils/command/install_data.py
+++ b/setuptools/_distutils/command/install_data.py
@@ -5,7 +5,13 @@
 
 # contributed by Bastian Kleineidam
 
+from __future__ import annotations
+
+import functools
 import os
+from collections.abc import Iterable
+from typing import ClassVar
+
 from ..core import Command
 from ..util import change_root, convert_path
 
@@ -17,24 +23,23 @@ class install_data(Command):
         (
             'install-dir=',
             'd',
-            "base directory for installing data files "
-            "(default: installation base dir)",
+            "base directory for installing data files [default: installation base dir]",
         ),
         ('root=', None, "install everything relative to this alternate root directory"),
         ('force', 'f', "force installation (overwrite existing files)"),
     ]
 
-    boolean_options = ['force']
+    boolean_options: ClassVar[list[str]] = ['force']
 
     def initialize_options(self):
         self.install_dir = None
         self.outfiles = []
         self.root = None
-        self.force = 0
+        self.force = False
         self.data_files = self.distribution.data_files
-        self.warn_dir = 1
+        self.warn_dir = True
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         self.set_undefined_options(
             'install',
             ('install_data', 'install_dir'),
@@ -42,39 +47,45 @@ def finalize_options(self):
             ('force', 'force'),
         )
 
-    def run(self):
+    def run(self) -> None:
         self.mkpath(self.install_dir)
         for f in self.data_files:
-            if isinstance(f, str):
-                # it's a simple file, so copy it
-                f = convert_path(f)
-                if self.warn_dir:
-                    self.warn(
-                        "setup script did not provide a directory for "
-                        "'%s' -- installing right in '%s'" % (f, self.install_dir)
-                    )
-                (out, _) = self.copy_file(f, self.install_dir)
+            self._copy(f)
+
+    @functools.singledispatchmethod
+    def _copy(self, f: tuple[str | os.PathLike, Iterable[str | os.PathLike]]):
+        # it's a tuple with path to install to and a list of files
+        dir = convert_path(f[0])
+        if not os.path.isabs(dir):
+            dir = os.path.join(self.install_dir, dir)
+        elif self.root:
+            dir = change_root(self.root, dir)
+        self.mkpath(dir)
+
+        if f[1] == []:
+            # If there are no files listed, the user must be
+            # trying to create an empty directory, so add the
+            # directory to the list of output files.
+            self.outfiles.append(dir)
+        else:
+            # Copy files, adding them to the list of output files.
+            for data in f[1]:
+                data = convert_path(data)
+                (out, _) = self.copy_file(data, dir)
                 self.outfiles.append(out)
-            else:
-                # it's a tuple with path to install to and a list of files
-                dir = convert_path(f[0])
-                if not os.path.isabs(dir):
-                    dir = os.path.join(self.install_dir, dir)
-                elif self.root:
-                    dir = change_root(self.root, dir)
-                self.mkpath(dir)
-
-                if f[1] == []:
-                    # If there are no files listed, the user must be
-                    # trying to create an empty directory, so add the
-                    # directory to the list of output files.
-                    self.outfiles.append(dir)
-                else:
-                    # Copy files, adding them to the list of output files.
-                    for data in f[1]:
-                        data = convert_path(data)
-                        (out, _) = self.copy_file(data, dir)
-                        self.outfiles.append(out)
+
+    @_copy.register(str)
+    @_copy.register(os.PathLike)
+    def _(self, f: str | os.PathLike):
+        # it's a simple file, so copy it
+        f = convert_path(f)
+        if self.warn_dir:
+            self.warn(
+                "setup script did not provide a directory for "
+                f"'{f}' -- installing right in '{self.install_dir}'"
+            )
+        (out, _) = self.copy_file(f, self.install_dir)
+        self.outfiles.append(out)
 
     def get_inputs(self):
         return self.data_files or []
diff --git a/setuptools/_distutils/command/install_egg_info.py b/setuptools/_distutils/command/install_egg_info.py
index f3e8f3447d..6840b34ec2 100644
--- a/setuptools/_distutils/command/install_egg_info.py
+++ b/setuptools/_distutils/command/install_egg_info.py
@@ -6,19 +6,20 @@
 """
 
 import os
-import sys
 import re
+import sys
+from typing import ClassVar
 
-from ..cmd import Command
 from .. import dir_util
 from .._log import log
+from ..cmd import Command
 
 
 class install_egg_info(Command):
     """Install an .egg-info file for the package"""
 
     description = "Install package's PKG-INFO metadata as an .egg-info file"
-    user_options = [
+    user_options: ClassVar[list[tuple[str, str, str]]] = [
         ('install-dir=', 'd', "directory to install to"),
     ]
 
@@ -31,11 +32,9 @@ def basename(self):
         Allow basename to be overridden by child class.
         Ref pypa/distutils#2.
         """
-        return "%s-%s-py%d.%d.egg-info" % (
-            to_filename(safe_name(self.distribution.get_name())),
-            to_filename(safe_version(self.distribution.get_version())),
-            *sys.version_info[:2],
-        )
+        name = to_filename(safe_name(self.distribution.get_name()))
+        version = to_filename(safe_version(self.distribution.get_version()))
+        return f"{name}-{version}-py{sys.version_info.major}.{sys.version_info.minor}.egg-info"
 
     def finalize_options(self):
         self.set_undefined_options('install_lib', ('install_dir', 'install_dir'))
@@ -45,7 +44,7 @@ def finalize_options(self):
     def run(self):
         target = self.target
         if os.path.isdir(target) and not os.path.islink(target):
-            dir_util.remove_tree(target, dry_run=self.dry_run)
+            dir_util.remove_tree(target)
         elif os.path.exists(target):
             self.execute(os.unlink, (self.target,), "Removing " + target)
         elif not os.path.isdir(self.install_dir):
@@ -53,9 +52,8 @@ def run(self):
                 os.makedirs, (self.install_dir,), "Creating " + self.install_dir
             )
         log.info("Writing %s", target)
-        if not self.dry_run:
-            with open(target, 'w', encoding='UTF-8') as f:
-                self.distribution.metadata.write_pkg_file(f)
+        with open(target, 'w', encoding='UTF-8') as f:
+            self.distribution.metadata.write_pkg_file(f)
 
     def get_outputs(self):
         return self.outputs
diff --git a/setuptools/_distutils/command/install_headers.py b/setuptools/_distutils/command/install_headers.py
index 085272c1a2..97af1371ef 100644
--- a/setuptools/_distutils/command/install_headers.py
+++ b/setuptools/_distutils/command/install_headers.py
@@ -3,6 +3,8 @@
 Implements the Distutils 'install_headers' command, to install C/C++ header
 files to the Python include directory."""
 
+from typing import ClassVar
+
 from ..core import Command
 
 
@@ -10,16 +12,16 @@
 class install_headers(Command):
     description = "install C/C++ header files"
 
-    user_options = [
+    user_options: ClassVar[list[tuple[str, str, str]]] = [
         ('install-dir=', 'd', "directory to install header files to"),
         ('force', 'f', "force installation (overwrite existing files)"),
     ]
 
-    boolean_options = ['force']
+    boolean_options: ClassVar[list[str]] = ['force']
 
     def initialize_options(self):
         self.install_dir = None
-        self.force = 0
+        self.force = False
         self.outfiles = []
 
     def finalize_options(self):
diff --git a/setuptools/_distutils/command/install_lib.py b/setuptools/_distutils/command/install_lib.py
index be4c243321..9909a61762 100644
--- a/setuptools/_distutils/command/install_lib.py
+++ b/setuptools/_distutils/command/install_lib.py
@@ -3,14 +3,16 @@
 Implements the Distutils 'install_lib' command
 (install all Python modules)."""
 
-import os
+from __future__ import annotations
+
 import importlib.util
+import os
 import sys
+from typing import Any, ClassVar
 
 from ..core import Command
 from ..errors import DistutilsOptionError
 
-
 # Extension for Python source files.
 PYTHON_SOURCE_EXTENSION = ".py"
 
@@ -48,19 +50,19 @@ class install_lib(Command):
         ('skip-build', None, "skip the build steps"),
     ]
 
-    boolean_options = ['force', 'compile', 'skip-build']
-    negative_opt = {'no-compile': 'compile'}
+    boolean_options: ClassVar[list[str]] = ['force', 'compile', 'skip-build']
+    negative_opt: ClassVar[dict[str, str]] = {'no-compile': 'compile'}
 
     def initialize_options(self):
         # let the 'install' command dictate our installation directory
         self.install_dir = None
         self.build_dir = None
-        self.force = 0
+        self.force = False
         self.compile = None
         self.optimize = None
         self.skip_build = None
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         # Get all the information we need to install pure Python modules
         # from the umbrella 'install' command -- build (source) directory,
         # install (target) directory, and whether to compile .py files.
@@ -82,12 +84,12 @@ def finalize_options(self):
         if not isinstance(self.optimize, int):
             try:
                 self.optimize = int(self.optimize)
-                if self.optimize not in (0, 1, 2):
-                    raise AssertionError
-            except (ValueError, AssertionError):
+            except ValueError:
+                pass
+            if self.optimize not in (0, 1, 2):
                 raise DistutilsOptionError("optimize must be 0, 1, or 2")
 
-    def run(self):
+    def run(self) -> None:
         # Make sure we have built everything we need first
         self.build()
 
@@ -103,24 +105,25 @@ def run(self):
     # -- Top-level worker functions ------------------------------------
     # (called from 'run()')
 
-    def build(self):
+    def build(self) -> None:
         if not self.skip_build:
             if self.distribution.has_pure_modules():
                 self.run_command('build_py')
             if self.distribution.has_ext_modules():
                 self.run_command('build_ext')
 
-    def install(self):
+    # Any: https://typing.readthedocs.io/en/latest/guides/writing_stubs.html#the-any-trick
+    def install(self) -> list[str] | Any:
         if os.path.isdir(self.build_dir):
             outfiles = self.copy_tree(self.build_dir, self.install_dir)
         else:
             self.warn(
-                "'%s' does not exist -- no Python modules to install" % self.build_dir
+                f"'{self.build_dir}' does not exist -- no Python modules to install"
             )
             return
         return outfiles
 
-    def byte_compile(self, files):
+    def byte_compile(self, files) -> None:
         if sys.dont_write_bytecode:
             self.warn('byte-compiling is disabled, skipping.')
             return
@@ -139,7 +142,6 @@ def byte_compile(self, files):
                 optimize=0,
                 force=self.force,
                 prefix=install_root,
-                dry_run=self.dry_run,
             )
         if self.optimize > 0:
             byte_compile(
@@ -148,7 +150,6 @@ def byte_compile(self, files):
                 force=self.force,
                 prefix=install_root,
                 verbose=self.verbose,
-                dry_run=self.dry_run,
             )
 
     # -- Utility methods -----------------------------------------------
@@ -162,9 +163,7 @@ def _mutate_outputs(self, has_any, build_cmd, cmd_option, output_dir):
         build_dir = getattr(build_cmd, cmd_option)
 
         prefix_len = len(build_dir) + len(os.sep)
-        outputs = []
-        for file in build_files:
-            outputs.append(os.path.join(output_dir, file[prefix_len:]))
+        outputs = [os.path.join(output_dir, file[prefix_len:]) for file in build_files]
 
         return outputs
 
diff --git a/setuptools/_distutils/command/install_scripts.py b/setuptools/_distutils/command/install_scripts.py
index 20f07aaa27..33d235d976 100644
--- a/setuptools/_distutils/command/install_scripts.py
+++ b/setuptools/_distutils/command/install_scripts.py
@@ -6,9 +6,11 @@
 # contributed by Bastian Kleineidam
 
 import os
-from ..core import Command
 from distutils._log import log
 from stat import ST_MODE
+from typing import ClassVar
+
+from ..core import Command
 
 
 class install_scripts(Command):
@@ -21,15 +23,15 @@ class install_scripts(Command):
         ('skip-build', None, "skip the build steps"),
     ]
 
-    boolean_options = ['force', 'skip-build']
+    boolean_options: ClassVar[list[str]] = ['force', 'skip-build']
 
     def initialize_options(self):
         self.install_dir = None
-        self.force = 0
+        self.force = False
         self.build_dir = None
         self.skip_build = None
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         self.set_undefined_options('build', ('build_scripts', 'build_dir'))
         self.set_undefined_options(
             'install',
@@ -38,7 +40,7 @@ def finalize_options(self):
             ('skip_build', 'skip_build'),
         )
 
-    def run(self):
+    def run(self) -> None:
         if not self.skip_build:
             self.run_command('build_scripts')
         self.outfiles = self.copy_tree(self.build_dir, self.install_dir)
@@ -46,12 +48,9 @@ def run(self):
             # Set the executable bits (owner, group, and world) on
             # all the scripts we just installed.
             for file in self.get_outputs():
-                if self.dry_run:
-                    log.info("changing mode of %s", file)
-                else:
-                    mode = ((os.stat(file)[ST_MODE]) | 0o555) & 0o7777
-                    log.info("changing mode of %s to %o", file, mode)
-                    os.chmod(file, mode)
+                mode = ((os.stat(file)[ST_MODE]) | 0o555) & 0o7777
+                log.info("changing mode of %s to %o", file, mode)
+                os.chmod(file, mode)
 
     def get_inputs(self):
         return self.distribution.scripts or []
diff --git a/setuptools/_distutils/command/py37compat.py b/setuptools/_distutils/command/py37compat.py
deleted file mode 100644
index aa0c0a7fcd..0000000000
--- a/setuptools/_distutils/command/py37compat.py
+++ /dev/null
@@ -1,31 +0,0 @@
-import sys
-
-
-def _pythonlib_compat():
-    """
-    On Python 3.7 and earlier, distutils would include the Python
-    library. See pypa/distutils#9.
-    """
-    from distutils import sysconfig
-
-    if not sysconfig.get_config_var('Py_ENABLED_SHARED'):
-        return
-
-    yield 'python{}.{}{}'.format(
-        sys.hexversion >> 24,
-        (sys.hexversion >> 16) & 0xFF,
-        sysconfig.get_config_var('ABIFLAGS'),
-    )
-
-
-def compose(f1, f2):
-    return lambda *args, **kwargs: f1(f2(*args, **kwargs))
-
-
-pythonlib = (
-    compose(list, _pythonlib_compat)
-    if sys.version_info < (3, 8)
-    and sys.platform != 'darwin'
-    and sys.platform[:3] != 'aix'
-    else list
-)
diff --git a/setuptools/_distutils/command/register.py b/setuptools/_distutils/command/register.py
deleted file mode 100644
index c19aabb91f..0000000000
--- a/setuptools/_distutils/command/register.py
+++ /dev/null
@@ -1,320 +0,0 @@
-"""distutils.command.register
-
-Implements the Distutils 'register' command (register with the repository).
-"""
-
-# created 2002/10/21, Richard Jones
-
-import getpass
-import io
-import logging
-import urllib.parse
-import urllib.request
-from warnings import warn
-
-from ..core import PyPIRCCommand
-from distutils._log import log
-
-
-class register(PyPIRCCommand):
-    description = "register the distribution with the Python package index"
-    user_options = PyPIRCCommand.user_options + [
-        ('list-classifiers', None, 'list the valid Trove classifiers'),
-        (
-            'strict',
-            None,
-            'Will stop the registering if the meta-data are not fully compliant',
-        ),
-    ]
-    boolean_options = PyPIRCCommand.boolean_options + [
-        'verify',
-        'list-classifiers',
-        'strict',
-    ]
-
-    sub_commands = [('check', lambda self: True)]
-
-    def initialize_options(self):
-        PyPIRCCommand.initialize_options(self)
-        self.list_classifiers = 0
-        self.strict = 0
-
-    def finalize_options(self):
-        PyPIRCCommand.finalize_options(self)
-        # setting options for the `check` subcommand
-        check_options = {
-            'strict': ('register', self.strict),
-            'restructuredtext': ('register', 1),
-        }
-        self.distribution.command_options['check'] = check_options
-
-    def run(self):
-        self.finalize_options()
-        self._set_config()
-
-        # Run sub commands
-        for cmd_name in self.get_sub_commands():
-            self.run_command(cmd_name)
-
-        if self.dry_run:
-            self.verify_metadata()
-        elif self.list_classifiers:
-            self.classifiers()
-        else:
-            self.send_metadata()
-
-    def check_metadata(self):
-        """Deprecated API."""
-        warn(
-            "distutils.command.register.check_metadata is deprecated; "
-            "use the check command instead",
-            DeprecationWarning,
-        )
-        check = self.distribution.get_command_obj('check')
-        check.ensure_finalized()
-        check.strict = self.strict
-        check.restructuredtext = 1
-        check.run()
-
-    def _set_config(self):
-        '''Reads the configuration file and set attributes.'''
-        config = self._read_pypirc()
-        if config != {}:
-            self.username = config['username']
-            self.password = config['password']
-            self.repository = config['repository']
-            self.realm = config['realm']
-            self.has_config = True
-        else:
-            if self.repository not in ('pypi', self.DEFAULT_REPOSITORY):
-                raise ValueError('%s not found in .pypirc' % self.repository)
-            if self.repository == 'pypi':
-                self.repository = self.DEFAULT_REPOSITORY
-            self.has_config = False
-
-    def classifiers(self):
-        '''Fetch the list of classifiers from the server.'''
-        url = self.repository + '?:action=list_classifiers'
-        response = urllib.request.urlopen(url)
-        log.info(self._read_pypi_response(response))
-
-    def verify_metadata(self):
-        '''Send the metadata to the package index server to be checked.'''
-        # send the info to the server and report the result
-        (code, result) = self.post_to_server(self.build_post_data('verify'))
-        log.info('Server response (%s): %s', code, result)
-
-    def send_metadata(self):  # noqa: C901
-        '''Send the metadata to the package index server.
-
-        Well, do the following:
-        1. figure who the user is, and then
-        2. send the data as a Basic auth'ed POST.
-
-        First we try to read the username/password from $HOME/.pypirc,
-        which is a ConfigParser-formatted file with a section
-        [distutils] containing username and password entries (both
-        in clear text). Eg:
-
-            [distutils]
-            index-servers =
-                pypi
-
-            [pypi]
-            username: fred
-            password: sekrit
-
-        Otherwise, to figure who the user is, we offer the user three
-        choices:
-
-         1. use existing login,
-         2. register as a new user, or
-         3. set the password to a random string and email the user.
-
-        '''
-        # see if we can short-cut and get the username/password from the
-        # config
-        if self.has_config:
-            choice = '1'
-            username = self.username
-            password = self.password
-        else:
-            choice = 'x'
-            username = password = ''
-
-        # get the user's login info
-        choices = '1 2 3 4'.split()
-        while choice not in choices:
-            self.announce(
-                '''\
-We need to know who you are, so please choose either:
- 1. use your existing login,
- 2. register as a new user,
- 3. have the server generate a new password for you (and email it to you), or
- 4. quit
-Your selection [default 1]: ''',
-                logging.INFO,
-            )
-            choice = input()
-            if not choice:
-                choice = '1'
-            elif choice not in choices:
-                print('Please choose one of the four options!')
-
-        if choice == '1':
-            # get the username and password
-            while not username:
-                username = input('Username: ')
-            while not password:
-                password = getpass.getpass('Password: ')
-
-            # set up the authentication
-            auth = urllib.request.HTTPPasswordMgr()
-            host = urllib.parse.urlparse(self.repository)[1]
-            auth.add_password(self.realm, host, username, password)
-            # send the info to the server and report the result
-            code, result = self.post_to_server(self.build_post_data('submit'), auth)
-            self.announce('Server response ({}): {}'.format(code, result), logging.INFO)
-
-            # possibly save the login
-            if code == 200:
-                if self.has_config:
-                    # sharing the password in the distribution instance
-                    # so the upload command can reuse it
-                    self.distribution.password = password
-                else:
-                    self.announce(
-                        (
-                            'I can store your PyPI login so future '
-                            'submissions will be faster.'
-                        ),
-                        logging.INFO,
-                    )
-                    self.announce(
-                        '(the login will be stored in %s)' % self._get_rc_file(),
-                        logging.INFO,
-                    )
-                    choice = 'X'
-                    while choice.lower() not in 'yn':
-                        choice = input('Save your login (y/N)?')
-                        if not choice:
-                            choice = 'n'
-                    if choice.lower() == 'y':
-                        self._store_pypirc(username, password)
-
-        elif choice == '2':
-            data = {':action': 'user'}
-            data['name'] = data['password'] = data['email'] = ''
-            data['confirm'] = None
-            while not data['name']:
-                data['name'] = input('Username: ')
-            while data['password'] != data['confirm']:
-                while not data['password']:
-                    data['password'] = getpass.getpass('Password: ')
-                while not data['confirm']:
-                    data['confirm'] = getpass.getpass(' Confirm: ')
-                if data['password'] != data['confirm']:
-                    data['password'] = ''
-                    data['confirm'] = None
-                    print("Password and confirm don't match!")
-            while not data['email']:
-                data['email'] = input('   EMail: ')
-            code, result = self.post_to_server(data)
-            if code != 200:
-                log.info('Server response (%s): %s', code, result)
-            else:
-                log.info('You will receive an email shortly.')
-                log.info('Follow the instructions in it to ' 'complete registration.')
-        elif choice == '3':
-            data = {':action': 'password_reset'}
-            data['email'] = ''
-            while not data['email']:
-                data['email'] = input('Your email address: ')
-            code, result = self.post_to_server(data)
-            log.info('Server response (%s): %s', code, result)
-
-    def build_post_data(self, action):
-        # figure the data to send - the metadata plus some additional
-        # information used by the package server
-        meta = self.distribution.metadata
-        data = {
-            ':action': action,
-            'metadata_version': '1.0',
-            'name': meta.get_name(),
-            'version': meta.get_version(),
-            'summary': meta.get_description(),
-            'home_page': meta.get_url(),
-            'author': meta.get_contact(),
-            'author_email': meta.get_contact_email(),
-            'license': meta.get_licence(),
-            'description': meta.get_long_description(),
-            'keywords': meta.get_keywords(),
-            'platform': meta.get_platforms(),
-            'classifiers': meta.get_classifiers(),
-            'download_url': meta.get_download_url(),
-            # PEP 314
-            'provides': meta.get_provides(),
-            'requires': meta.get_requires(),
-            'obsoletes': meta.get_obsoletes(),
-        }
-        if data['provides'] or data['requires'] or data['obsoletes']:
-            data['metadata_version'] = '1.1'
-        return data
-
-    def post_to_server(self, data, auth=None):  # noqa: C901
-        '''Post a query to the server, and return a string response.'''
-        if 'name' in data:
-            self.announce(
-                'Registering {} to {}'.format(data['name'], self.repository),
-                logging.INFO,
-            )
-        # Build up the MIME payload for the urllib2 POST data
-        boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
-        sep_boundary = '\n--' + boundary
-        end_boundary = sep_boundary + '--'
-        body = io.StringIO()
-        for key, value in data.items():
-            # handle multiple entries for the same name
-            if type(value) not in (type([]), type(())):
-                value = [value]
-            for value in value:
-                value = str(value)
-                body.write(sep_boundary)
-                body.write('\nContent-Disposition: form-data; name="%s"' % key)
-                body.write("\n\n")
-                body.write(value)
-                if value and value[-1] == '\r':
-                    body.write('\n')  # write an extra newline (lurve Macs)
-        body.write(end_boundary)
-        body.write("\n")
-        body = body.getvalue().encode("utf-8")
-
-        # build the Request
-        headers = {
-            'Content-type': 'multipart/form-data; boundary=%s; charset=utf-8'
-            % boundary,
-            'Content-length': str(len(body)),
-        }
-        req = urllib.request.Request(self.repository, body, headers)
-
-        # handle HTTP and include the Basic Auth handler
-        opener = urllib.request.build_opener(
-            urllib.request.HTTPBasicAuthHandler(password_mgr=auth)
-        )
-        data = ''
-        try:
-            result = opener.open(req)
-        except urllib.error.HTTPError as e:
-            if self.show_response:
-                data = e.fp.read()
-            result = e.code, e.msg
-        except urllib.error.URLError as e:
-            result = 500, str(e)
-        else:
-            if self.show_response:
-                data = self._read_pypi_response(result)
-            result = 200, 'OK'
-        if self.show_response:
-            msg = '\n'.join(('-' * 75, data, '-' * 75))
-            self.announce(msg, logging.INFO)
-        return result
diff --git a/setuptools/_distutils/command/sdist.py b/setuptools/_distutils/command/sdist.py
index ac489726ca..e64cc82902 100644
--- a/setuptools/_distutils/command/sdist.py
+++ b/setuptools/_distutils/command/sdist.py
@@ -2,40 +2,42 @@
 
 Implements the Distutils 'sdist' command (create a source distribution)."""
 
+from __future__ import annotations
+
 import os
 import sys
+from collections.abc import Callable
+from distutils import archive_util, dir_util, file_util
+from distutils._log import log
 from glob import glob
-from warnings import warn
+from itertools import filterfalse
+from typing import ClassVar
 
 from ..core import Command
-from distutils import dir_util
-from distutils import file_util
-from distutils import archive_util
-from ..text_file import TextFile
+from ..errors import DistutilsOptionError, DistutilsTemplateError
 from ..filelist import FileList
-from distutils._log import log
+from ..text_file import TextFile
 from ..util import convert_path
-from ..errors import DistutilsOptionError, DistutilsTemplateError
 
 
 def show_formats():
     """Print all possible values for the 'formats' option (used by
     the "--help-formats" command-line option).
     """
-    from ..fancy_getopt import FancyGetopt
     from ..archive_util import ARCHIVE_FORMATS
+    from ..fancy_getopt import FancyGetopt
 
-    formats = []
-    for format in ARCHIVE_FORMATS.keys():
-        formats.append(("formats=" + format, None, ARCHIVE_FORMATS[format][2]))
-    formats.sort()
+    formats = sorted(
+        ("formats=" + format, None, ARCHIVE_FORMATS[format][2])
+        for format in ARCHIVE_FORMATS.keys()
+    )
     FancyGetopt(formats).print_help("List of available source distribution formats:")
 
 
 class sdist(Command):
     description = "create a source distribution (tarball, zip file, etc.)"
 
-    def checking_metadata(self):
+    def checking_metadata(self) -> bool:
         """Callable used for the check sub-command.
 
         Placed here so user_options can view it"""
@@ -62,7 +64,7 @@ def checking_metadata(self):
         (
             'manifest-only',
             'o',
-            "just regenerate the manifest and then stop " "(implies --force-manifest)",
+            "just regenerate the manifest and then stop (implies --force-manifest)",
         ),
         (
             'force-manifest',
@@ -79,7 +81,7 @@ def checking_metadata(self):
         (
             'dist-dir=',
             'd',
-            "directory to put the source distribution archive(s) in " "[default: dist]",
+            "directory to put the source distribution archive(s) in [default: dist]",
         ),
         (
             'metadata-check',
@@ -99,7 +101,7 @@ def checking_metadata(self):
         ),
     ]
 
-    boolean_options = [
+    boolean_options: ClassVar[list[str]] = [
         'use-defaults',
         'prune',
         'manifest-only',
@@ -108,15 +110,18 @@ def checking_metadata(self):
         'metadata-check',
     ]
 
-    help_options = [
+    help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [
         ('help-formats', None, "list available distribution formats", show_formats),
     ]
 
-    negative_opt = {'no-defaults': 'use-defaults', 'no-prune': 'prune'}
+    negative_opt: ClassVar[dict[str, str]] = {
+        'no-defaults': 'use-defaults',
+        'no-prune': 'prune',
+    }
 
     sub_commands = [('check', checking_metadata)]
 
-    READMES = ('README', 'README.txt', 'README.rst')
+    READMES: ClassVar[tuple[str, ...]] = ('README', 'README.txt', 'README.rst')
 
     def initialize_options(self):
         # 'template' and 'manifest' are, respectively, the names of
@@ -126,22 +131,22 @@ def initialize_options(self):
 
         # 'use_defaults': if true, we will include the default file set
         # in the manifest
-        self.use_defaults = 1
-        self.prune = 1
+        self.use_defaults = True
+        self.prune = True
 
-        self.manifest_only = 0
-        self.force_manifest = 0
+        self.manifest_only = False
+        self.force_manifest = False
 
         self.formats = ['gztar']
-        self.keep_temp = 0
+        self.keep_temp = False
         self.dist_dir = None
 
         self.archive_files = None
-        self.metadata_check = 1
+        self.metadata_check = True
         self.owner = None
         self.group = None
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         if self.manifest is None:
             self.manifest = "MANIFEST"
         if self.template is None:
@@ -151,12 +156,12 @@ def finalize_options(self):
 
         bad_format = archive_util.check_archive_formats(self.formats)
         if bad_format:
-            raise DistutilsOptionError("unknown archive format '%s'" % bad_format)
+            raise DistutilsOptionError(f"unknown archive format '{bad_format}'")
 
         if self.dist_dir is None:
             self.dist_dir = "dist"
 
-    def run(self):
+    def run(self) -> None:
         # 'filelist' contains the list of files that will make up the
         # manifest
         self.filelist = FileList()
@@ -178,18 +183,7 @@ def run(self):
         # or zipfile, or whatever.
         self.make_distribution()
 
-    def check_metadata(self):
-        """Deprecated API."""
-        warn(
-            "distutils.command.sdist.check_metadata is deprecated, \
-              use the check command instead",
-            PendingDeprecationWarning,
-        )
-        check = self.distribution.get_command_obj('check')
-        check.ensure_finalized()
-        check.run()
-
-    def get_file_list(self):
+    def get_file_list(self) -> None:
         """Figure out the list of files to include in the source
         distribution, and put it in 'self.filelist'.  This might involve
         reading the manifest template (and writing the manifest), or just
@@ -230,7 +224,7 @@ def get_file_list(self):
         self.filelist.remove_duplicates()
         self.write_manifest()
 
-    def add_defaults(self):
+    def add_defaults(self) -> None:
         """Add all the default files to self.filelist:
           - README or README.txt
           - setup.py
@@ -289,7 +283,7 @@ def _add_defaults_standards(self):
                 if self._cs_path_exists(fn):
                     self.filelist.append(fn)
                 else:
-                    self.warn("standard file '%s' not found" % fn)
+                    self.warn(f"standard file '{fn}' not found")
 
     def _add_defaults_optional(self):
         optional = ['tests/test*.py', 'test/test*.py', 'setup.cfg']
@@ -309,7 +303,7 @@ def _add_defaults_python(self):
 
         # getting package_data files
         # (computed in build_py.data_files by build_py.finalize_options)
-        for pkg, src_dir, build_dir, filenames in build_py.data_files:
+        for _pkg, src_dir, _build_dir, filenames in build_py.data_files:
             for filename in filenames:
                 self.filelist.append(os.path.join(src_dir, filename))
 
@@ -345,7 +339,7 @@ def _add_defaults_scripts(self):
             build_scripts = self.get_finalized_command('build_scripts')
             self.filelist.extend(build_scripts.get_source_files())
 
-    def read_template(self):
+    def read_template(self) -> None:
         """Read and parse manifest template file named by self.template.
 
         (usually "MANIFEST.in") The parsing and processing is done by
@@ -354,12 +348,12 @@ def read_template(self):
         log.info("reading manifest template '%s'", self.template)
         template = TextFile(
             self.template,
-            strip_comments=1,
-            skip_blanks=1,
-            join_lines=1,
-            lstrip_ws=1,
-            rstrip_ws=1,
-            collapse_join=1,
+            strip_comments=True,
+            skip_blanks=True,
+            join_lines=True,
+            lstrip_ws=True,
+            rstrip_ws=True,
+            collapse_join=True,
         )
 
         try:
@@ -375,13 +369,12 @@ def read_template(self):
                 # convert_path function
                 except (DistutilsTemplateError, ValueError) as msg:
                     self.warn(
-                        "%s, line %d: %s"
-                        % (template.filename, template.current_line, msg)
+                        f"{template.filename}, line {int(template.current_line)}: {msg}"
                     )
         finally:
             template.close()
 
-    def prune_file_list(self):
+    def prune_file_list(self) -> None:
         """Prune off branches that might slip into the file list as created
         by 'read_template()', but really don't belong there:
           * the build tree (typically "build")
@@ -392,7 +385,7 @@ def prune_file_list(self):
         build = self.get_finalized_command('build')
         base_dir = self.distribution.get_fullname()
 
-        self.filelist.exclude_pattern(None, prefix=build.build_base)
+        self.filelist.exclude_pattern(None, prefix=os.fspath(build.build_base))
         self.filelist.exclude_pattern(None, prefix=base_dir)
 
         if sys.platform == 'win32':
@@ -402,17 +395,16 @@ def prune_file_list(self):
 
         vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr', '_darcs']
         vcs_ptrn = r'(^|{})({})({}).*'.format(seps, '|'.join(vcs_dirs), seps)
-        self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)
+        self.filelist.exclude_pattern(vcs_ptrn, is_regex=True)
 
-    def write_manifest(self):
+    def write_manifest(self) -> None:
         """Write the file list in 'self.filelist' (presumably as filled in
         by 'add_defaults()' and 'read_template()') to the manifest file
         named by 'self.manifest'.
         """
         if self._manifest_is_not_generated():
             log.info(
-                "not writing to manually maintained "
-                "manifest file '%s'" % self.manifest
+                f"not writing to manually maintained manifest file '{self.manifest}'"
             )
             return
 
@@ -421,7 +413,7 @@ def write_manifest(self):
         self.execute(
             file_util.write_file,
             (self.manifest, content),
-            "writing manifest file '%s'" % self.manifest,
+            f"writing manifest file '{self.manifest}'",
         )
 
     def _manifest_is_not_generated(self):
@@ -429,28 +421,23 @@ def _manifest_is_not_generated(self):
         if not os.path.isfile(self.manifest):
             return False
 
-        fp = open(self.manifest)
-        try:
-            first_line = fp.readline()
-        finally:
-            fp.close()
+        with open(self.manifest, encoding='utf-8') as fp:
+            first_line = next(fp)
         return first_line != '# file GENERATED by distutils, do NOT edit\n'
 
-    def read_manifest(self):
+    def read_manifest(self) -> None:
         """Read the manifest file (named by 'self.manifest') and use it to
         fill in 'self.filelist', the list of files to include in the source
         distribution.
         """
         log.info("reading manifest file '%s'", self.manifest)
-        with open(self.manifest) as manifest:
-            for line in manifest:
+        with open(self.manifest, encoding='utf-8') as lines:
+            self.filelist.extend(
                 # ignore comments and blank lines
-                line = line.strip()
-                if line.startswith('#') or not line:
-                    continue
-                self.filelist.append(line)
+                filter(None, filterfalse(is_comment, map(str.strip, lines)))
+            )
 
-    def make_release_tree(self, base_dir, files):
+    def make_release_tree(self, base_dir, files) -> None:
         """Create the directory tree that will become the source
         distribution archive.  All directories implied by the filenames in
         'files' are created under 'base_dir', and then we hard link or copy
@@ -463,7 +450,7 @@ def make_release_tree(self, base_dir, files):
         # put 'files' there; the 'mkpath()' is just so we don't die
         # if the manifest happens to be empty.
         self.mkpath(base_dir)
-        dir_util.create_tree(base_dir, files, dry_run=self.dry_run)
+        dir_util.create_tree(base_dir, files)
 
         # And walk over the list of files, either making a hard link (if
         # os.link exists) to each one that doesn't already exist in its
@@ -474,10 +461,10 @@ def make_release_tree(self, base_dir, files):
 
         if hasattr(os, 'link'):  # can make hard links on this system
             link = 'hard'
-            msg = "making hard links in %s..." % base_dir
+            msg = f"making hard links in {base_dir}..."
         else:  # nope, have to copy
             link = None
-            msg = "copying files to %s..." % base_dir
+            msg = f"copying files to {base_dir}..."
 
         if not files:
             log.warning("no files to distribute -- empty manifest?")
@@ -492,7 +479,7 @@ def make_release_tree(self, base_dir, files):
 
         self.distribution.metadata.write_pkg_info(base_dir)
 
-    def make_distribution(self):
+    def make_distribution(self) -> None:
         """Create the source distribution(s).  First, we create the release
         tree with 'make_release_tree()'; then, we create all required
         archive files (according to 'self.formats') from the release tree.
@@ -521,10 +508,14 @@ def make_distribution(self):
         self.archive_files = archive_files
 
         if not self.keep_temp:
-            dir_util.remove_tree(base_dir, dry_run=self.dry_run)
+            dir_util.remove_tree(base_dir)
 
     def get_archive_files(self):
         """Return the list of archive files created when the command
         was run, or None if the command hasn't run yet.
         """
         return self.archive_files
+
+
+def is_comment(line: str) -> bool:
+    return line.startswith('#')
diff --git a/setuptools/_distutils/command/upload.py b/setuptools/_distutils/command/upload.py
deleted file mode 100644
index caf15f04a6..0000000000
--- a/setuptools/_distutils/command/upload.py
+++ /dev/null
@@ -1,206 +0,0 @@
-"""
-distutils.command.upload
-
-Implements the Distutils 'upload' subcommand (upload package to a package
-index).
-"""
-
-import os
-import io
-import hashlib
-import logging
-from base64 import standard_b64encode
-from urllib.request import urlopen, Request, HTTPError
-from urllib.parse import urlparse
-from ..errors import DistutilsError, DistutilsOptionError
-from ..core import PyPIRCCommand
-from ..spawn import spawn
-
-
-# PyPI Warehouse supports MD5, SHA256, and Blake2 (blake2-256)
-# https://bugs.python.org/issue40698
-_FILE_CONTENT_DIGESTS = {
-    "md5_digest": getattr(hashlib, "md5", None),
-    "sha256_digest": getattr(hashlib, "sha256", None),
-    "blake2_256_digest": getattr(hashlib, "blake2b", None),
-}
-
-
-class upload(PyPIRCCommand):
-    description = "upload binary package to PyPI"
-
-    user_options = PyPIRCCommand.user_options + [
-        ('sign', 's', 'sign files to upload using gpg'),
-        ('identity=', 'i', 'GPG identity used to sign files'),
-    ]
-
-    boolean_options = PyPIRCCommand.boolean_options + ['sign']
-
-    def initialize_options(self):
-        PyPIRCCommand.initialize_options(self)
-        self.username = ''
-        self.password = ''
-        self.show_response = 0
-        self.sign = False
-        self.identity = None
-
-    def finalize_options(self):
-        PyPIRCCommand.finalize_options(self)
-        if self.identity and not self.sign:
-            raise DistutilsOptionError("Must use --sign for --identity to have meaning")
-        config = self._read_pypirc()
-        if config != {}:
-            self.username = config['username']
-            self.password = config['password']
-            self.repository = config['repository']
-            self.realm = config['realm']
-
-        # getting the password from the distribution
-        # if previously set by the register command
-        if not self.password and self.distribution.password:
-            self.password = self.distribution.password
-
-    def run(self):
-        if not self.distribution.dist_files:
-            msg = (
-                "Must create and upload files in one command "
-                "(e.g. setup.py sdist upload)"
-            )
-            raise DistutilsOptionError(msg)
-        for command, pyversion, filename in self.distribution.dist_files:
-            self.upload_file(command, pyversion, filename)
-
-    def upload_file(self, command, pyversion, filename):  # noqa: C901
-        # Makes sure the repository URL is compliant
-        schema, netloc, url, params, query, fragments = urlparse(self.repository)
-        if params or query or fragments:
-            raise AssertionError("Incompatible url %s" % self.repository)
-
-        if schema not in ('http', 'https'):
-            raise AssertionError("unsupported schema " + schema)
-
-        # Sign if requested
-        if self.sign:
-            gpg_args = ["gpg", "--detach-sign", "-a", filename]
-            if self.identity:
-                gpg_args[2:2] = ["--local-user", self.identity]
-            spawn(gpg_args, dry_run=self.dry_run)
-
-        # Fill in the data - send all the meta-data in case we need to
-        # register a new release
-        f = open(filename, 'rb')
-        try:
-            content = f.read()
-        finally:
-            f.close()
-
-        meta = self.distribution.metadata
-        data = {
-            # action
-            ':action': 'file_upload',
-            'protocol_version': '1',
-            # identify release
-            'name': meta.get_name(),
-            'version': meta.get_version(),
-            # file content
-            'content': (os.path.basename(filename), content),
-            'filetype': command,
-            'pyversion': pyversion,
-            # additional meta-data
-            'metadata_version': '1.0',
-            'summary': meta.get_description(),
-            'home_page': meta.get_url(),
-            'author': meta.get_contact(),
-            'author_email': meta.get_contact_email(),
-            'license': meta.get_licence(),
-            'description': meta.get_long_description(),
-            'keywords': meta.get_keywords(),
-            'platform': meta.get_platforms(),
-            'classifiers': meta.get_classifiers(),
-            'download_url': meta.get_download_url(),
-            # PEP 314
-            'provides': meta.get_provides(),
-            'requires': meta.get_requires(),
-            'obsoletes': meta.get_obsoletes(),
-        }
-
-        data['comment'] = ''
-
-        # file content digests
-        for digest_name, digest_cons in _FILE_CONTENT_DIGESTS.items():
-            if digest_cons is None:
-                continue
-            try:
-                data[digest_name] = digest_cons(content).hexdigest()
-            except ValueError:
-                # hash digest not available or blocked by security policy
-                pass
-
-        if self.sign:
-            with open(filename + ".asc", "rb") as f:
-                data['gpg_signature'] = (os.path.basename(filename) + ".asc", f.read())
-
-        # set up the authentication
-        user_pass = (self.username + ":" + self.password).encode('ascii')
-        # The exact encoding of the authentication string is debated.
-        # Anyway PyPI only accepts ascii for both username or password.
-        auth = "Basic " + standard_b64encode(user_pass).decode('ascii')
-
-        # Build up the MIME payload for the POST data
-        boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
-        sep_boundary = b'\r\n--' + boundary.encode('ascii')
-        end_boundary = sep_boundary + b'--\r\n'
-        body = io.BytesIO()
-        for key, value in data.items():
-            title = '\r\nContent-Disposition: form-data; name="%s"' % key
-            # handle multiple entries for the same name
-            if not isinstance(value, list):
-                value = [value]
-            for value in value:
-                if type(value) is tuple:
-                    title += '; filename="%s"' % value[0]
-                    value = value[1]
-                else:
-                    value = str(value).encode('utf-8')
-                body.write(sep_boundary)
-                body.write(title.encode('utf-8'))
-                body.write(b"\r\n\r\n")
-                body.write(value)
-        body.write(end_boundary)
-        body = body.getvalue()
-
-        msg = "Submitting {} to {}".format(filename, self.repository)
-        self.announce(msg, logging.INFO)
-
-        # build the Request
-        headers = {
-            'Content-type': 'multipart/form-data; boundary=%s' % boundary,
-            'Content-length': str(len(body)),
-            'Authorization': auth,
-        }
-
-        request = Request(self.repository, data=body, headers=headers)
-        # send the data
-        try:
-            result = urlopen(request)
-            status = result.getcode()
-            reason = result.msg
-        except HTTPError as e:
-            status = e.code
-            reason = e.msg
-        except OSError as e:
-            self.announce(str(e), logging.ERROR)
-            raise
-
-        if status == 200:
-            self.announce(
-                'Server response ({}): {}'.format(status, reason), logging.INFO
-            )
-            if self.show_response:
-                text = self._read_pypi_response(result)
-                msg = '\n'.join(('-' * 75, text, '-' * 75))
-                self.announce(msg, logging.INFO)
-        else:
-            msg = 'Upload failed ({}): {}'.format(status, reason)
-            self.announce(msg, logging.ERROR)
-            raise DistutilsError(msg)
diff --git a/setuptools/_distutils/command/wininst-10.0-amd64.exe b/setuptools/_distutils/command/wininst-10.0-amd64.exe
deleted file mode 100644
index 6fa0dce163..0000000000
Binary files a/setuptools/_distutils/command/wininst-10.0-amd64.exe and /dev/null differ
diff --git a/setuptools/_distutils/command/wininst-10.0.exe b/setuptools/_distutils/command/wininst-10.0.exe
deleted file mode 100644
index afc3bc6c14..0000000000
Binary files a/setuptools/_distutils/command/wininst-10.0.exe and /dev/null differ
diff --git a/setuptools/_distutils/command/wininst-14.0-amd64.exe b/setuptools/_distutils/command/wininst-14.0-amd64.exe
deleted file mode 100644
index 253c2e2ecc..0000000000
Binary files a/setuptools/_distutils/command/wininst-14.0-amd64.exe and /dev/null differ
diff --git a/setuptools/_distutils/command/wininst-14.0.exe b/setuptools/_distutils/command/wininst-14.0.exe
deleted file mode 100644
index 46f5f35667..0000000000
Binary files a/setuptools/_distutils/command/wininst-14.0.exe and /dev/null differ
diff --git a/setuptools/_distutils/command/wininst-6.0.exe b/setuptools/_distutils/command/wininst-6.0.exe
deleted file mode 100644
index f57c855a61..0000000000
Binary files a/setuptools/_distutils/command/wininst-6.0.exe and /dev/null differ
diff --git a/setuptools/_distutils/command/wininst-7.1.exe b/setuptools/_distutils/command/wininst-7.1.exe
deleted file mode 100644
index 1433bc1ad3..0000000000
Binary files a/setuptools/_distutils/command/wininst-7.1.exe and /dev/null differ
diff --git a/setuptools/_distutils/command/wininst-8.0.exe b/setuptools/_distutils/command/wininst-8.0.exe
deleted file mode 100644
index 7403bfabf5..0000000000
Binary files a/setuptools/_distutils/command/wininst-8.0.exe and /dev/null differ
diff --git a/setuptools/_distutils/command/wininst-9.0-amd64.exe b/setuptools/_distutils/command/wininst-9.0-amd64.exe
deleted file mode 100644
index 94fbd4341b..0000000000
Binary files a/setuptools/_distutils/command/wininst-9.0-amd64.exe and /dev/null differ
diff --git a/setuptools/_distutils/command/wininst-9.0.exe b/setuptools/_distutils/command/wininst-9.0.exe
deleted file mode 100644
index 2ec261f9fd..0000000000
Binary files a/setuptools/_distutils/command/wininst-9.0.exe and /dev/null differ
diff --git a/setuptools/_distutils/compat/__init__.py b/setuptools/_distutils/compat/__init__.py
new file mode 100644
index 0000000000..2c43729b09
--- /dev/null
+++ b/setuptools/_distutils/compat/__init__.py
@@ -0,0 +1,18 @@
+from __future__ import annotations
+
+from collections.abc import Iterable
+from typing import TypeVar
+
+_IterableT = TypeVar("_IterableT", bound="Iterable[str]")
+
+
+def consolidate_linker_args(args: _IterableT) -> _IterableT | str:
+    """
+    Ensure the return value is a string for backward compatibility.
+
+    Retain until at least 2025-04-31. See pypa/distutils#246
+    """
+
+    if not all(arg.startswith('-Wl,') for arg in args):
+        return args
+    return '-Wl,' + ','.join(arg.removeprefix('-Wl,') for arg in args)
diff --git a/setuptools/_distutils/compat/numpy.py b/setuptools/_distutils/compat/numpy.py
new file mode 100644
index 0000000000..73eca7acb1
--- /dev/null
+++ b/setuptools/_distutils/compat/numpy.py
@@ -0,0 +1,2 @@
+# required for older numpy versions on Pythons prior to 3.12; see pypa/setuptools#4876
+from ..compilers.C.base import _default_compilers, compiler_class  # noqa: F401
diff --git a/setuptools/_distutils/compat/py39.py b/setuptools/_distutils/compat/py39.py
new file mode 100644
index 0000000000..1b436d7658
--- /dev/null
+++ b/setuptools/_distutils/compat/py39.py
@@ -0,0 +1,66 @@
+import functools
+import itertools
+import platform
+import sys
+
+
+def add_ext_suffix_39(vars):
+    """
+    Ensure vars contains 'EXT_SUFFIX'. pypa/distutils#130
+    """
+    import _imp
+
+    ext_suffix = _imp.extension_suffixes()[0]
+    vars.update(
+        EXT_SUFFIX=ext_suffix,
+        # sysconfig sets SO to match EXT_SUFFIX, so maintain
+        # that expectation.
+        # https://github.com/python/cpython/blob/785cc6770588de087d09e89a69110af2542be208/Lib/sysconfig.py#L671-L673
+        SO=ext_suffix,
+    )
+
+
+needs_ext_suffix = sys.version_info < (3, 10) and platform.system() == 'Windows'
+add_ext_suffix = add_ext_suffix_39 if needs_ext_suffix else lambda vars: None
+
+
+# from more_itertools
+class UnequalIterablesError(ValueError):
+    def __init__(self, details=None):
+        msg = 'Iterables have different lengths'
+        if details is not None:
+            msg += (': index 0 has length {}; index {} has length {}').format(*details)
+
+        super().__init__(msg)
+
+
+# from more_itertools
+def _zip_equal_generator(iterables):
+    _marker = object()
+    for combo in itertools.zip_longest(*iterables, fillvalue=_marker):
+        for val in combo:
+            if val is _marker:
+                raise UnequalIterablesError()
+        yield combo
+
+
+# from more_itertools
+def _zip_equal(*iterables):
+    # Check whether the iterables are all the same size.
+    try:
+        first_size = len(iterables[0])
+        for i, it in enumerate(iterables[1:], 1):
+            size = len(it)
+            if size != first_size:
+                raise UnequalIterablesError(details=(first_size, i, size))
+        # All sizes are equal, we can use the built-in zip.
+        return zip(*iterables)
+    # If any one of the iterables didn't have a length, start reading
+    # them until one runs out.
+    except TypeError:
+        return _zip_equal_generator(iterables)
+
+
+zip_strict = (
+    _zip_equal if sys.version_info < (3, 10) else functools.partial(zip, strict=True)
+)
diff --git a/setuptools/_distutils/compilers/C/base.py b/setuptools/_distutils/compilers/C/base.py
new file mode 100644
index 0000000000..ea6b5458ef
--- /dev/null
+++ b/setuptools/_distutils/compilers/C/base.py
@@ -0,0 +1,1386 @@
+"""distutils.ccompiler
+
+Contains Compiler, an abstract base class that defines the interface
+for the Distutils compiler abstraction model."""
+
+from __future__ import annotations
+
+import os
+import pathlib
+import re
+import sys
+import warnings
+from collections.abc import Callable, Iterable, MutableSequence, Sequence
+from typing import (
+    TYPE_CHECKING,
+    ClassVar,
+    Literal,
+    TypeVar,
+    Union,
+    overload,
+)
+
+from more_itertools import always_iterable
+
+from ..._log import log
+from ..._modified import newer_group
+from ...dir_util import mkpath
+from ...errors import (
+    DistutilsModuleError,
+    DistutilsPlatformError,
+)
+from ...file_util import move_file
+from ...spawn import spawn
+from ...util import execute, is_mingw, split_quoted
+from .errors import (
+    CompileError,
+    LinkError,
+    UnknownFileType,
+)
+
+if TYPE_CHECKING:
+    from typing_extensions import TypeAlias, TypeVarTuple, Unpack
+
+    _Ts = TypeVarTuple("_Ts")
+
+_Macro: TypeAlias = Union[tuple[str], tuple[str, Union[str, None]]]
+_StrPathT = TypeVar("_StrPathT", bound="str | os.PathLike[str]")
+_BytesPathT = TypeVar("_BytesPathT", bound="bytes | os.PathLike[bytes]")
+
+
+class Compiler:
+    """Abstract base class to define the interface that must be implemented
+    by real compiler classes.  Also has some utility methods used by
+    several compiler classes.
+
+    The basic idea behind a compiler abstraction class is that each
+    instance can be used for all the compile/link steps in building a
+    single project.  Thus, attributes common to all of those compile and
+    link steps -- include directories, macros to define, libraries to link
+    against, etc. -- are attributes of the compiler instance.  To allow for
+    variability in how individual files are treated, most of those
+    attributes may be varied on a per-compilation or per-link basis.
+    """
+
+    # 'compiler_type' is a class attribute that identifies this class.  It
+    # keeps code that wants to know what kind of compiler it's dealing with
+    # from having to import all possible compiler classes just to do an
+    # 'isinstance'.  In concrete CCompiler subclasses, 'compiler_type'
+    # should really, really be one of the keys of the 'compiler_class'
+    # dictionary (see below -- used by the 'new_compiler()' factory
+    # function) -- authors of new compiler interface classes are
+    # responsible for updating 'compiler_class'!
+    compiler_type: ClassVar[str] = None  # type: ignore[assignment]
+
+    # XXX things not handled by this compiler abstraction model:
+    #   * client can't provide additional options for a compiler,
+    #     e.g. warning, optimization, debugging flags.  Perhaps this
+    #     should be the domain of concrete compiler abstraction classes
+    #     (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base
+    #     class should have methods for the common ones.
+    #   * can't completely override the include or library searchg
+    #     path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2".
+    #     I'm not sure how widely supported this is even by Unix
+    #     compilers, much less on other platforms.  And I'm even less
+    #     sure how useful it is; maybe for cross-compiling, but
+    #     support for that is a ways off.  (And anyways, cross
+    #     compilers probably have a dedicated binary with the
+    #     right paths compiled in.  I hope.)
+    #   * can't do really freaky things with the library list/library
+    #     dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against
+    #     different versions of libfoo.a in different locations.  I
+    #     think this is useless without the ability to null out the
+    #     library search path anyways.
+
+    executables: ClassVar[dict]
+
+    # Subclasses that rely on the standard filename generation methods
+    # implemented below should override these; see the comment near
+    # those methods ('object_filenames()' et. al.) for details:
+    src_extensions: ClassVar[list[str] | None] = None
+    obj_extension: ClassVar[str | None] = None
+    static_lib_extension: ClassVar[str | None] = None
+    shared_lib_extension: ClassVar[str | None] = None
+    static_lib_format: ClassVar[str | None] = None  # format string
+    shared_lib_format: ClassVar[str | None] = None  # prob. same as static_lib_format
+    exe_extension: ClassVar[str | None] = None
+
+    # Default language settings. language_map is used to detect a source
+    # file or Extension target language, checking source filenames.
+    # language_order is used to detect the language precedence, when deciding
+    # what language to use when mixing source types. For example, if some
+    # extension has two files with ".c" extension, and one with ".cpp", it
+    # is still linked as c++.
+    language_map: ClassVar[dict[str, str]] = {
+        ".c": "c",
+        ".cc": "c++",
+        ".cpp": "c++",
+        ".cxx": "c++",
+        ".m": "objc",
+    }
+    language_order: ClassVar[list[str]] = ["c++", "objc", "c"]
+
+    include_dirs: list[str] = []
+    """
+    include dirs specific to this compiler class
+    """
+
+    library_dirs: list[str] = []
+    """
+    library dirs specific to this compiler class
+    """
+
+    def __init__(self, verbose: bool = False, force: bool = False) -> None:
+        self.force = force
+        self.verbose = verbose
+
+        # 'output_dir': a common output directory for object, library,
+        # shared object, and shared library files
+        self.output_dir: str | None = None
+
+        # 'macros': a list of macro definitions (or undefinitions).  A
+        # macro definition is a 2-tuple (name, value), where the value is
+        # either a string or None (no explicit value).  A macro
+        # undefinition is a 1-tuple (name,).
+        self.macros: list[_Macro] = []
+
+        # 'include_dirs': a list of directories to search for include files
+        self.include_dirs = []
+
+        # 'libraries': a list of libraries to include in any link
+        # (library names, not filenames: eg. "foo" not "libfoo.a")
+        self.libraries: list[str] = []
+
+        # 'library_dirs': a list of directories to search for libraries
+        self.library_dirs = []
+
+        # 'runtime_library_dirs': a list of directories to search for
+        # shared libraries/objects at runtime
+        self.runtime_library_dirs: list[str] = []
+
+        # 'objects': a list of object files (or similar, such as explicitly
+        # named library files) to include on any link
+        self.objects: list[str] = []
+
+        for key in self.executables.keys():
+            self.set_executable(key, self.executables[key])
+
+    def set_executables(self, **kwargs: str) -> None:
+        """Define the executables (and options for them) that will be run
+        to perform the various stages of compilation.  The exact set of
+        executables that may be specified here depends on the compiler
+        class (via the 'executables' class attribute), but most will have:
+          compiler      the C/C++ compiler
+          linker_so     linker used to create shared objects and libraries
+          linker_exe    linker used to create binary executables
+          archiver      static library creator
+
+        On platforms with a command-line (Unix, DOS/Windows), each of these
+        is a string that will be split into executable name and (optional)
+        list of arguments.  (Splitting the string is done similarly to how
+        Unix shells operate: words are delimited by spaces, but quotes and
+        backslashes can override this.  See
+        'distutils.util.split_quoted()'.)
+        """
+
+        # Note that some CCompiler implementation classes will define class
+        # attributes 'cpp', 'cc', etc. with hard-coded executable names;
+        # this is appropriate when a compiler class is for exactly one
+        # compiler/OS combination (eg. MSVCCompiler).  Other compiler
+        # classes (UnixCCompiler, in particular) are driven by information
+        # discovered at run-time, since there are many different ways to do
+        # basically the same things with Unix C compilers.
+
+        for key in kwargs:
+            if key not in self.executables:
+                raise ValueError(
+                    f"unknown executable '{key}' for class {self.__class__.__name__}"
+                )
+            self.set_executable(key, kwargs[key])
+
+    def set_executable(self, key, value):
+        if isinstance(value, str):
+            setattr(self, key, split_quoted(value))
+        else:
+            setattr(self, key, value)
+
+    def _find_macro(self, name):
+        i = 0
+        for defn in self.macros:
+            if defn[0] == name:
+                return i
+            i += 1
+        return None
+
+    def _check_macro_definitions(self, definitions):
+        """Ensure that every element of 'definitions' is valid."""
+        for defn in definitions:
+            self._check_macro_definition(*defn)
+
+    def _check_macro_definition(self, defn):
+        """
+        Raise a TypeError if defn is not valid.
+
+        A valid definition is either a (name, value) 2-tuple or a (name,) tuple.
+        """
+        if not isinstance(defn, tuple) or not self._is_valid_macro(*defn):
+            raise TypeError(
+                f"invalid macro definition '{defn}': "
+                "must be tuple (string,), (string, string), or (string, None)"
+            )
+
+    @staticmethod
+    def _is_valid_macro(name, value=None):
+        """
+        A valid macro is a ``name : str`` and a ``value : str | None``.
+
+        >>> Compiler._is_valid_macro('foo', None)
+        True
+        """
+        return isinstance(name, str) and isinstance(value, (str, type(None)))
+
+    # -- Bookkeeping methods -------------------------------------------
+
+    def define_macro(self, name: str, value: str | None = None) -> None:
+        """Define a preprocessor macro for all compilations driven by this
+        compiler object.  The optional parameter 'value' should be a
+        string; if it is not supplied, then the macro will be defined
+        without an explicit value and the exact outcome depends on the
+        compiler used (XXX true? does ANSI say anything about this?)
+        """
+        # Delete from the list of macro definitions/undefinitions if
+        # already there (so that this one will take precedence).
+        i = self._find_macro(name)
+        if i is not None:
+            del self.macros[i]
+
+        self.macros.append((name, value))
+
+    def undefine_macro(self, name: str) -> None:
+        """Undefine a preprocessor macro for all compilations driven by
+        this compiler object.  If the same macro is defined by
+        'define_macro()' and undefined by 'undefine_macro()' the last call
+        takes precedence (including multiple redefinitions or
+        undefinitions).  If the macro is redefined/undefined on a
+        per-compilation basis (ie. in the call to 'compile()'), then that
+        takes precedence.
+        """
+        # Delete from the list of macro definitions/undefinitions if
+        # already there (so that this one will take precedence).
+        i = self._find_macro(name)
+        if i is not None:
+            del self.macros[i]
+
+        undefn = (name,)
+        self.macros.append(undefn)
+
+    def add_include_dir(self, dir: str) -> None:
+        """Add 'dir' to the list of directories that will be searched for
+        header files.  The compiler is instructed to search directories in
+        the order in which they are supplied by successive calls to
+        'add_include_dir()'.
+        """
+        self.include_dirs.append(dir)
+
+    def set_include_dirs(self, dirs: list[str]) -> None:
+        """Set the list of directories that will be searched to 'dirs' (a
+        list of strings).  Overrides any preceding calls to
+        'add_include_dir()'; subsequence calls to 'add_include_dir()' add
+        to the list passed to 'set_include_dirs()'.  This does not affect
+        any list of standard include directories that the compiler may
+        search by default.
+        """
+        self.include_dirs = dirs[:]
+
+    def add_library(self, libname: str) -> None:
+        """Add 'libname' to the list of libraries that will be included in
+        all links driven by this compiler object.  Note that 'libname'
+        should *not* be the name of a file containing a library, but the
+        name of the library itself: the actual filename will be inferred by
+        the linker, the compiler, or the compiler class (depending on the
+        platform).
+
+        The linker will be instructed to link against libraries in the
+        order they were supplied to 'add_library()' and/or
+        'set_libraries()'.  It is perfectly valid to duplicate library
+        names; the linker will be instructed to link against libraries as
+        many times as they are mentioned.
+        """
+        self.libraries.append(libname)
+
+    def set_libraries(self, libnames: list[str]) -> None:
+        """Set the list of libraries to be included in all links driven by
+        this compiler object to 'libnames' (a list of strings).  This does
+        not affect any standard system libraries that the linker may
+        include by default.
+        """
+        self.libraries = libnames[:]
+
+    def add_library_dir(self, dir: str) -> None:
+        """Add 'dir' to the list of directories that will be searched for
+        libraries specified to 'add_library()' and 'set_libraries()'.  The
+        linker will be instructed to search for libraries in the order they
+        are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.
+        """
+        self.library_dirs.append(dir)
+
+    def set_library_dirs(self, dirs: list[str]) -> None:
+        """Set the list of library search directories to 'dirs' (a list of
+        strings).  This does not affect any standard library search path
+        that the linker may search by default.
+        """
+        self.library_dirs = dirs[:]
+
+    def add_runtime_library_dir(self, dir: str) -> None:
+        """Add 'dir' to the list of directories that will be searched for
+        shared libraries at runtime.
+        """
+        self.runtime_library_dirs.append(dir)
+
+    def set_runtime_library_dirs(self, dirs: list[str]) -> None:
+        """Set the list of directories to search for shared libraries at
+        runtime to 'dirs' (a list of strings).  This does not affect any
+        standard search path that the runtime linker may search by
+        default.
+        """
+        self.runtime_library_dirs = dirs[:]
+
+    def add_link_object(self, object: str) -> None:
+        """Add 'object' to the list of object files (or analogues, such as
+        explicitly named library files or the output of "resource
+        compilers") to be included in every link driven by this compiler
+        object.
+        """
+        self.objects.append(object)
+
+    def set_link_objects(self, objects: list[str]) -> None:
+        """Set the list of object files (or analogues) to be included in
+        every link to 'objects'.  This does not affect any standard object
+        files that the linker may include by default (such as system
+        libraries).
+        """
+        self.objects = objects[:]
+
+    # -- Private utility methods --------------------------------------
+    # (here for the convenience of subclasses)
+
+    # Helper method to prep compiler in subclass compile() methods
+
+    def _setup_compile(
+        self,
+        outdir: str | None,
+        macros: list[_Macro] | None,
+        incdirs: list[str] | tuple[str, ...] | None,
+        sources,
+        depends,
+        extra,
+    ):
+        """Process arguments and decide which source files to compile."""
+        outdir, macros, incdirs = self._fix_compile_args(outdir, macros, incdirs)
+
+        if extra is None:
+            extra = []
+
+        # Get the list of expected output (object) files
+        objects = self.object_filenames(sources, strip_dir=False, output_dir=outdir)
+        assert len(objects) == len(sources)
+
+        pp_opts = gen_preprocess_options(macros, incdirs)
+
+        build = {}
+        for i in range(len(sources)):
+            src = sources[i]
+            obj = objects[i]
+            ext = os.path.splitext(src)[1]
+            self.mkpath(os.path.dirname(obj))
+            build[obj] = (src, ext)
+
+        return macros, objects, extra, pp_opts, build
+
+    def _get_cc_args(self, pp_opts, debug, before):
+        # works for unixccompiler, cygwinccompiler
+        cc_args = pp_opts + ['-c']
+        if debug:
+            cc_args[:0] = ['-g']
+        if before:
+            cc_args[:0] = before
+        return cc_args
+
+    def _fix_compile_args(
+        self,
+        output_dir: str | None,
+        macros: list[_Macro] | None,
+        include_dirs: list[str] | tuple[str, ...] | None,
+    ) -> tuple[str, list[_Macro], list[str]]:
+        """Typecheck and fix-up some of the arguments to the 'compile()'
+        method, and return fixed-up values.  Specifically: if 'output_dir'
+        is None, replaces it with 'self.output_dir'; ensures that 'macros'
+        is a list, and augments it with 'self.macros'; ensures that
+        'include_dirs' is a list, and augments it with 'self.include_dirs'.
+        Guarantees that the returned values are of the correct type,
+        i.e. for 'output_dir' either string or None, and for 'macros' and
+        'include_dirs' either list or None.
+        """
+        if output_dir is None:
+            output_dir = self.output_dir
+        elif not isinstance(output_dir, str):
+            raise TypeError("'output_dir' must be a string or None")
+
+        if macros is None:
+            macros = list(self.macros)
+        elif isinstance(macros, list):
+            macros = macros + (self.macros or [])
+        else:
+            raise TypeError("'macros' (if supplied) must be a list of tuples")
+
+        if include_dirs is None:
+            include_dirs = list(self.include_dirs)
+        elif isinstance(include_dirs, (list, tuple)):
+            include_dirs = list(include_dirs) + (self.include_dirs or [])
+        else:
+            raise TypeError("'include_dirs' (if supplied) must be a list of strings")
+
+        # add include dirs for class
+        include_dirs += self.__class__.include_dirs
+
+        return output_dir, macros, include_dirs
+
+    def _prep_compile(self, sources, output_dir, depends=None):
+        """Decide which source files must be recompiled.
+
+        Determine the list of object files corresponding to 'sources',
+        and figure out which ones really need to be recompiled.
+        Return a list of all object files and a dictionary telling
+        which source files can be skipped.
+        """
+        # Get the list of expected output (object) files
+        objects = self.object_filenames(sources, output_dir=output_dir)
+        assert len(objects) == len(sources)
+
+        # Return an empty dict for the "which source files can be skipped"
+        # return value to preserve API compatibility.
+        return objects, {}
+
+    def _fix_object_args(
+        self, objects: list[str] | tuple[str, ...], output_dir: str | None
+    ) -> tuple[list[str], str]:
+        """Typecheck and fix up some arguments supplied to various methods.
+        Specifically: ensure that 'objects' is a list; if output_dir is
+        None, replace with self.output_dir.  Return fixed versions of
+        'objects' and 'output_dir'.
+        """
+        if not isinstance(objects, (list, tuple)):
+            raise TypeError("'objects' must be a list or tuple of strings")
+        objects = list(objects)
+
+        if output_dir is None:
+            output_dir = self.output_dir
+        elif not isinstance(output_dir, str):
+            raise TypeError("'output_dir' must be a string or None")
+
+        return (objects, output_dir)
+
+    def _fix_lib_args(
+        self,
+        libraries: list[str] | tuple[str, ...] | None,
+        library_dirs: list[str] | tuple[str, ...] | None,
+        runtime_library_dirs: list[str] | tuple[str, ...] | None,
+    ) -> tuple[list[str], list[str], list[str]]:
+        """Typecheck and fix up some of the arguments supplied to the
+        'link_*' methods.  Specifically: ensure that all arguments are
+        lists, and augment them with their permanent versions
+        (eg. 'self.libraries' augments 'libraries').  Return a tuple with
+        fixed versions of all arguments.
+        """
+        if libraries is None:
+            libraries = list(self.libraries)
+        elif isinstance(libraries, (list, tuple)):
+            libraries = list(libraries) + (self.libraries or [])
+        else:
+            raise TypeError("'libraries' (if supplied) must be a list of strings")
+
+        if library_dirs is None:
+            library_dirs = list(self.library_dirs)
+        elif isinstance(library_dirs, (list, tuple)):
+            library_dirs = list(library_dirs) + (self.library_dirs or [])
+        else:
+            raise TypeError("'library_dirs' (if supplied) must be a list of strings")
+
+        # add library dirs for class
+        library_dirs += self.__class__.library_dirs
+
+        if runtime_library_dirs is None:
+            runtime_library_dirs = list(self.runtime_library_dirs)
+        elif isinstance(runtime_library_dirs, (list, tuple)):
+            runtime_library_dirs = list(runtime_library_dirs) + (
+                self.runtime_library_dirs or []
+            )
+        else:
+            raise TypeError(
+                "'runtime_library_dirs' (if supplied) must be a list of strings"
+            )
+
+        return (libraries, library_dirs, runtime_library_dirs)
+
+    def _need_link(self, objects, output_file):
+        """Return true if we need to relink the files listed in 'objects'
+        to recreate 'output_file'.
+        """
+        if self.force:
+            return True
+        newer = newer_group(objects, output_file)
+        return newer
+
+    def detect_language(self, sources: str | list[str]) -> str | None:
+        """Detect the language of a given file, or list of files. Uses
+        language_map, and language_order to do the job.
+        """
+        if not isinstance(sources, list):
+            sources = [sources]
+        lang = None
+        index = len(self.language_order)
+        for source in sources:
+            base, ext = os.path.splitext(source)
+            extlang = self.language_map.get(ext)
+            try:
+                extindex = self.language_order.index(extlang)
+                if extindex < index:
+                    lang = extlang
+                    index = extindex
+            except ValueError:
+                pass
+        return lang
+
+    # -- Worker methods ------------------------------------------------
+    # (must be implemented by subclasses)
+
+    def preprocess(
+        self,
+        source: str | os.PathLike[str],
+        output_file: str | os.PathLike[str] | None = None,
+        macros: list[_Macro] | None = None,
+        include_dirs: list[str] | tuple[str, ...] | None = None,
+        extra_preargs: list[str] | None = None,
+        extra_postargs: Iterable[str] | None = None,
+    ):
+        """Preprocess a single C/C++ source file, named in 'source'.
+        Output will be written to file named 'output_file', or stdout if
+        'output_file' not supplied.  'macros' is a list of macro
+        definitions as for 'compile()', which will augment the macros set
+        with 'define_macro()' and 'undefine_macro()'.  'include_dirs' is a
+        list of directory names that will be added to the default list.
+
+        Raises PreprocessError on failure.
+        """
+        pass
+
+    def compile(
+        self,
+        sources: Sequence[str | os.PathLike[str]],
+        output_dir: str | None = None,
+        macros: list[_Macro] | None = None,
+        include_dirs: list[str] | tuple[str, ...] | None = None,
+        debug: bool = False,
+        extra_preargs: list[str] | None = None,
+        extra_postargs: list[str] | None = None,
+        depends: list[str] | tuple[str, ...] | None = None,
+    ) -> list[str]:
+        """Compile one or more source files.
+
+        'sources' must be a list of filenames, most likely C/C++
+        files, but in reality anything that can be handled by a
+        particular compiler and compiler class (eg. MSVCCompiler can
+        handle resource files in 'sources').  Return a list of object
+        filenames, one per source filename in 'sources'.  Depending on
+        the implementation, not all source files will necessarily be
+        compiled, but all corresponding object filenames will be
+        returned.
+
+        If 'output_dir' is given, object files will be put under it, while
+        retaining their original path component.  That is, "foo/bar.c"
+        normally compiles to "foo/bar.o" (for a Unix implementation); if
+        'output_dir' is "build", then it would compile to
+        "build/foo/bar.o".
+
+        'macros', if given, must be a list of macro definitions.  A macro
+        definition is either a (name, value) 2-tuple or a (name,) 1-tuple.
+        The former defines a macro; if the value is None, the macro is
+        defined without an explicit value.  The 1-tuple case undefines a
+        macro.  Later definitions/redefinitions/ undefinitions take
+        precedence.
+
+        'include_dirs', if given, must be a list of strings, the
+        directories to add to the default include file search path for this
+        compilation only.
+
+        'debug' is a boolean; if true, the compiler will be instructed to
+        output debug symbols in (or alongside) the object file(s).
+
+        'extra_preargs' and 'extra_postargs' are implementation- dependent.
+        On platforms that have the notion of a command-line (e.g. Unix,
+        DOS/Windows), they are most likely lists of strings: extra
+        command-line arguments to prepend/append to the compiler command
+        line.  On other platforms, consult the implementation class
+        documentation.  In any event, they are intended as an escape hatch
+        for those occasions when the abstract compiler framework doesn't
+        cut the mustard.
+
+        'depends', if given, is a list of filenames that all targets
+        depend on.  If a source file is older than any file in
+        depends, then the source file will be recompiled.  This
+        supports dependency tracking, but only at a coarse
+        granularity.
+
+        Raises CompileError on failure.
+        """
+        # A concrete compiler class can either override this method
+        # entirely or implement _compile().
+        macros, objects, extra_postargs, pp_opts, build = self._setup_compile(
+            output_dir, macros, include_dirs, sources, depends, extra_postargs
+        )
+        cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
+
+        for obj in objects:
+            try:
+                src, ext = build[obj]
+            except KeyError:
+                continue
+            self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
+
+        # Return *all* object filenames, not just the ones we just built.
+        return objects
+
+    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
+        """Compile 'src' to product 'obj'."""
+        # A concrete compiler class that does not override compile()
+        # should implement _compile().
+        pass
+
+    def create_static_lib(
+        self,
+        objects: list[str] | tuple[str, ...],
+        output_libname: str,
+        output_dir: str | None = None,
+        debug: bool = False,
+        target_lang: str | None = None,
+    ) -> None:
+        """Link a bunch of stuff together to create a static library file.
+        The "bunch of stuff" consists of the list of object files supplied
+        as 'objects', the extra object files supplied to
+        'add_link_object()' and/or 'set_link_objects()', the libraries
+        supplied to 'add_library()' and/or 'set_libraries()', and the
+        libraries supplied as 'libraries' (if any).
+
+        'output_libname' should be a library name, not a filename; the
+        filename will be inferred from the library name.  'output_dir' is
+        the directory where the library file will be put.
+
+        'debug' is a boolean; if true, debugging information will be
+        included in the library (note that on most platforms, it is the
+        compile step where this matters: the 'debug' flag is included here
+        just for consistency).
+
+        'target_lang' is the target language for which the given objects
+        are being compiled. This allows specific linkage time treatment of
+        certain languages.
+
+        Raises LibError on failure.
+        """
+        pass
+
+    # values for target_desc parameter in link()
+    SHARED_OBJECT = "shared_object"
+    SHARED_LIBRARY = "shared_library"
+    EXECUTABLE = "executable"
+
+    def link(
+        self,
+        target_desc: str,
+        objects: list[str] | tuple[str, ...],
+        output_filename: str,
+        output_dir: str | None = None,
+        libraries: list[str] | tuple[str, ...] | None = None,
+        library_dirs: list[str] | tuple[str, ...] | None = None,
+        runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
+        export_symbols: Iterable[str] | None = None,
+        debug: bool = False,
+        extra_preargs: list[str] | None = None,
+        extra_postargs: list[str] | None = None,
+        build_temp: str | os.PathLike[str] | None = None,
+        target_lang: str | None = None,
+    ):
+        """Link a bunch of stuff together to create an executable or
+        shared library file.
+
+        The "bunch of stuff" consists of the list of object files supplied
+        as 'objects'.  'output_filename' should be a filename.  If
+        'output_dir' is supplied, 'output_filename' is relative to it
+        (i.e. 'output_filename' can provide directory components if
+        needed).
+
+        'libraries' is a list of libraries to link against.  These are
+        library names, not filenames, since they're translated into
+        filenames in a platform-specific way (eg. "foo" becomes "libfoo.a"
+        on Unix and "foo.lib" on DOS/Windows).  However, they can include a
+        directory component, which means the linker will look in that
+        specific directory rather than searching all the normal locations.
+
+        'library_dirs', if supplied, should be a list of directories to
+        search for libraries that were specified as bare library names
+        (ie. no directory component).  These are on top of the system
+        default and those supplied to 'add_library_dir()' and/or
+        'set_library_dirs()'.  'runtime_library_dirs' is a list of
+        directories that will be embedded into the shared library and used
+        to search for other shared libraries that *it* depends on at
+        run-time.  (This may only be relevant on Unix.)
+
+        'export_symbols' is a list of symbols that the shared library will
+        export.  (This appears to be relevant only on Windows.)
+
+        'debug' is as for 'compile()' and 'create_static_lib()', with the
+        slight distinction that it actually matters on most platforms (as
+        opposed to 'create_static_lib()', which includes a 'debug' flag
+        mostly for form's sake).
+
+        'extra_preargs' and 'extra_postargs' are as for 'compile()' (except
+        of course that they supply command-line arguments for the
+        particular linker being used).
+
+        'target_lang' is the target language for which the given objects
+        are being compiled. This allows specific linkage time treatment of
+        certain languages.
+
+        Raises LinkError on failure.
+        """
+        raise NotImplementedError
+
+    # Old 'link_*()' methods, rewritten to use the new 'link()' method.
+
+    def link_shared_lib(
+        self,
+        objects: list[str] | tuple[str, ...],
+        output_libname: str,
+        output_dir: str | None = None,
+        libraries: list[str] | tuple[str, ...] | None = None,
+        library_dirs: list[str] | tuple[str, ...] | None = None,
+        runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
+        export_symbols: Iterable[str] | None = None,
+        debug: bool = False,
+        extra_preargs: list[str] | None = None,
+        extra_postargs: list[str] | None = None,
+        build_temp: str | os.PathLike[str] | None = None,
+        target_lang: str | None = None,
+    ):
+        self.link(
+            Compiler.SHARED_LIBRARY,
+            objects,
+            self.library_filename(output_libname, lib_type='shared'),
+            output_dir,
+            libraries,
+            library_dirs,
+            runtime_library_dirs,
+            export_symbols,
+            debug,
+            extra_preargs,
+            extra_postargs,
+            build_temp,
+            target_lang,
+        )
+
+    def link_shared_object(
+        self,
+        objects: list[str] | tuple[str, ...],
+        output_filename: str,
+        output_dir: str | None = None,
+        libraries: list[str] | tuple[str, ...] | None = None,
+        library_dirs: list[str] | tuple[str, ...] | None = None,
+        runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
+        export_symbols: Iterable[str] | None = None,
+        debug: bool = False,
+        extra_preargs: list[str] | None = None,
+        extra_postargs: list[str] | None = None,
+        build_temp: str | os.PathLike[str] | None = None,
+        target_lang: str | None = None,
+    ):
+        self.link(
+            Compiler.SHARED_OBJECT,
+            objects,
+            output_filename,
+            output_dir,
+            libraries,
+            library_dirs,
+            runtime_library_dirs,
+            export_symbols,
+            debug,
+            extra_preargs,
+            extra_postargs,
+            build_temp,
+            target_lang,
+        )
+
+    def link_executable(
+        self,
+        objects: list[str] | tuple[str, ...],
+        output_progname: str,
+        output_dir: str | None = None,
+        libraries: list[str] | tuple[str, ...] | None = None,
+        library_dirs: list[str] | tuple[str, ...] | None = None,
+        runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
+        debug: bool = False,
+        extra_preargs: list[str] | None = None,
+        extra_postargs: list[str] | None = None,
+        target_lang: str | None = None,
+    ):
+        self.link(
+            Compiler.EXECUTABLE,
+            objects,
+            self.executable_filename(output_progname),
+            output_dir,
+            libraries,
+            library_dirs,
+            runtime_library_dirs,
+            None,
+            debug,
+            extra_preargs,
+            extra_postargs,
+            None,
+            target_lang,
+        )
+
+    # -- Miscellaneous methods -----------------------------------------
+    # These are all used by the 'gen_lib_options() function; there is
+    # no appropriate default implementation so subclasses should
+    # implement all of these.
+
+    def library_dir_option(self, dir: str) -> str:
+        """Return the compiler option to add 'dir' to the list of
+        directories searched for libraries.
+        """
+        raise NotImplementedError
+
+    def runtime_library_dir_option(self, dir: str) -> str:
+        """Return the compiler option to add 'dir' to the list of
+        directories searched for runtime libraries.
+        """
+        raise NotImplementedError
+
+    def library_option(self, lib: str) -> str:
+        """Return the compiler option to add 'lib' to the list of libraries
+        linked into the shared library or executable.
+        """
+        raise NotImplementedError
+
+    def has_function(  # noqa: C901
+        self,
+        funcname: str,
+        includes: Iterable[str] | None = None,
+        include_dirs: list[str] | tuple[str, ...] | None = None,
+        libraries: list[str] | None = None,
+        library_dirs: list[str] | tuple[str, ...] | None = None,
+    ) -> bool:
+        """Return a boolean indicating whether funcname is provided as
+        a symbol on the current platform.  The optional arguments can
+        be used to augment the compilation environment.
+
+        The libraries argument is a list of flags to be passed to the
+        linker to make additional symbol definitions available for
+        linking.
+
+        The includes and include_dirs arguments are deprecated.
+        Usually, supplying include files with function declarations
+        will cause function detection to fail even in cases where the
+        symbol is available for linking.
+
+        """
+        # this can't be included at module scope because it tries to
+        # import math which might not be available at that point - maybe
+        # the necessary logic should just be inlined?
+        import tempfile
+
+        if includes is None:
+            includes = []
+        else:
+            warnings.warn("includes is deprecated", DeprecationWarning)
+        if include_dirs is None:
+            include_dirs = []
+        else:
+            warnings.warn("include_dirs is deprecated", DeprecationWarning)
+        if libraries is None:
+            libraries = []
+        if library_dirs is None:
+            library_dirs = []
+        fd, fname = tempfile.mkstemp(".c", funcname, text=True)
+        with os.fdopen(fd, "w", encoding='utf-8') as f:
+            for incl in includes:
+                f.write(f"""#include "{incl}"\n""")
+            if not includes:
+                # Use "char func(void);" as the prototype to follow
+                # what autoconf does.  This prototype does not match
+                # any well-known function the compiler might recognize
+                # as a builtin, so this ends up as a true link test.
+                # Without a fake prototype, the test would need to
+                # know the exact argument types, and the has_function
+                # interface does not provide that level of information.
+                f.write(
+                    f"""\
+#ifdef __cplusplus
+extern "C"
+#endif
+char {funcname}(void);
+"""
+                )
+            f.write(
+                f"""\
+int main (int argc, char **argv) {{
+    {funcname}();
+    return 0;
+}}
+"""
+            )
+
+        try:
+            objects = self.compile([fname], include_dirs=include_dirs)
+        except CompileError:
+            return False
+        finally:
+            os.remove(fname)
+
+        try:
+            self.link_executable(
+                objects, "a.out", libraries=libraries, library_dirs=library_dirs
+            )
+        except (LinkError, TypeError):
+            return False
+        else:
+            os.remove(
+                self.executable_filename("a.out", output_dir=self.output_dir or '')
+            )
+        finally:
+            for fn in objects:
+                os.remove(fn)
+        return True
+
+    def find_library_file(
+        self, dirs: Iterable[str], lib: str, debug: bool = False
+    ) -> str | None:
+        """Search the specified list of directories for a static or shared
+        library file 'lib' and return the full path to that file.  If
+        'debug' true, look for a debugging version (if that makes sense on
+        the current platform).  Return None if 'lib' wasn't found in any of
+        the specified directories.
+        """
+        raise NotImplementedError
+
+    # -- Filename generation methods -----------------------------------
+
+    # The default implementation of the filename generating methods are
+    # prejudiced towards the Unix/DOS/Windows view of the world:
+    #   * object files are named by replacing the source file extension
+    #     (eg. .c/.cpp -> .o/.obj)
+    #   * library files (shared or static) are named by plugging the
+    #     library name and extension into a format string, eg.
+    #     "lib%s.%s" % (lib_name, ".a") for Unix static libraries
+    #   * executables are named by appending an extension (possibly
+    #     empty) to the program name: eg. progname + ".exe" for
+    #     Windows
+    #
+    # To reduce redundant code, these methods expect to find
+    # several attributes in the current object (presumably defined
+    # as class attributes):
+    #   * src_extensions -
+    #     list of C/C++ source file extensions, eg. ['.c', '.cpp']
+    #   * obj_extension -
+    #     object file extension, eg. '.o' or '.obj'
+    #   * static_lib_extension -
+    #     extension for static library files, eg. '.a' or '.lib'
+    #   * shared_lib_extension -
+    #     extension for shared library/object files, eg. '.so', '.dll'
+    #   * static_lib_format -
+    #     format string for generating static library filenames,
+    #     eg. 'lib%s.%s' or '%s.%s'
+    #   * shared_lib_format
+    #     format string for generating shared library filenames
+    #     (probably same as static_lib_format, since the extension
+    #     is one of the intended parameters to the format string)
+    #   * exe_extension -
+    #     extension for executable files, eg. '' or '.exe'
+
+    def object_filenames(
+        self,
+        source_filenames: Iterable[str | os.PathLike[str]],
+        strip_dir: bool = False,
+        output_dir: str | os.PathLike[str] | None = '',
+    ) -> list[str]:
+        if output_dir is None:
+            output_dir = ''
+        return list(
+            self._make_out_path(output_dir, strip_dir, src_name)
+            for src_name in source_filenames
+        )
+
+    @property
+    def out_extensions(self):
+        return dict.fromkeys(self.src_extensions, self.obj_extension)
+
+    def _make_out_path(self, output_dir, strip_dir, src_name):
+        return self._make_out_path_exts(
+            output_dir, strip_dir, src_name, self.out_extensions
+        )
+
+    @classmethod
+    def _make_out_path_exts(cls, output_dir, strip_dir, src_name, extensions):
+        r"""
+        >>> exts = {'.c': '.o'}
+        >>> Compiler._make_out_path_exts('.', False, '/foo/bar.c', exts).replace('\\', '/')
+        './foo/bar.o'
+        >>> Compiler._make_out_path_exts('.', True, '/foo/bar.c', exts).replace('\\', '/')
+        './bar.o'
+        """
+        src = pathlib.PurePath(src_name)
+        # Ensure base is relative to honor output_dir (python/cpython#37775).
+        base = cls._make_relative(src)
+        try:
+            new_ext = extensions[src.suffix]
+        except LookupError:
+            raise UnknownFileType(f"unknown file type '{src.suffix}' (from '{src}')")
+        if strip_dir:
+            base = pathlib.PurePath(base.name)
+        return os.path.join(output_dir, base.with_suffix(new_ext))
+
+    @staticmethod
+    def _make_relative(base: pathlib.Path):
+        return base.relative_to(base.anchor)
+
+    @overload
+    def shared_object_filename(
+        self,
+        basename: str,
+        strip_dir: Literal[False] = False,
+        output_dir: str | os.PathLike[str] = "",
+    ) -> str: ...
+    @overload
+    def shared_object_filename(
+        self,
+        basename: str | os.PathLike[str],
+        strip_dir: Literal[True],
+        output_dir: str | os.PathLike[str] = "",
+    ) -> str: ...
+    def shared_object_filename(
+        self,
+        basename: str | os.PathLike[str],
+        strip_dir: bool = False,
+        output_dir: str | os.PathLike[str] = '',
+    ) -> str:
+        assert output_dir is not None
+        if strip_dir:
+            basename = os.path.basename(basename)
+        return os.path.join(output_dir, basename + self.shared_lib_extension)
+
+    @overload
+    def executable_filename(
+        self,
+        basename: str,
+        strip_dir: Literal[False] = False,
+        output_dir: str | os.PathLike[str] = "",
+    ) -> str: ...
+    @overload
+    def executable_filename(
+        self,
+        basename: str | os.PathLike[str],
+        strip_dir: Literal[True],
+        output_dir: str | os.PathLike[str] = "",
+    ) -> str: ...
+    def executable_filename(
+        self,
+        basename: str | os.PathLike[str],
+        strip_dir: bool = False,
+        output_dir: str | os.PathLike[str] = '',
+    ) -> str:
+        assert output_dir is not None
+        if strip_dir:
+            basename = os.path.basename(basename)
+        return os.path.join(output_dir, basename + (self.exe_extension or ''))
+
+    def library_filename(
+        self,
+        libname: str,
+        lib_type: str = "static",
+        strip_dir: bool = False,
+        output_dir: str | os.PathLike[str] = "",  # or 'shared'
+    ):
+        assert output_dir is not None
+        expected = '"static", "shared", "dylib", "xcode_stub"'
+        if lib_type not in eval(expected):
+            raise ValueError(f"'lib_type' must be {expected}")
+        fmt = getattr(self, lib_type + "_lib_format")
+        ext = getattr(self, lib_type + "_lib_extension")
+
+        dir, base = os.path.split(libname)
+        filename = fmt % (base, ext)
+        if strip_dir:
+            dir = ''
+
+        return os.path.join(output_dir, dir, filename)
+
+    # -- Utility methods -----------------------------------------------
+
+    def announce(self, msg: object, level: int = 1) -> None:
+        log.debug(msg)
+
+    def debug_print(self, msg: object) -> None:
+        from distutils.debug import DEBUG
+
+        if DEBUG:
+            print(msg)
+
+    def warn(self, msg: object) -> None:
+        sys.stderr.write(f"warning: {msg}\n")
+
+    def execute(
+        self,
+        func: Callable[[Unpack[_Ts]], object],
+        args: tuple[Unpack[_Ts]],
+        msg: object = None,
+        level: int = 1,
+    ) -> None:
+        execute(func, args, msg)
+
+    def spawn(
+        self, cmd: MutableSequence[bytes | str | os.PathLike[str]], **kwargs
+    ) -> None:
+        spawn(cmd, **kwargs)
+
+    @overload
+    def move_file(
+        self, src: str | os.PathLike[str], dst: _StrPathT
+    ) -> _StrPathT | str: ...
+    @overload
+    def move_file(
+        self, src: bytes | os.PathLike[bytes], dst: _BytesPathT
+    ) -> _BytesPathT | bytes: ...
+    def move_file(
+        self,
+        src: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+        dst: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+    ) -> str | os.PathLike[str] | bytes | os.PathLike[bytes]:
+        return move_file(src, dst)
+
+    def mkpath(self, name, mode=0o777):
+        mkpath(name, mode)
+
+
+# Map a sys.platform/os.name ('posix', 'nt') to the default compiler
+# type for that platform. Keys are interpreted as re match
+# patterns. Order is important; platform mappings are preferred over
+# OS names.
+_default_compilers = (
+    # Platform string mappings
+    # on a cygwin built python we can use gcc like an ordinary UNIXish
+    # compiler
+    ('cygwin.*', 'unix'),
+    ('zos', 'zos'),
+    # OS name mappings
+    ('posix', 'unix'),
+    ('nt', 'msvc'),
+)
+
+
+def get_default_compiler(osname: str | None = None, platform: str | None = None) -> str:
+    """Determine the default compiler to use for the given platform.
+
+    osname should be one of the standard Python OS names (i.e. the
+    ones returned by os.name) and platform the common value
+    returned by sys.platform for the platform in question.
+
+    The default values are os.name and sys.platform in case the
+    parameters are not given.
+    """
+    if osname is None:
+        osname = os.name
+    if platform is None:
+        platform = sys.platform
+    # Mingw is a special case where sys.platform is 'win32' but we
+    # want to use the 'mingw32' compiler, so check it first
+    if is_mingw():
+        return 'mingw32'
+    for pattern, compiler in _default_compilers:
+        if (
+            re.match(pattern, platform) is not None
+            or re.match(pattern, osname) is not None
+        ):
+            return compiler
+    # Default to Unix compiler
+    return 'unix'
+
+
+# Map compiler types to (module_name, class_name) pairs -- ie. where to
+# find the code that implements an interface to this compiler.  (The module
+# is assumed to be in the 'distutils' package.)
+compiler_class = {
+    'unix': ('unixccompiler', 'UnixCCompiler', "standard UNIX-style compiler"),
+    'msvc': ('_msvccompiler', 'MSVCCompiler', "Microsoft Visual C++"),
+    'cygwin': (
+        'cygwinccompiler',
+        'CygwinCCompiler',
+        "Cygwin port of GNU C Compiler for Win32",
+    ),
+    'mingw32': (
+        'cygwinccompiler',
+        'Mingw32CCompiler',
+        "Mingw32 port of GNU C Compiler for Win32",
+    ),
+    'bcpp': ('bcppcompiler', 'BCPPCompiler', "Borland C++ Compiler"),
+    'zos': ('zosccompiler', 'zOSCCompiler', 'IBM XL C/C++ Compilers'),
+}
+
+
+def show_compilers() -> None:
+    """Print list of available compilers (used by the "--help-compiler"
+    options to "build", "build_ext", "build_clib").
+    """
+    # XXX this "knows" that the compiler option it's describing is
+    # "--compiler", which just happens to be the case for the three
+    # commands that use it.
+    from distutils.fancy_getopt import FancyGetopt
+
+    compilers = sorted(
+        ("compiler=" + compiler, None, compiler_class[compiler][2])
+        for compiler in compiler_class.keys()
+    )
+    pretty_printer = FancyGetopt(compilers)
+    pretty_printer.print_help("List of available compilers:")
+
+
+def new_compiler(
+    plat: str | None = None,
+    compiler: str | None = None,
+    verbose: bool = False,
+    force: bool = False,
+) -> Compiler:
+    """Generate an instance of some CCompiler subclass for the supplied
+    platform/compiler combination.  'plat' defaults to 'os.name'
+    (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler
+    for that platform.  Currently only 'posix' and 'nt' are supported, and
+    the default compilers are "traditional Unix interface" (UnixCCompiler
+    class) and Visual C++ (MSVCCompiler class).  Note that it's perfectly
+    possible to ask for a Unix compiler object under Windows, and a
+    Microsoft compiler object under Unix -- if you supply a value for
+    'compiler', 'plat' is ignored.
+    """
+    if plat is None:
+        plat = os.name
+
+    try:
+        if compiler is None:
+            compiler = get_default_compiler(plat)
+
+        (module_name, class_name, long_description) = compiler_class[compiler]
+    except KeyError:
+        msg = f"don't know how to compile C/C++ code on platform '{plat}'"
+        if compiler is not None:
+            msg = msg + f" with '{compiler}' compiler"
+        raise DistutilsPlatformError(msg)
+
+    try:
+        module_name = "distutils." + module_name
+        __import__(module_name)
+        module = sys.modules[module_name]
+        klass = vars(module)[class_name]
+    except ImportError:
+        raise DistutilsModuleError(
+            f"can't compile C/C++ code: unable to load module '{module_name}'"
+        )
+    except KeyError:
+        raise DistutilsModuleError(
+            f"can't compile C/C++ code: unable to find class '{class_name}' "
+            f"in module '{module_name}'"
+        )
+
+    # XXX The None is necessary to preserve backwards compatibility
+    # with classes that expect verbose to be the first positional
+    # argument.
+    return klass(None, force=force)
+
+
+def gen_preprocess_options(
+    macros: Iterable[_Macro], include_dirs: Iterable[str]
+) -> list[str]:
+    """Generate C pre-processor options (-D, -U, -I) as used by at least
+    two types of compilers: the typical Unix compiler and Visual C++.
+    'macros' is the usual thing, a list of 1- or 2-tuples, where (name,)
+    means undefine (-U) macro 'name', and (name,value) means define (-D)
+    macro 'name' to 'value'.  'include_dirs' is just a list of directory
+    names to be added to the header file search path (-I).  Returns a list
+    of command-line options suitable for either Unix compilers or Visual
+    C++.
+    """
+    # XXX it would be nice (mainly aesthetic, and so we don't generate
+    # stupid-looking command lines) to go over 'macros' and eliminate
+    # redundant definitions/undefinitions (ie. ensure that only the
+    # latest mention of a particular macro winds up on the command
+    # line).  I don't think it's essential, though, since most (all?)
+    # Unix C compilers only pay attention to the latest -D or -U
+    # mention of a macro on their command line.  Similar situation for
+    # 'include_dirs'.  I'm punting on both for now.  Anyways, weeding out
+    # redundancies like this should probably be the province of
+    # CCompiler, since the data structures used are inherited from it
+    # and therefore common to all CCompiler classes.
+    pp_opts = []
+    for macro in macros:
+        if not (isinstance(macro, tuple) and 1 <= len(macro) <= 2):
+            raise TypeError(
+                f"bad macro definition '{macro}': "
+                "each element of 'macros' list must be a 1- or 2-tuple"
+            )
+
+        if len(macro) == 1:  # undefine this macro
+            pp_opts.append(f"-U{macro[0]}")
+        elif len(macro) == 2:
+            if macro[1] is None:  # define with no explicit value
+                pp_opts.append(f"-D{macro[0]}")
+            else:
+                # XXX *don't* need to be clever about quoting the
+                # macro value here, because we're going to avoid the
+                # shell at all costs when we spawn the command!
+                pp_opts.append("-D{}={}".format(*macro))
+
+    pp_opts.extend(f"-I{dir}" for dir in include_dirs)
+    return pp_opts
+
+
+def gen_lib_options(
+    compiler: Compiler,
+    library_dirs: Iterable[str],
+    runtime_library_dirs: Iterable[str],
+    libraries: Iterable[str],
+) -> list[str]:
+    """Generate linker options for searching library directories and
+    linking with specific libraries.  'libraries' and 'library_dirs' are,
+    respectively, lists of library names (not filenames!) and search
+    directories.  Returns a list of command-line options suitable for use
+    with some compiler (depending on the two format strings passed in).
+    """
+    lib_opts = [compiler.library_dir_option(dir) for dir in library_dirs]
+
+    for dir in runtime_library_dirs:
+        lib_opts.extend(always_iterable(compiler.runtime_library_dir_option(dir)))
+
+    # XXX it's important that we *not* remove redundant library mentions!
+    # sometimes you really do have to say "-lfoo -lbar -lfoo" in order to
+    # resolve all symbols.  I just hope we never have to say "-lfoo obj.o
+    # -lbar" to get things to work -- that's certainly a possibility, but a
+    # pretty nasty way to arrange your C code.
+
+    for lib in libraries:
+        (lib_dir, lib_name) = os.path.split(lib)
+        if lib_dir:
+            lib_file = compiler.find_library_file([lib_dir], lib_name)
+            if lib_file:
+                lib_opts.append(lib_file)
+            else:
+                compiler.warn(
+                    f"no library file corresponding to '{lib}' found (skipping)"
+                )
+        else:
+            lib_opts.append(compiler.library_option(lib))
+    return lib_opts
diff --git a/setuptools/_distutils/compilers/C/cygwin.py b/setuptools/_distutils/compilers/C/cygwin.py
new file mode 100644
index 0000000000..f349e9decd
--- /dev/null
+++ b/setuptools/_distutils/compilers/C/cygwin.py
@@ -0,0 +1,340 @@
+"""distutils.cygwinccompiler
+
+Provides the CygwinCCompiler class, a subclass of UnixCCompiler that
+handles the Cygwin port of the GNU C compiler to Windows.  It also contains
+the Mingw32CCompiler class which handles the mingw32 port of GCC (same as
+cygwin in no-cygwin mode).
+"""
+
+import copy
+import os
+import pathlib
+import shlex
+import sys
+import warnings
+from subprocess import check_output
+
+from ...errors import (
+    DistutilsExecError,
+    DistutilsPlatformError,
+)
+from ...file_util import write_file
+from ...sysconfig import get_config_vars
+from ...version import LooseVersion, suppress_known_deprecation
+from . import unix
+from .errors import (
+    CompileError,
+    Error,
+)
+
+
+def get_msvcr():
+    """No longer needed, but kept for backward compatibility."""
+    return []
+
+
+_runtime_library_dirs_msg = (
+    "Unable to set runtime library search path on Windows, "
+    "usually indicated by `runtime_library_dirs` parameter to Extension"
+)
+
+
+class Compiler(unix.Compiler):
+    """Handles the Cygwin port of the GNU C compiler to Windows."""
+
+    compiler_type = 'cygwin'
+    obj_extension = ".o"
+    static_lib_extension = ".a"
+    shared_lib_extension = ".dll.a"
+    dylib_lib_extension = ".dll"
+    static_lib_format = "lib%s%s"
+    shared_lib_format = "lib%s%s"
+    dylib_lib_format = "cyg%s%s"
+    exe_extension = ".exe"
+
+    def __init__(self, verbose=False, force=False):
+        super().__init__(verbose, force=force)
+
+        status, details = check_config_h()
+        self.debug_print(f"Python's GCC status: {status} (details: {details})")
+        if status is not CONFIG_H_OK:
+            self.warn(
+                "Python's pyconfig.h doesn't seem to support your compiler. "
+                f"Reason: {details}. "
+                "Compiling may fail because of undefined preprocessor macros."
+            )
+
+        self.cc, self.cxx = get_config_vars('CC', 'CXX')
+
+        # Override 'CC' and 'CXX' environment variables for
+        # building using MINGW compiler for MSVC python.
+        self.cc = os.environ.get('CC', self.cc or 'gcc')
+        self.cxx = os.environ.get('CXX', self.cxx or 'g++')
+
+        self.linker_dll = self.cc
+        self.linker_dll_cxx = self.cxx
+        shared_option = "-shared"
+
+        self.set_executables(
+            compiler=f'{self.cc} -mcygwin -O -Wall',
+            compiler_so=f'{self.cc} -mcygwin -mdll -O -Wall',
+            compiler_cxx=f'{self.cxx} -mcygwin -O -Wall',
+            compiler_so_cxx=f'{self.cxx} -mcygwin -mdll -O -Wall',
+            linker_exe=f'{self.cc} -mcygwin',
+            linker_so=f'{self.linker_dll} -mcygwin {shared_option}',
+            linker_exe_cxx=f'{self.cxx} -mcygwin',
+            linker_so_cxx=f'{self.linker_dll_cxx} -mcygwin {shared_option}',
+        )
+
+        self.dll_libraries = get_msvcr()
+
+    @property
+    def gcc_version(self):
+        # Older numpy depended on this existing to check for ancient
+        # gcc versions. This doesn't make much sense with clang etc so
+        # just hardcode to something recent.
+        # https://github.com/numpy/numpy/pull/20333
+        warnings.warn(
+            "gcc_version attribute of CygwinCCompiler is deprecated. "
+            "Instead of returning actual gcc version a fixed value 11.2.0 is returned.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        with suppress_known_deprecation():
+            return LooseVersion("11.2.0")
+
+    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
+        """Compiles the source by spawning GCC and windres if needed."""
+        if ext in ('.rc', '.res'):
+            # gcc needs '.res' and '.rc' compiled to object files !!!
+            try:
+                self.spawn(["windres", "-i", src, "-o", obj])
+            except DistutilsExecError as msg:
+                raise CompileError(msg)
+        else:  # for other files use the C-compiler
+            try:
+                if self.detect_language(src) == 'c++':
+                    self.spawn(
+                        self.compiler_so_cxx
+                        + cc_args
+                        + [src, '-o', obj]
+                        + extra_postargs
+                    )
+                else:
+                    self.spawn(
+                        self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs
+                    )
+            except DistutilsExecError as msg:
+                raise CompileError(msg)
+
+    def link(
+        self,
+        target_desc,
+        objects,
+        output_filename,
+        output_dir=None,
+        libraries=None,
+        library_dirs=None,
+        runtime_library_dirs=None,
+        export_symbols=None,
+        debug=False,
+        extra_preargs=None,
+        extra_postargs=None,
+        build_temp=None,
+        target_lang=None,
+    ):
+        """Link the objects."""
+        # use separate copies, so we can modify the lists
+        extra_preargs = copy.copy(extra_preargs or [])
+        libraries = copy.copy(libraries or [])
+        objects = copy.copy(objects or [])
+
+        if runtime_library_dirs:
+            self.warn(_runtime_library_dirs_msg)
+
+        # Additional libraries
+        libraries.extend(self.dll_libraries)
+
+        # handle export symbols by creating a def-file
+        # with executables this only works with gcc/ld as linker
+        if (export_symbols is not None) and (
+            target_desc != self.EXECUTABLE or self.linker_dll == "gcc"
+        ):
+            # (The linker doesn't do anything if output is up-to-date.
+            # So it would probably better to check if we really need this,
+            # but for this we had to insert some unchanged parts of
+            # UnixCCompiler, and this is not what we want.)
+
+            # we want to put some files in the same directory as the
+            # object files are, build_temp doesn't help much
+            # where are the object files
+            temp_dir = os.path.dirname(objects[0])
+            # name of dll to give the helper files the same base name
+            (dll_name, dll_extension) = os.path.splitext(
+                os.path.basename(output_filename)
+            )
+
+            # generate the filenames for these files
+            def_file = os.path.join(temp_dir, dll_name + ".def")
+
+            # Generate .def file
+            contents = [f"LIBRARY {os.path.basename(output_filename)}", "EXPORTS"]
+            contents.extend(export_symbols)
+            self.execute(write_file, (def_file, contents), f"writing {def_file}")
+
+            # next add options for def-file
+
+            # for gcc/ld the def-file is specified as any object files
+            objects.append(def_file)
+
+        # end: if ((export_symbols is not None) and
+        #        (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
+
+        # who wants symbols and a many times larger output file
+        # should explicitly switch the debug mode on
+        # otherwise we let ld strip the output file
+        # (On my machine: 10KiB < stripped_file < ??100KiB
+        #   unstripped_file = stripped_file + XXX KiB
+        #  ( XXX=254 for a typical python extension))
+        if not debug:
+            extra_preargs.append("-s")
+
+        super().link(
+            target_desc,
+            objects,
+            output_filename,
+            output_dir,
+            libraries,
+            library_dirs,
+            runtime_library_dirs,
+            None,  # export_symbols, we do this in our def-file
+            debug,
+            extra_preargs,
+            extra_postargs,
+            build_temp,
+            target_lang,
+        )
+
+    def runtime_library_dir_option(self, dir):
+        # cygwin doesn't support rpath. While in theory we could error
+        # out like MSVC does, code might expect it to work like on Unix, so
+        # just warn and hope for the best.
+        self.warn(_runtime_library_dirs_msg)
+        return []
+
+    # -- Miscellaneous methods -----------------------------------------
+
+    def _make_out_path(self, output_dir, strip_dir, src_name):
+        # use normcase to make sure '.rc' is really '.rc' and not '.RC'
+        norm_src_name = os.path.normcase(src_name)
+        return super()._make_out_path(output_dir, strip_dir, norm_src_name)
+
+    @property
+    def out_extensions(self):
+        """
+        Add support for rc and res files.
+        """
+        return {
+            **super().out_extensions,
+            **{ext: ext + self.obj_extension for ext in ('.res', '.rc')},
+        }
+
+
+# the same as cygwin plus some additional parameters
+class MinGW32Compiler(Compiler):
+    """Handles the Mingw32 port of the GNU C compiler to Windows."""
+
+    compiler_type = 'mingw32'
+
+    def __init__(self, verbose=False, force=False):
+        super().__init__(verbose, force)
+
+        shared_option = "-shared"
+
+        if is_cygwincc(self.cc):
+            raise Error('Cygwin gcc cannot be used with --compiler=mingw32')
+
+        self.set_executables(
+            compiler=f'{self.cc} -O -Wall',
+            compiler_so=f'{self.cc} -shared -O -Wall',
+            compiler_so_cxx=f'{self.cxx} -shared -O -Wall',
+            compiler_cxx=f'{self.cxx} -O -Wall',
+            linker_exe=f'{self.cc}',
+            linker_so=f'{self.linker_dll} {shared_option}',
+            linker_exe_cxx=f'{self.cxx}',
+            linker_so_cxx=f'{self.linker_dll_cxx} {shared_option}',
+        )
+
+    def runtime_library_dir_option(self, dir):
+        raise DistutilsPlatformError(_runtime_library_dirs_msg)
+
+
+# Because these compilers aren't configured in Python's pyconfig.h file by
+# default, we should at least warn the user if he is using an unmodified
+# version.
+
+CONFIG_H_OK = "ok"
+CONFIG_H_NOTOK = "not ok"
+CONFIG_H_UNCERTAIN = "uncertain"
+
+
+def check_config_h():
+    """Check if the current Python installation appears amenable to building
+    extensions with GCC.
+
+    Returns a tuple (status, details), where 'status' is one of the following
+    constants:
+
+    - CONFIG_H_OK: all is well, go ahead and compile
+    - CONFIG_H_NOTOK: doesn't look good
+    - CONFIG_H_UNCERTAIN: not sure -- unable to read pyconfig.h
+
+    'details' is a human-readable string explaining the situation.
+
+    Note there are two ways to conclude "OK": either 'sys.version' contains
+    the string "GCC" (implying that this Python was built with GCC), or the
+    installed "pyconfig.h" contains the string "__GNUC__".
+    """
+
+    # XXX since this function also checks sys.version, it's not strictly a
+    # "pyconfig.h" check -- should probably be renamed...
+
+    from distutils import sysconfig
+
+    # if sys.version contains GCC then python was compiled with GCC, and the
+    # pyconfig.h file should be OK
+    if "GCC" in sys.version:
+        return CONFIG_H_OK, "sys.version mentions 'GCC'"
+
+    # Clang would also work
+    if "Clang" in sys.version:
+        return CONFIG_H_OK, "sys.version mentions 'Clang'"
+
+    # let's see if __GNUC__ is mentioned in python.h
+    fn = sysconfig.get_config_h_filename()
+    try:
+        config_h = pathlib.Path(fn).read_text(encoding='utf-8')
+    except OSError as exc:
+        return (CONFIG_H_UNCERTAIN, f"couldn't read '{fn}': {exc.strerror}")
+    else:
+        substring = '__GNUC__'
+        if substring in config_h:
+            code = CONFIG_H_OK
+            mention_inflected = 'mentions'
+        else:
+            code = CONFIG_H_NOTOK
+            mention_inflected = 'does not mention'
+        return code, f"{fn!r} {mention_inflected} {substring!r}"
+
+
+def is_cygwincc(cc):
+    """Try to determine if the compiler that would be used is from cygwin."""
+    out_string = check_output(shlex.split(cc) + ['-dumpmachine'])
+    return out_string.strip().endswith(b'cygwin')
+
+
+get_versions = None
+"""
+A stand-in for the previous get_versions() function to prevent failures
+when monkeypatched. See pypa/setuptools#2969.
+"""
diff --git a/setuptools/_distutils/compilers/C/errors.py b/setuptools/_distutils/compilers/C/errors.py
new file mode 100644
index 0000000000..01328592b2
--- /dev/null
+++ b/setuptools/_distutils/compilers/C/errors.py
@@ -0,0 +1,24 @@
+class Error(Exception):
+    """Some compile/link operation failed."""
+
+
+class PreprocessError(Error):
+    """Failure to preprocess one or more C/C++ files."""
+
+
+class CompileError(Error):
+    """Failure to compile one or more C/C++ source files."""
+
+
+class LibError(Error):
+    """Failure to create a static library from one or more C/C++ object
+    files."""
+
+
+class LinkError(Error):
+    """Failure to link one or more C/C++ object files into an executable
+    or shared library file."""
+
+
+class UnknownFileType(Error):
+    """Attempt to process an unknown file type."""
diff --git a/setuptools/_distutils/compilers/C/msvc.py b/setuptools/_distutils/compilers/C/msvc.py
new file mode 100644
index 0000000000..1f50fa5088
--- /dev/null
+++ b/setuptools/_distutils/compilers/C/msvc.py
@@ -0,0 +1,614 @@
+"""distutils._msvccompiler
+
+Contains MSVCCompiler, an implementation of the abstract CCompiler class
+for Microsoft Visual Studio 2015.
+
+This module requires VS 2015 or later.
+"""
+
+# Written by Perry Stoll
+# hacked by Robin Becker and Thomas Heller to do a better job of
+#   finding DevStudio (through the registry)
+# ported to VS 2005 and VS 2008 by Christian Heimes
+# ported to VS 2015 by Steve Dower
+from __future__ import annotations
+
+import contextlib
+import os
+import subprocess
+import unittest.mock as mock
+import warnings
+from collections.abc import Iterable
+
+with contextlib.suppress(ImportError):
+    import winreg
+
+from itertools import count
+
+from ..._log import log
+from ...errors import (
+    DistutilsExecError,
+    DistutilsPlatformError,
+)
+from ...util import get_host_platform, get_platform
+from . import base
+from .base import gen_lib_options
+from .errors import (
+    CompileError,
+    LibError,
+    LinkError,
+)
+
+
+def _find_vc2015():
+    try:
+        key = winreg.OpenKeyEx(
+            winreg.HKEY_LOCAL_MACHINE,
+            r"Software\Microsoft\VisualStudio\SxS\VC7",
+            access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY,
+        )
+    except OSError:
+        log.debug("Visual C++ is not registered")
+        return None, None
+
+    best_version = 0
+    best_dir = None
+    with key:
+        for i in count():
+            try:
+                v, vc_dir, vt = winreg.EnumValue(key, i)
+            except OSError:
+                break
+            if v and vt == winreg.REG_SZ and os.path.isdir(vc_dir):
+                try:
+                    version = int(float(v))
+                except (ValueError, TypeError):
+                    continue
+                if version >= 14 and version > best_version:
+                    best_version, best_dir = version, vc_dir
+    return best_version, best_dir
+
+
+def _find_vc2017():
+    """Returns "15, path" based on the result of invoking vswhere.exe
+    If no install is found, returns "None, None"
+
+    The version is returned to avoid unnecessarily changing the function
+    result. It may be ignored when the path is not None.
+
+    If vswhere.exe is not available, by definition, VS 2017 is not
+    installed.
+    """
+    root = os.environ.get("ProgramFiles(x86)") or os.environ.get("ProgramFiles")
+    if not root:
+        return None, None
+
+    variant = 'arm64' if get_platform() == 'win-arm64' else 'x86.x64'
+    suitable_components = (
+        f"Microsoft.VisualStudio.Component.VC.Tools.{variant}",
+        "Microsoft.VisualStudio.Workload.WDExpress",
+    )
+
+    for component in suitable_components:
+        # Workaround for `-requiresAny` (only available on VS 2017 > 15.6)
+        with contextlib.suppress(
+            subprocess.CalledProcessError, OSError, UnicodeDecodeError
+        ):
+            path = (
+                subprocess.check_output([
+                    os.path.join(
+                        root, "Microsoft Visual Studio", "Installer", "vswhere.exe"
+                    ),
+                    "-latest",
+                    "-prerelease",
+                    "-requires",
+                    component,
+                    "-property",
+                    "installationPath",
+                    "-products",
+                    "*",
+                ])
+                .decode(encoding="mbcs", errors="strict")
+                .strip()
+            )
+
+            path = os.path.join(path, "VC", "Auxiliary", "Build")
+            if os.path.isdir(path):
+                return 15, path
+
+    return None, None  # no suitable component found
+
+
+PLAT_SPEC_TO_RUNTIME = {
+    'x86': 'x86',
+    'x86_amd64': 'x64',
+    'x86_arm': 'arm',
+    'x86_arm64': 'arm64',
+}
+
+
+def _find_vcvarsall(plat_spec):
+    # bpo-38597: Removed vcruntime return value
+    _, best_dir = _find_vc2017()
+
+    if not best_dir:
+        best_version, best_dir = _find_vc2015()
+
+    if not best_dir:
+        log.debug("No suitable Visual C++ version found")
+        return None, None
+
+    vcvarsall = os.path.join(best_dir, "vcvarsall.bat")
+    if not os.path.isfile(vcvarsall):
+        log.debug("%s cannot be found", vcvarsall)
+        return None, None
+
+    return vcvarsall, None
+
+
+def _get_vc_env(plat_spec):
+    if os.getenv("DISTUTILS_USE_SDK"):
+        return {key.lower(): value for key, value in os.environ.items()}
+
+    vcvarsall, _ = _find_vcvarsall(plat_spec)
+    if not vcvarsall:
+        raise DistutilsPlatformError(
+            'Microsoft Visual C++ 14.0 or greater is required. '
+            'Get it with "Microsoft C++ Build Tools": '
+            'https://visualstudio.microsoft.com/visual-cpp-build-tools/'
+        )
+
+    try:
+        out = subprocess.check_output(
+            f'cmd /u /c "{vcvarsall}" {plat_spec} && set',
+            stderr=subprocess.STDOUT,
+        ).decode('utf-16le', errors='replace')
+    except subprocess.CalledProcessError as exc:
+        log.error(exc.output)
+        raise DistutilsPlatformError(f"Error executing {exc.cmd}")
+
+    env = {
+        key.lower(): value
+        for key, _, value in (line.partition('=') for line in out.splitlines())
+        if key and value
+    }
+
+    return env
+
+
+def _find_exe(exe, paths=None):
+    """Return path to an MSVC executable program.
+
+    Tries to find the program in several places: first, one of the
+    MSVC program search paths from the registry; next, the directories
+    in the PATH environment variable.  If any of those work, return an
+    absolute path that is known to exist.  If none of them work, just
+    return the original program name, 'exe'.
+    """
+    if not paths:
+        paths = os.getenv('path').split(os.pathsep)
+    for p in paths:
+        fn = os.path.join(os.path.abspath(p), exe)
+        if os.path.isfile(fn):
+            return fn
+    return exe
+
+
+_vcvars_names = {
+    'win32': 'x86',
+    'win-amd64': 'amd64',
+    'win-arm32': 'arm',
+    'win-arm64': 'arm64',
+}
+
+
+def _get_vcvars_spec(host_platform, platform):
+    """
+    Given a host platform and platform, determine the spec for vcvarsall.
+
+    Uses the native MSVC host if the host platform would need expensive
+    emulation for x86.
+
+    >>> _get_vcvars_spec('win-arm64', 'win32')
+    'arm64_x86'
+    >>> _get_vcvars_spec('win-arm64', 'win-amd64')
+    'arm64_amd64'
+
+    Otherwise, always cross-compile from x86 to work with the
+    lighter-weight MSVC installs that do not include native 64-bit tools.
+
+    >>> _get_vcvars_spec('win32', 'win32')
+    'x86'
+    >>> _get_vcvars_spec('win-arm32', 'win-arm32')
+    'x86_arm'
+    >>> _get_vcvars_spec('win-amd64', 'win-arm64')
+    'x86_arm64'
+    """
+    if host_platform != 'win-arm64':
+        host_platform = 'win32'
+    vc_hp = _vcvars_names[host_platform]
+    vc_plat = _vcvars_names[platform]
+    return vc_hp if vc_hp == vc_plat else f'{vc_hp}_{vc_plat}'
+
+
+class Compiler(base.Compiler):
+    """Concrete class that implements an interface to Microsoft Visual C++,
+    as defined by the CCompiler abstract class."""
+
+    compiler_type = 'msvc'
+
+    # Just set this so CCompiler's constructor doesn't barf.  We currently
+    # don't use the 'set_executables()' bureaucracy provided by CCompiler,
+    # as it really isn't necessary for this sort of single-compiler class.
+    # Would be nice to have a consistent interface with UnixCCompiler,
+    # though, so it's worth thinking about.
+    executables = {}
+
+    # Private class data (need to distinguish C from C++ source for compiler)
+    _c_extensions = ['.c']
+    _cpp_extensions = ['.cc', '.cpp', '.cxx']
+    _rc_extensions = ['.rc']
+    _mc_extensions = ['.mc']
+
+    # Needed for the filename generation methods provided by the
+    # base class, CCompiler.
+    src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions
+    res_extension = '.res'
+    obj_extension = '.obj'
+    static_lib_extension = '.lib'
+    shared_lib_extension = '.dll'
+    static_lib_format = shared_lib_format = '%s%s'
+    exe_extension = '.exe'
+
+    def __init__(self, verbose=False, force=False) -> None:
+        super().__init__(verbose, force=force)
+        # target platform (.plat_name is consistent with 'bdist')
+        self.plat_name = None
+        self.initialized = False
+
+    @classmethod
+    def _configure(cls, vc_env):
+        """
+        Set class-level include/lib dirs.
+        """
+        cls.include_dirs = cls._parse_path(vc_env.get('include', ''))
+        cls.library_dirs = cls._parse_path(vc_env.get('lib', ''))
+
+    @staticmethod
+    def _parse_path(val):
+        return [dir.rstrip(os.sep) for dir in val.split(os.pathsep) if dir]
+
+    def initialize(self, plat_name: str | None = None) -> None:
+        # multi-init means we would need to check platform same each time...
+        assert not self.initialized, "don't init multiple times"
+        if plat_name is None:
+            plat_name = get_platform()
+        # sanity check for platforms to prevent obscure errors later.
+        if plat_name not in _vcvars_names:
+            raise DistutilsPlatformError(
+                f"--plat-name must be one of {tuple(_vcvars_names)}"
+            )
+
+        plat_spec = _get_vcvars_spec(get_host_platform(), plat_name)
+
+        vc_env = _get_vc_env(plat_spec)
+        if not vc_env:
+            raise DistutilsPlatformError(
+                "Unable to find a compatible Visual Studio installation."
+            )
+        self._configure(vc_env)
+
+        self._paths = vc_env.get('path', '')
+        paths = self._paths.split(os.pathsep)
+        self.cc = _find_exe("cl.exe", paths)
+        self.linker = _find_exe("link.exe", paths)
+        self.lib = _find_exe("lib.exe", paths)
+        self.rc = _find_exe("rc.exe", paths)  # resource compiler
+        self.mc = _find_exe("mc.exe", paths)  # message compiler
+        self.mt = _find_exe("mt.exe", paths)  # message compiler
+
+        self.preprocess_options = None
+        # bpo-38597: Always compile with dynamic linking
+        # Future releases of Python 3.x will include all past
+        # versions of vcruntime*.dll for compatibility.
+        self.compile_options = ['/nologo', '/O2', '/W3', '/GL', '/DNDEBUG', '/MD']
+
+        self.compile_options_debug = [
+            '/nologo',
+            '/Od',
+            '/MDd',
+            '/Zi',
+            '/W3',
+            '/D_DEBUG',
+        ]
+
+        ldflags = ['/nologo', '/INCREMENTAL:NO', '/LTCG']
+
+        ldflags_debug = ['/nologo', '/INCREMENTAL:NO', '/LTCG', '/DEBUG:FULL']
+
+        self.ldflags_exe = [*ldflags, '/MANIFEST:EMBED,ID=1']
+        self.ldflags_exe_debug = [*ldflags_debug, '/MANIFEST:EMBED,ID=1']
+        self.ldflags_shared = [
+            *ldflags,
+            '/DLL',
+            '/MANIFEST:EMBED,ID=2',
+            '/MANIFESTUAC:NO',
+        ]
+        self.ldflags_shared_debug = [
+            *ldflags_debug,
+            '/DLL',
+            '/MANIFEST:EMBED,ID=2',
+            '/MANIFESTUAC:NO',
+        ]
+        self.ldflags_static = [*ldflags]
+        self.ldflags_static_debug = [*ldflags_debug]
+
+        self._ldflags = {
+            (base.Compiler.EXECUTABLE, None): self.ldflags_exe,
+            (base.Compiler.EXECUTABLE, False): self.ldflags_exe,
+            (base.Compiler.EXECUTABLE, True): self.ldflags_exe_debug,
+            (base.Compiler.SHARED_OBJECT, None): self.ldflags_shared,
+            (base.Compiler.SHARED_OBJECT, False): self.ldflags_shared,
+            (base.Compiler.SHARED_OBJECT, True): self.ldflags_shared_debug,
+            (base.Compiler.SHARED_LIBRARY, None): self.ldflags_static,
+            (base.Compiler.SHARED_LIBRARY, False): self.ldflags_static,
+            (base.Compiler.SHARED_LIBRARY, True): self.ldflags_static_debug,
+        }
+
+        self.initialized = True
+
+    # -- Worker methods ------------------------------------------------
+
+    @property
+    def out_extensions(self) -> dict[str, str]:
+        return {
+            **super().out_extensions,
+            **{
+                ext: self.res_extension
+                for ext in self._rc_extensions + self._mc_extensions
+            },
+        }
+
+    def compile(  # noqa: C901
+        self,
+        sources,
+        output_dir=None,
+        macros=None,
+        include_dirs=None,
+        debug=False,
+        extra_preargs=None,
+        extra_postargs=None,
+        depends=None,
+    ):
+        if not self.initialized:
+            self.initialize()
+        compile_info = self._setup_compile(
+            output_dir, macros, include_dirs, sources, depends, extra_postargs
+        )
+        macros, objects, extra_postargs, pp_opts, build = compile_info
+
+        compile_opts = extra_preargs or []
+        compile_opts.append('/c')
+        if debug:
+            compile_opts.extend(self.compile_options_debug)
+        else:
+            compile_opts.extend(self.compile_options)
+
+        add_cpp_opts = False
+
+        for obj in objects:
+            try:
+                src, ext = build[obj]
+            except KeyError:
+                continue
+            if debug:
+                # pass the full pathname to MSVC in debug mode,
+                # this allows the debugger to find the source file
+                # without asking the user to browse for it
+                src = os.path.abspath(src)
+
+            if ext in self._c_extensions:
+                input_opt = f"/Tc{src}"
+            elif ext in self._cpp_extensions:
+                input_opt = f"/Tp{src}"
+                add_cpp_opts = True
+            elif ext in self._rc_extensions:
+                # compile .RC to .RES file
+                input_opt = src
+                output_opt = "/fo" + obj
+                try:
+                    self.spawn([self.rc] + pp_opts + [output_opt, input_opt])
+                except DistutilsExecError as msg:
+                    raise CompileError(msg)
+                continue
+            elif ext in self._mc_extensions:
+                # Compile .MC to .RC file to .RES file.
+                #   * '-h dir' specifies the directory for the
+                #     generated include file
+                #   * '-r dir' specifies the target directory of the
+                #     generated RC file and the binary message resource
+                #     it includes
+                #
+                # For now (since there are no options to change this),
+                # we use the source-directory for the include file and
+                # the build directory for the RC file and message
+                # resources. This works at least for win32all.
+                h_dir = os.path.dirname(src)
+                rc_dir = os.path.dirname(obj)
+                try:
+                    # first compile .MC to .RC and .H file
+                    self.spawn([self.mc, '-h', h_dir, '-r', rc_dir, src])
+                    base, _ = os.path.splitext(os.path.basename(src))
+                    rc_file = os.path.join(rc_dir, base + '.rc')
+                    # then compile .RC to .RES file
+                    self.spawn([self.rc, "/fo" + obj, rc_file])
+
+                except DistutilsExecError as msg:
+                    raise CompileError(msg)
+                continue
+            else:
+                # how to handle this file?
+                raise CompileError(f"Don't know how to compile {src} to {obj}")
+
+            args = [self.cc] + compile_opts + pp_opts
+            if add_cpp_opts:
+                args.append('/EHsc')
+            args.extend((input_opt, "/Fo" + obj))
+            args.extend(extra_postargs)
+
+            try:
+                self.spawn(args)
+            except DistutilsExecError as msg:
+                raise CompileError(msg)
+
+        return objects
+
+    def create_static_lib(
+        self,
+        objects: list[str] | tuple[str, ...],
+        output_libname: str,
+        output_dir: str | None = None,
+        debug: bool = False,
+        target_lang: str | None = None,
+    ) -> None:
+        if not self.initialized:
+            self.initialize()
+        objects, output_dir = self._fix_object_args(objects, output_dir)
+        output_filename = self.library_filename(output_libname, output_dir=output_dir)
+
+        if self._need_link(objects, output_filename):
+            lib_args = objects + ['/OUT:' + output_filename]
+            if debug:
+                pass  # XXX what goes here?
+            try:
+                log.debug('Executing "%s" %s', self.lib, ' '.join(lib_args))
+                self.spawn([self.lib] + lib_args)
+            except DistutilsExecError as msg:
+                raise LibError(msg)
+        else:
+            log.debug("skipping %s (up-to-date)", output_filename)
+
+    def link(
+        self,
+        target_desc: str,
+        objects: list[str] | tuple[str, ...],
+        output_filename: str,
+        output_dir: str | None = None,
+        libraries: list[str] | tuple[str, ...] | None = None,
+        library_dirs: list[str] | tuple[str, ...] | None = None,
+        runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
+        export_symbols: Iterable[str] | None = None,
+        debug: bool = False,
+        extra_preargs: list[str] | None = None,
+        extra_postargs: Iterable[str] | None = None,
+        build_temp: str | os.PathLike[str] | None = None,
+        target_lang: str | None = None,
+    ) -> None:
+        if not self.initialized:
+            self.initialize()
+        objects, output_dir = self._fix_object_args(objects, output_dir)
+        fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
+        libraries, library_dirs, runtime_library_dirs = fixed_args
+
+        if runtime_library_dirs:
+            self.warn(
+                "I don't know what to do with 'runtime_library_dirs': "
+                + str(runtime_library_dirs)
+            )
+
+        lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
+        if output_dir is not None:
+            output_filename = os.path.join(output_dir, output_filename)
+
+        if self._need_link(objects, output_filename):
+            ldflags = self._ldflags[target_desc, debug]
+
+            export_opts = ["/EXPORT:" + sym for sym in (export_symbols or [])]
+
+            ld_args = (
+                ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename]
+            )
+
+            # The MSVC linker generates .lib and .exp files, which cannot be
+            # suppressed by any linker switches. The .lib files may even be
+            # needed! Make sure they are generated in the temporary build
+            # directory. Since they have different names for debug and release
+            # builds, they can go into the same directory.
+            build_temp = os.path.dirname(objects[0])
+            if export_symbols is not None:
+                (dll_name, dll_ext) = os.path.splitext(
+                    os.path.basename(output_filename)
+                )
+                implib_file = os.path.join(build_temp, self.library_filename(dll_name))
+                ld_args.append('/IMPLIB:' + implib_file)
+
+            if extra_preargs:
+                ld_args[:0] = extra_preargs
+            if extra_postargs:
+                ld_args.extend(extra_postargs)
+
+            output_dir = os.path.dirname(os.path.abspath(output_filename))
+            self.mkpath(output_dir)
+            try:
+                log.debug('Executing "%s" %s', self.linker, ' '.join(ld_args))
+                self.spawn([self.linker] + ld_args)
+            except DistutilsExecError as msg:
+                raise LinkError(msg)
+        else:
+            log.debug("skipping %s (up-to-date)", output_filename)
+
+    def spawn(self, cmd):
+        env = dict(os.environ, PATH=self._paths)
+        with self._fallback_spawn(cmd, env) as fallback:
+            return super().spawn(cmd, env=env)
+        return fallback.value
+
+    @contextlib.contextmanager
+    def _fallback_spawn(self, cmd, env):
+        """
+        Discovered in pypa/distutils#15, some tools monkeypatch the compiler,
+        so the 'env' kwarg causes a TypeError. Detect this condition and
+        restore the legacy, unsafe behavior.
+        """
+        bag = type('Bag', (), {})()
+        try:
+            yield bag
+        except TypeError as exc:
+            if "unexpected keyword argument 'env'" not in str(exc):
+                raise
+        else:
+            return
+        warnings.warn("Fallback spawn triggered. Please update distutils monkeypatch.")
+        with mock.patch.dict('os.environ', env):
+            bag.value = super().spawn(cmd)
+
+    # -- Miscellaneous methods -----------------------------------------
+    # These are all used by the 'gen_lib_options() function, in
+    # ccompiler.py.
+
+    def library_dir_option(self, dir):
+        return "/LIBPATH:" + dir
+
+    def runtime_library_dir_option(self, dir):
+        raise DistutilsPlatformError(
+            "don't know how to set runtime library search path for MSVC"
+        )
+
+    def library_option(self, lib):
+        return self.library_filename(lib)
+
+    def find_library_file(self, dirs, lib, debug=False):
+        # Prefer a debugging library if found (and requested), but deal
+        # with it if we don't have one.
+        if debug:
+            try_names = [lib + "_d", lib]
+        else:
+            try_names = [lib]
+        for dir in dirs:
+            for name in try_names:
+                libfile = os.path.join(dir, self.library_filename(name))
+                if os.path.isfile(libfile):
+                    return libfile
+        else:
+            # Oops, didn't find it in *any* of 'dirs'
+            return None
diff --git a/setuptools/_distutils/tests/test_ccompiler.py b/setuptools/_distutils/compilers/C/tests/test_base.py
similarity index 79%
rename from setuptools/_distutils/tests/test_ccompiler.py
rename to setuptools/_distutils/compilers/C/tests/test_base.py
index 49691d4b9b..a762e2b649 100644
--- a/setuptools/_distutils/tests/test_ccompiler.py
+++ b/setuptools/_distutils/compilers/C/tests/test_base.py
@@ -1,21 +1,12 @@
-import os
-import sys
 import platform
-import textwrap
 import sysconfig
+import textwrap
 
 import pytest
 
-from distutils import ccompiler
-
+from .. import base
 
-def _make_strs(paths):
-    """
-    Convert paths to strings for legacy compatibility.
-    """
-    if sys.version_info > (3, 8) and platform.system() != "Windows":
-        return paths
-    return list(map(os.fspath, paths))
+pytestmark = pytest.mark.usefixtures('suppress_path_mangle')
 
 
 @pytest.fixture
@@ -36,7 +27,7 @@ def c_file(tmp_path):
         .lstrip()
         .replace('#headers', headers)
     )
-    c_file.write_text(payload)
+    c_file.write_text(payload, encoding='utf-8')
     return c_file
 
 
@@ -45,21 +36,21 @@ def test_set_include_dirs(c_file):
     Extensions should build even if set_include_dirs is invoked.
     In particular, compiler-specific paths should not be overridden.
     """
-    compiler = ccompiler.new_compiler()
+    compiler = base.new_compiler()
     python = sysconfig.get_paths()['include']
     compiler.set_include_dirs([python])
-    compiler.compile(_make_strs([c_file]))
+    compiler.compile([c_file])
 
     # do it again, setting include dirs after any initialization
     compiler.set_include_dirs([python])
-    compiler.compile(_make_strs([c_file]))
+    compiler.compile([c_file])
 
 
 def test_has_function_prototype():
     # Issue https://github.com/pypa/setuptools/issues/3648
     # Test prototype-generating behavior.
 
-    compiler = ccompiler.new_compiler()
+    compiler = base.new_compiler()
 
     # Every C implementation should have these.
     assert compiler.has_function('abort')
@@ -83,10 +74,10 @@ def test_include_dirs_after_multiple_compile_calls(c_file):
     Calling compile multiple times should not change the include dirs
     (regression test for setuptools issue #3591).
     """
-    compiler = ccompiler.new_compiler()
+    compiler = base.new_compiler()
     python = sysconfig.get_paths()['include']
     compiler.set_include_dirs([python])
-    compiler.compile(_make_strs([c_file]))
+    compiler.compile([c_file])
     assert compiler.include_dirs == [python]
-    compiler.compile(_make_strs([c_file]))
+    compiler.compile([c_file])
     assert compiler.include_dirs == [python]
diff --git a/setuptools/_distutils/tests/test_cygwinccompiler.py b/setuptools/_distutils/compilers/C/tests/test_cygwin.py
similarity index 55%
rename from setuptools/_distutils/tests/test_cygwinccompiler.py
rename to setuptools/_distutils/compilers/C/tests/test_cygwin.py
index 6fb449a6c2..9adf6b8ebf 100644
--- a/setuptools/_distutils/tests/test_cygwinccompiler.py
+++ b/setuptools/_distutils/compilers/C/tests/test_cygwin.py
@@ -1,18 +1,13 @@
 """Tests for distutils.cygwinccompiler."""
-import sys
+
 import os
+import sys
+from distutils import sysconfig
+from distutils.tests import support
 
 import pytest
 
-from distutils.cygwinccompiler import (
-    check_config_h,
-    CONFIG_H_OK,
-    CONFIG_H_NOTOK,
-    CONFIG_H_UNCERTAIN,
-    get_msvcr,
-)
-from distutils.tests import support
-from distutils import sysconfig
+from .. import cygwin
 
 
 @pytest.fixture(autouse=True)
@@ -54,63 +49,28 @@ def test_check_config_h(self):
             '4.0.1 (Apple Computer, Inc. build 5370)]'
         )
 
-        assert check_config_h()[0] == CONFIG_H_OK
+        assert cygwin.check_config_h()[0] == cygwin.CONFIG_H_OK
 
         # then it tries to see if it can find "__GNUC__" in pyconfig.h
         sys.version = 'something without the *CC word'
 
         # if the file doesn't exist it returns  CONFIG_H_UNCERTAIN
-        assert check_config_h()[0] == CONFIG_H_UNCERTAIN
+        assert cygwin.check_config_h()[0] == cygwin.CONFIG_H_UNCERTAIN
 
         # if it exists but does not contain __GNUC__, it returns CONFIG_H_NOTOK
         self.write_file(self.python_h, 'xxx')
-        assert check_config_h()[0] == CONFIG_H_NOTOK
+        assert cygwin.check_config_h()[0] == cygwin.CONFIG_H_NOTOK
 
         # and CONFIG_H_OK if __GNUC__ is found
         self.write_file(self.python_h, 'xxx __GNUC__ xxx')
-        assert check_config_h()[0] == CONFIG_H_OK
+        assert cygwin.check_config_h()[0] == cygwin.CONFIG_H_OK
 
     def test_get_msvcr(self):
-        # none
-        sys.version = (
-            '2.6.1 (r261:67515, Dec  6 2008, 16:42:21) '
-            '\n[GCC 4.0.1 (Apple Computer, Inc. build 5370)]'
-        )
-        assert get_msvcr() is None
-
-        # MSVC 7.0
-        sys.version = (
-            '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.1300 32 bits (Intel)]'
-        )
-        assert get_msvcr() == ['msvcr70']
-
-        # MSVC 7.1
-        sys.version = (
-            '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.1310 32 bits (Intel)]'
-        )
-        assert get_msvcr() == ['msvcr71']
-
-        # VS2005 / MSVC 8.0
-        sys.version = (
-            '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.1400 32 bits (Intel)]'
-        )
-        assert get_msvcr() == ['msvcr80']
-
-        # VS2008 / MSVC 9.0
-        sys.version = (
-            '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.1500 32 bits (Intel)]'
-        )
-        assert get_msvcr() == ['msvcr90']
+        assert cygwin.get_msvcr() == []
 
-        sys.version = (
-            '3.10.0 (tags/v3.10.0:b494f59, Oct  4 2021, 18:46:30) '
-            '[MSC v.1929 32 bit (Intel)]'
-        )
-        assert get_msvcr() == ['vcruntime140']
+    @pytest.mark.skipif('sys.platform != "cygwin"')
+    def test_dll_libraries_not_none(self):
+        from distutils.cygwinccompiler import CygwinCCompiler
 
-        # unknown
-        sys.version = (
-            '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.2000 32 bits (Intel)]'
-        )
-        with pytest.raises(ValueError):
-            get_msvcr()
+        compiler = CygwinCCompiler()
+        assert compiler.dll_libraries is not None
diff --git a/setuptools/_distutils/compilers/C/tests/test_mingw.py b/setuptools/_distutils/compilers/C/tests/test_mingw.py
new file mode 100644
index 0000000000..dc45687a91
--- /dev/null
+++ b/setuptools/_distutils/compilers/C/tests/test_mingw.py
@@ -0,0 +1,48 @@
+from distutils import sysconfig
+from distutils.errors import DistutilsPlatformError
+from distutils.util import is_mingw, split_quoted
+
+import pytest
+
+from .. import cygwin, errors
+
+
+class TestMinGW32Compiler:
+    @pytest.mark.skipif(not is_mingw(), reason='not on mingw')
+    def test_compiler_type(self):
+        compiler = cygwin.MinGW32Compiler()
+        assert compiler.compiler_type == 'mingw32'
+
+    @pytest.mark.skipif(not is_mingw(), reason='not on mingw')
+    def test_set_executables(self, monkeypatch):
+        monkeypatch.setenv('CC', 'cc')
+        monkeypatch.setenv('CXX', 'c++')
+
+        compiler = cygwin.MinGW32Compiler()
+
+        assert compiler.compiler == split_quoted('cc -O -Wall')
+        assert compiler.compiler_so == split_quoted('cc -shared -O -Wall')
+        assert compiler.compiler_cxx == split_quoted('c++ -O -Wall')
+        assert compiler.linker_exe == split_quoted('cc')
+        assert compiler.linker_so == split_quoted('cc -shared')
+
+    @pytest.mark.skipif(not is_mingw(), reason='not on mingw')
+    def test_runtime_library_dir_option(self):
+        compiler = cygwin.MinGW32Compiler()
+        with pytest.raises(DistutilsPlatformError):
+            compiler.runtime_library_dir_option('/usr/lib')
+
+    @pytest.mark.skipif(not is_mingw(), reason='not on mingw')
+    def test_cygwincc_error(self, monkeypatch):
+        monkeypatch.setattr(cygwin, 'is_cygwincc', lambda _: True)
+
+        with pytest.raises(errors.Error):
+            cygwin.MinGW32Compiler()
+
+    @pytest.mark.skipif('sys.platform == "cygwin"')
+    def test_customize_compiler_with_msvc_python(self):
+        # In case we have an MSVC Python build, but still want to use
+        # MinGW32Compiler, then customize_compiler() shouldn't fail at least.
+        # https://github.com/pypa/setuptools/issues/4456
+        compiler = cygwin.MinGW32Compiler()
+        sysconfig.customize_compiler(compiler)
diff --git a/setuptools/_distutils/tests/test_msvccompiler.py b/setuptools/_distutils/compilers/C/tests/test_msvc.py
similarity index 67%
rename from setuptools/_distutils/tests/test_msvccompiler.py
rename to setuptools/_distutils/compilers/C/tests/test_msvc.py
index f63537b8e5..eca831996a 100644
--- a/setuptools/_distutils/tests/test_msvccompiler.py
+++ b/setuptools/_distutils/compilers/C/tests/test_msvc.py
@@ -1,36 +1,57 @@
-"""Tests for distutils._msvccompiler."""
-import sys
 import os
+import sys
+import sysconfig
 import threading
 import unittest.mock as mock
-
-import pytest
-
 from distutils.errors import DistutilsPlatformError
 from distutils.tests import support
-from distutils import _msvccompiler
+from distutils.util import get_platform
+
+import pytest
 
+from .. import msvc
 
-needs_winreg = pytest.mark.skipif('not hasattr(_msvccompiler, "winreg")')
+needs_winreg = pytest.mark.skipif('not hasattr(msvc, "winreg")')
 
 
 class Testmsvccompiler(support.TempdirManager):
-    def test_no_compiler(self):
+    def test_no_compiler(self, monkeypatch):
         # makes sure query_vcvarsall raises
         # a DistutilsPlatformError if the compiler
         # is not found
         def _find_vcvarsall(plat_spec):
             return None, None
 
-        old_find_vcvarsall = _msvccompiler._find_vcvarsall
-        _msvccompiler._find_vcvarsall = _find_vcvarsall
-        try:
-            with pytest.raises(DistutilsPlatformError):
-                _msvccompiler._get_vc_env(
-                    'wont find this version',
-                )
-        finally:
-            _msvccompiler._find_vcvarsall = old_find_vcvarsall
+        monkeypatch.setattr(msvc, '_find_vcvarsall', _find_vcvarsall)
+
+        with pytest.raises(DistutilsPlatformError):
+            msvc._get_vc_env(
+                'wont find this version',
+            )
+
+    @pytest.mark.skipif(
+        not sysconfig.get_platform().startswith("win"),
+        reason="Only run test for non-mingw Windows platforms",
+    )
+    @pytest.mark.parametrize(
+        "plat_name, expected",
+        [
+            ("win-arm64", "win-arm64"),
+            ("win-amd64", "win-amd64"),
+            (None, get_platform()),
+        ],
+    )
+    def test_cross_platform_compilation_paths(self, monkeypatch, plat_name, expected):
+        """
+        Ensure a specified target platform is passed to _get_vcvars_spec.
+        """
+        compiler = msvc.Compiler()
+
+        def _get_vcvars_spec(host_platform, platform):
+            assert platform == expected
+
+        monkeypatch.setattr(msvc, '_get_vcvars_spec', _get_vcvars_spec)
+        compiler.initialize(plat_name)
 
     @needs_winreg
     def test_get_vc_env_unicode(self):
@@ -41,7 +62,7 @@ def test_get_vc_env_unicode(self):
         old_distutils_use_sdk = os.environ.pop('DISTUTILS_USE_SDK', None)
         os.environ[test_var] = test_value
         try:
-            env = _msvccompiler._get_vc_env('x86')
+            env = msvc._get_vc_env('x86')
             assert test_var.lower() in env
             assert test_value == env[test_var.lower()]
         finally:
@@ -54,7 +75,7 @@ def test_get_vc_env_unicode(self):
     def test_get_vc(self, ver):
         # This function cannot be mocked, so pass if VC is found
         # and skip otherwise.
-        lookup = getattr(_msvccompiler, f'_find_vc{ver}')
+        lookup = getattr(msvc, f'_find_vc{ver}')
         expected_version = {2015: 14, 2017: 15}[ver]
         version, path = lookup()
         if not version:
@@ -81,7 +102,7 @@ def test_concurrent_safe(self):
         """
         Concurrent calls to spawn should have consistent results.
         """
-        compiler = _msvccompiler.MSVCCompiler()
+        compiler = msvc.Compiler()
         compiler._paths = "expected"
         inner_cmd = 'import os; assert os.environ["PATH"] == "expected"'
         command = [sys.executable, '-c', inner_cmd]
@@ -102,7 +123,7 @@ def test_concurrent_safe_fallback(self):
         """
         from distutils import ccompiler
 
-        compiler = _msvccompiler.MSVCCompiler()
+        compiler = msvc.Compiler()
         compiler._paths = "expected"
 
         def CCompiler_spawn(self, cmd):
diff --git a/setuptools/_distutils/tests/test_unixccompiler.py b/setuptools/_distutils/compilers/C/tests/test_unix.py
similarity index 63%
rename from setuptools/_distutils/tests/test_unixccompiler.py
rename to setuptools/_distutils/compilers/C/tests/test_unix.py
index a018442459..35b6b0e050 100644
--- a/setuptools/_distutils/tests/test_unixccompiler.py
+++ b/setuptools/_distutils/compilers/C/tests/test_unix.py
@@ -1,18 +1,19 @@
 """Tests for distutils.unixccompiler."""
+
 import os
 import sys
 import unittest.mock as mock
-
-from .py38compat import EnvironmentVarGuard
-
 from distutils import sysconfig
+from distutils.compat import consolidate_linker_args
 from distutils.errors import DistutilsPlatformError
-from distutils.unixccompiler import UnixCCompiler
+from distutils.tests import support
+from distutils.tests.compat.py39 import EnvironmentVarGuard
 from distutils.util import _clear_cached_macosx_ver
 
-from . import support
 import pytest
 
+from .. import unix
+
 
 @pytest.fixture(autouse=True)
 def save_values(monkeypatch):
@@ -23,7 +24,7 @@ def save_values(monkeypatch):
 
 @pytest.fixture(autouse=True)
 def compiler_wrapper(request):
-    class CompilerWrapper(UnixCCompiler):
+    class CompilerWrapper(unix.Compiler):
         def rpath_foo(self):
             return self.runtime_library_dir_option('/foo')
 
@@ -31,7 +32,7 @@ def rpath_foo(self):
 
 
 class TestUnixCCompiler(support.TempdirManager):
-    @pytest.mark.skipif('platform.system == "Windows"')  # noqa: C901
+    @pytest.mark.skipif('platform.system == "Windows"')
     def test_runtime_libdir_option(self):  # noqa: C901
         # Issue #5900; GitHub Issue #37
         #
@@ -72,10 +73,7 @@ def gcv(var):
 
         def do_darwin_test(syscfg_macosx_ver, env_macosx_ver, expected_flag):
             env = os.environ
-            msg = "macOS version = (sysconfig={!r}, env={!r})".format(
-                syscfg_macosx_ver,
-                env_macosx_ver,
-            )
+            msg = f"macOS version = (sysconfig={syscfg_macosx_ver!r}, env={env_macosx_ver!r})"
 
             # Save
             old_gcv = sysconfig.get_config_var
@@ -152,7 +150,10 @@ def gcv(v):
                 return 'yes'
 
         sysconfig.get_config_var = gcv
-        assert self.cc.rpath_foo() == '-Wl,--enable-new-dtags,-R/foo'
+        assert self.cc.rpath_foo() == consolidate_linker_args([
+            '-Wl,--enable-new-dtags',
+            '-Wl,-rpath,/foo',
+        ])
 
         def gcv(v):
             if v == 'CC':
@@ -161,7 +162,10 @@ def gcv(v):
                 return 'yes'
 
         sysconfig.get_config_var = gcv
-        assert self.cc.rpath_foo() == '-Wl,--enable-new-dtags,-R/foo'
+        assert self.cc.rpath_foo() == consolidate_linker_args([
+            '-Wl,--enable-new-dtags',
+            '-Wl,-rpath,/foo',
+        ])
 
         # GCC non-GNULD
         sys.platform = 'bar'
@@ -186,7 +190,10 @@ def gcv(v):
                 return 'yes'
 
         sysconfig.get_config_var = gcv
-        assert self.cc.rpath_foo() == '-Wl,--enable-new-dtags,-R/foo'
+        assert self.cc.rpath_foo() == consolidate_linker_args([
+            '-Wl,--enable-new-dtags',
+            '-Wl,-rpath,/foo',
+        ])
 
         # non-GCC GNULD
         sys.platform = 'bar'
@@ -198,7 +205,10 @@ def gcv(v):
                 return 'yes'
 
         sysconfig.get_config_var = gcv
-        assert self.cc.rpath_foo() == '-Wl,--enable-new-dtags,-R/foo'
+        assert self.cc.rpath_foo() == consolidate_linker_args([
+            '-Wl,--enable-new-dtags',
+            '-Wl,-rpath,/foo',
+        ])
 
         # non-GCC non-GNULD
         sys.platform = 'bar'
@@ -235,6 +245,70 @@ def gcvs(*args, _orig=sysconfig.get_config_vars):
         assert self.cc.linker_so[0] == 'my_cc'
 
     @pytest.mark.skipif('platform.system == "Windows"')
+    def test_cxx_commands_used_are_correct(self):
+        def gcv(v):
+            if v == 'LDSHARED':
+                return 'ccache gcc-4.2 -bundle -undefined dynamic_lookup'
+            elif v == 'LDCXXSHARED':
+                return 'ccache g++-4.2 -bundle -undefined dynamic_lookup'
+            elif v == 'CXX':
+                return 'ccache g++-4.2'
+            elif v == 'CC':
+                return 'ccache gcc-4.2'
+            return ''
+
+        def gcvs(*args, _orig=sysconfig.get_config_vars):
+            if args:
+                return list(map(sysconfig.get_config_var, args))
+            return _orig()  # pragma: no cover
+
+        sysconfig.get_config_var = gcv
+        sysconfig.get_config_vars = gcvs
+        with (
+            mock.patch.object(self.cc, 'spawn', return_value=None) as mock_spawn,
+            mock.patch.object(self.cc, '_need_link', return_value=True),
+            mock.patch.object(self.cc, 'mkpath', return_value=None),
+            EnvironmentVarGuard() as env,
+        ):
+            # override environment overrides in case they're specified by CI
+            del env['CXX']
+            del env['LDCXXSHARED']
+
+            sysconfig.customize_compiler(self.cc)
+            assert self.cc.linker_so_cxx[0:2] == ['ccache', 'g++-4.2']
+            assert self.cc.linker_exe_cxx[0:2] == ['ccache', 'g++-4.2']
+            self.cc.link(None, [], 'a.out', target_lang='c++')
+            call_args = mock_spawn.call_args[0][0]
+            expected = ['ccache', 'g++-4.2', '-bundle', '-undefined', 'dynamic_lookup']
+            assert call_args[:5] == expected
+
+            self.cc.link_executable([], 'a.out', target_lang='c++')
+            call_args = mock_spawn.call_args[0][0]
+            expected = ['ccache', 'g++-4.2', '-o', self.cc.executable_filename('a.out')]
+            assert call_args[:4] == expected
+
+            env['LDCXXSHARED'] = 'wrapper g++-4.2 -bundle -undefined dynamic_lookup'
+            env['CXX'] = 'wrapper g++-4.2'
+            sysconfig.customize_compiler(self.cc)
+            assert self.cc.linker_so_cxx[0:2] == ['wrapper', 'g++-4.2']
+            assert self.cc.linker_exe_cxx[0:2] == ['wrapper', 'g++-4.2']
+            self.cc.link(None, [], 'a.out', target_lang='c++')
+            call_args = mock_spawn.call_args[0][0]
+            expected = ['wrapper', 'g++-4.2', '-bundle', '-undefined', 'dynamic_lookup']
+            assert call_args[:5] == expected
+
+            self.cc.link_executable([], 'a.out', target_lang='c++')
+            call_args = mock_spawn.call_args[0][0]
+            expected = [
+                'wrapper',
+                'g++-4.2',
+                '-o',
+                self.cc.executable_filename('a.out'),
+            ]
+            assert call_args[:4] == expected
+
+    @pytest.mark.skipif('platform.system == "Windows"')
+    @pytest.mark.usefixtures('disable_macos_customization')
     def test_cc_overrides_ldshared_for_cxx_correctly(self):
         """
         Ensure that setting CC env variable also changes default linker
@@ -246,9 +320,13 @@ def test_cc_overrides_ldshared_for_cxx_correctly(self):
         def gcv(v):
             if v == 'LDSHARED':
                 return 'gcc-4.2 -bundle -undefined dynamic_lookup '
+            elif v == 'LDCXXSHARED':
+                return 'g++-4.2 -bundle -undefined dynamic_lookup '
             elif v == 'CXX':
                 return 'g++-4.2'
-            return 'gcc-4.2'
+            elif v == 'CC':
+                return 'gcc-4.2'
+            return ''
 
         def gcvs(*args, _orig=sysconfig.get_config_vars):
             if args:
@@ -257,13 +335,12 @@ def gcvs(*args, _orig=sysconfig.get_config_vars):
 
         sysconfig.get_config_var = gcv
         sysconfig.get_config_vars = gcvs
-        with mock.patch.object(
-            self.cc, 'spawn', return_value=None
-        ) as mock_spawn, mock.patch.object(
-            self.cc, '_need_link', return_value=True
-        ), mock.patch.object(
-            self.cc, 'mkpath', return_value=None
-        ), EnvironmentVarGuard() as env:
+        with (
+            mock.patch.object(self.cc, 'spawn', return_value=None) as mock_spawn,
+            mock.patch.object(self.cc, '_need_link', return_value=True),
+            mock.patch.object(self.cc, 'mkpath', return_value=None),
+            EnvironmentVarGuard() as env,
+        ):
             env['CC'] = 'ccache my_cc'
             env['CXX'] = 'my_cxx'
             del env['LDSHARED']
@@ -304,3 +381,33 @@ def test_has_function(self):
         self.cc.output_dir = 'scratch'
         os.chdir(self.mkdtemp())
         self.cc.has_function('abort')
+
+    def test_find_library_file(self, monkeypatch):
+        compiler = unix.Compiler()
+        compiler._library_root = lambda dir: dir
+        monkeypatch.setattr(os.path, 'exists', lambda d: 'existing' in d)
+
+        libname = 'libabc.dylib' if sys.platform != 'cygwin' else 'cygabc.dll'
+        dirs = ('/foo/bar/missing', '/foo/bar/existing')
+        assert (
+            compiler.find_library_file(dirs, 'abc').replace('\\', '/')
+            == f'/foo/bar/existing/{libname}'
+        )
+        assert (
+            compiler.find_library_file(reversed(dirs), 'abc').replace('\\', '/')
+            == f'/foo/bar/existing/{libname}'
+        )
+
+        monkeypatch.setattr(
+            os.path,
+            'exists',
+            lambda d: 'existing' in d and '.a' in d and '.dll.a' not in d,
+        )
+        assert (
+            compiler.find_library_file(dirs, 'abc').replace('\\', '/')
+            == '/foo/bar/existing/libabc.a'
+        )
+        assert (
+            compiler.find_library_file(reversed(dirs), 'abc').replace('\\', '/')
+            == '/foo/bar/existing/libabc.a'
+        )
diff --git a/setuptools/_distutils/compilers/C/unix.py b/setuptools/_distutils/compilers/C/unix.py
new file mode 100644
index 0000000000..1231b32d20
--- /dev/null
+++ b/setuptools/_distutils/compilers/C/unix.py
@@ -0,0 +1,422 @@
+"""distutils.unixccompiler
+
+Contains the UnixCCompiler class, a subclass of CCompiler that handles
+the "typical" Unix-style command-line C compiler:
+  * macros defined with -Dname[=value]
+  * macros undefined with -Uname
+  * include search directories specified with -Idir
+  * libraries specified with -lllib
+  * library search directories specified with -Ldir
+  * compile handled by 'cc' (or similar) executable with -c option:
+    compiles .c to .o
+  * link static library handled by 'ar' command (possibly with 'ranlib')
+  * link shared library handled by 'cc -shared'
+"""
+
+from __future__ import annotations
+
+import itertools
+import os
+import re
+import shlex
+import sys
+from collections.abc import Iterable
+
+from ... import sysconfig
+from ..._log import log
+from ..._macos_compat import compiler_fixup
+from ..._modified import newer
+from ...compat import consolidate_linker_args
+from ...errors import DistutilsExecError
+from . import base
+from .base import _Macro, gen_lib_options, gen_preprocess_options
+from .errors import (
+    CompileError,
+    LibError,
+    LinkError,
+)
+
+# XXX Things not currently handled:
+#   * optimization/debug/warning flags; we just use whatever's in Python's
+#     Makefile and live with it.  Is this adequate?  If not, we might
+#     have to have a bunch of subclasses GNUCCompiler, SGICCompiler,
+#     SunCCompiler, and I suspect down that road lies madness.
+#   * even if we don't know a warning flag from an optimization flag,
+#     we need some way for outsiders to feed preprocessor/compiler/linker
+#     flags in to us -- eg. a sysadmin might want to mandate certain flags
+#     via a site config file, or a user might want to set something for
+#     compiling this module distribution only via the setup.py command
+#     line, whatever.  As long as these options come from something on the
+#     current system, they can be as system-dependent as they like, and we
+#     should just happily stuff them into the preprocessor/compiler/linker
+#     options and carry on.
+
+
+def _split_env(cmd):
+    """
+    For macOS, split command into 'env' portion (if any)
+    and the rest of the linker command.
+
+    >>> _split_env(['a', 'b', 'c'])
+    ([], ['a', 'b', 'c'])
+    >>> _split_env(['/usr/bin/env', 'A=3', 'gcc'])
+    (['/usr/bin/env', 'A=3'], ['gcc'])
+    """
+    pivot = 0
+    if os.path.basename(cmd[0]) == "env":
+        pivot = 1
+        while '=' in cmd[pivot]:
+            pivot += 1
+    return cmd[:pivot], cmd[pivot:]
+
+
+def _split_aix(cmd):
+    """
+    AIX platforms prefix the compiler with the ld_so_aix
+    script, so split that from the linker command.
+
+    >>> _split_aix(['a', 'b', 'c'])
+    ([], ['a', 'b', 'c'])
+    >>> _split_aix(['/bin/foo/ld_so_aix', 'gcc'])
+    (['/bin/foo/ld_so_aix'], ['gcc'])
+    """
+    pivot = os.path.basename(cmd[0]) == 'ld_so_aix'
+    return cmd[:pivot], cmd[pivot:]
+
+
+def _linker_params(linker_cmd, compiler_cmd):
+    """
+    The linker command usually begins with the compiler
+    command (possibly multiple elements), followed by zero or more
+    params for shared library building.
+
+    If the LDSHARED env variable overrides the linker command,
+    however, the commands may not match.
+
+    Return the best guess of the linker parameters by stripping
+    the linker command. If the compiler command does not
+    match the linker command, assume the linker command is
+    just the first element.
+
+    >>> _linker_params('gcc foo bar'.split(), ['gcc'])
+    ['foo', 'bar']
+    >>> _linker_params('gcc foo bar'.split(), ['other'])
+    ['foo', 'bar']
+    >>> _linker_params('ccache gcc foo bar'.split(), 'ccache gcc'.split())
+    ['foo', 'bar']
+    >>> _linker_params(['gcc'], ['gcc'])
+    []
+    """
+    c_len = len(compiler_cmd)
+    pivot = c_len if linker_cmd[:c_len] == compiler_cmd else 1
+    return linker_cmd[pivot:]
+
+
+class Compiler(base.Compiler):
+    compiler_type = 'unix'
+
+    # These are used by CCompiler in two places: the constructor sets
+    # instance attributes 'preprocessor', 'compiler', etc. from them, and
+    # 'set_executable()' allows any of these to be set.  The defaults here
+    # are pretty generic; they will probably have to be set by an outsider
+    # (eg. using information discovered by the sysconfig about building
+    # Python extensions).
+    executables = {
+        'preprocessor': None,
+        'compiler': ["cc"],
+        'compiler_so': ["cc"],
+        'compiler_cxx': ["c++"],
+        'compiler_so_cxx': ["c++"],
+        'linker_so': ["cc", "-shared"],
+        'linker_so_cxx': ["c++", "-shared"],
+        'linker_exe': ["cc"],
+        'linker_exe_cxx': ["c++", "-shared"],
+        'archiver': ["ar", "-cr"],
+        'ranlib': None,
+    }
+
+    if sys.platform[:6] == "darwin":
+        executables['ranlib'] = ["ranlib"]
+
+    # Needed for the filename generation methods provided by the base
+    # class, CCompiler.  NB. whoever instantiates/uses a particular
+    # UnixCCompiler instance should set 'shared_lib_ext' -- we set a
+    # reasonable common default here, but it's not necessarily used on all
+    # Unices!
+
+    src_extensions = [".c", ".C", ".cc", ".cxx", ".cpp", ".m"]
+    obj_extension = ".o"
+    static_lib_extension = ".a"
+    shared_lib_extension = ".so"
+    dylib_lib_extension = ".dylib"
+    xcode_stub_lib_extension = ".tbd"
+    static_lib_format = shared_lib_format = dylib_lib_format = "lib%s%s"
+    xcode_stub_lib_format = dylib_lib_format
+    if sys.platform == "cygwin":
+        exe_extension = ".exe"
+        shared_lib_extension = ".dll.a"
+        dylib_lib_extension = ".dll"
+        dylib_lib_format = "cyg%s%s"
+
+    def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs):
+        """Remove standard library path from rpath"""
+        libraries, library_dirs, runtime_library_dirs = super()._fix_lib_args(
+            libraries, library_dirs, runtime_library_dirs
+        )
+        libdir = sysconfig.get_config_var('LIBDIR')
+        if (
+            runtime_library_dirs
+            and libdir.startswith("/usr/lib")
+            and (libdir in runtime_library_dirs)
+        ):
+            runtime_library_dirs.remove(libdir)
+        return libraries, library_dirs, runtime_library_dirs
+
+    def preprocess(
+        self,
+        source: str | os.PathLike[str],
+        output_file: str | os.PathLike[str] | None = None,
+        macros: list[_Macro] | None = None,
+        include_dirs: list[str] | tuple[str, ...] | None = None,
+        extra_preargs: list[str] | None = None,
+        extra_postargs: Iterable[str] | None = None,
+    ):
+        fixed_args = self._fix_compile_args(None, macros, include_dirs)
+        ignore, macros, include_dirs = fixed_args
+        pp_opts = gen_preprocess_options(macros, include_dirs)
+        pp_args = self.preprocessor + pp_opts
+        if output_file:
+            pp_args.extend(['-o', output_file])
+        if extra_preargs:
+            pp_args[:0] = extra_preargs
+        if extra_postargs:
+            pp_args.extend(extra_postargs)
+        pp_args.append(source)
+
+        # reasons to preprocess:
+        # - force is indicated
+        # - output is directed to stdout
+        # - source file is newer than the target
+        preprocess = self.force or output_file is None or newer(source, output_file)
+        if not preprocess:
+            return
+
+        if output_file:
+            self.mkpath(os.path.dirname(output_file))
+
+        try:
+            self.spawn(pp_args)
+        except DistutilsExecError as msg:
+            raise CompileError(msg)
+
+    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
+        compiler_so = compiler_fixup(self.compiler_so, cc_args + extra_postargs)
+        compiler_so_cxx = compiler_fixup(self.compiler_so_cxx, cc_args + extra_postargs)
+        try:
+            if self.detect_language(src) == 'c++':
+                self.spawn(
+                    compiler_so_cxx + cc_args + [src, '-o', obj] + extra_postargs
+                )
+            else:
+                self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs)
+        except DistutilsExecError as msg:
+            raise CompileError(msg)
+
+    def create_static_lib(
+        self, objects, output_libname, output_dir=None, debug=False, target_lang=None
+    ):
+        objects, output_dir = self._fix_object_args(objects, output_dir)
+
+        output_filename = self.library_filename(output_libname, output_dir=output_dir)
+
+        if self._need_link(objects, output_filename):
+            self.mkpath(os.path.dirname(output_filename))
+            self.spawn(self.archiver + [output_filename] + objects + self.objects)
+
+            # Not many Unices required ranlib anymore -- SunOS 4.x is, I
+            # think the only major Unix that does.  Maybe we need some
+            # platform intelligence here to skip ranlib if it's not
+            # needed -- or maybe Python's configure script took care of
+            # it for us, hence the check for leading colon.
+            if self.ranlib:
+                try:
+                    self.spawn(self.ranlib + [output_filename])
+                except DistutilsExecError as msg:
+                    raise LibError(msg)
+        else:
+            log.debug("skipping %s (up-to-date)", output_filename)
+
+    def link(
+        self,
+        target_desc,
+        objects: list[str] | tuple[str, ...],
+        output_filename,
+        output_dir: str | None = None,
+        libraries: list[str] | tuple[str, ...] | None = None,
+        library_dirs: list[str] | tuple[str, ...] | None = None,
+        runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
+        export_symbols=None,
+        debug=False,
+        extra_preargs=None,
+        extra_postargs=None,
+        build_temp=None,
+        target_lang=None,
+    ):
+        objects, output_dir = self._fix_object_args(objects, output_dir)
+        fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
+        libraries, library_dirs, runtime_library_dirs = fixed_args
+
+        lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
+        if not isinstance(output_dir, (str, type(None))):
+            raise TypeError("'output_dir' must be a string or None")
+        if output_dir is not None:
+            output_filename = os.path.join(output_dir, output_filename)
+
+        if self._need_link(objects, output_filename):
+            ld_args = objects + self.objects + lib_opts + ['-o', output_filename]
+            if debug:
+                ld_args[:0] = ['-g']
+            if extra_preargs:
+                ld_args[:0] = extra_preargs
+            if extra_postargs:
+                ld_args.extend(extra_postargs)
+            self.mkpath(os.path.dirname(output_filename))
+            try:
+                # Select a linker based on context: linker_exe when
+                # building an executable or linker_so (with shared options)
+                # when building a shared library.
+                building_exe = target_desc == base.Compiler.EXECUTABLE
+                target_cxx = target_lang == "c++"
+                linker = (
+                    (self.linker_exe_cxx if target_cxx else self.linker_exe)
+                    if building_exe
+                    else (self.linker_so_cxx if target_cxx else self.linker_so)
+                )[:]
+
+                if target_cxx and self.compiler_cxx:
+                    env, linker_ne = _split_env(linker)
+                    aix, linker_na = _split_aix(linker_ne)
+                    _, compiler_cxx_ne = _split_env(self.compiler_cxx)
+                    _, linker_exe_ne = _split_env(self.linker_exe_cxx)
+
+                    params = _linker_params(linker_na, linker_exe_ne)
+                    linker = env + aix + compiler_cxx_ne + params
+
+                linker = compiler_fixup(linker, ld_args)
+
+                self.spawn(linker + ld_args)
+            except DistutilsExecError as msg:
+                raise LinkError(msg)
+        else:
+            log.debug("skipping %s (up-to-date)", output_filename)
+
+    # -- Miscellaneous methods -----------------------------------------
+    # These are all used by the 'gen_lib_options() function, in
+    # ccompiler.py.
+
+    def library_dir_option(self, dir):
+        return "-L" + dir
+
+    def _is_gcc(self):
+        cc_var = sysconfig.get_config_var("CC")
+        compiler = os.path.basename(shlex.split(cc_var)[0])
+        return "gcc" in compiler or "g++" in compiler
+
+    def runtime_library_dir_option(self, dir: str) -> str | list[str]:  # type: ignore[override] # Fixed in pypa/distutils#339
+        # XXX Hackish, at the very least.  See Python bug #445902:
+        # https://bugs.python.org/issue445902
+        # Linkers on different platforms need different options to
+        # specify that directories need to be added to the list of
+        # directories searched for dependencies when a dynamic library
+        # is sought.  GCC on GNU systems (Linux, FreeBSD, ...) has to
+        # be told to pass the -R option through to the linker, whereas
+        # other compilers and gcc on other systems just know this.
+        # Other compilers may need something slightly different.  At
+        # this time, there's no way to determine this information from
+        # the configuration data stored in the Python installation, so
+        # we use this hack.
+        if sys.platform[:6] == "darwin":
+            from distutils.util import get_macosx_target_ver, split_version
+
+            macosx_target_ver = get_macosx_target_ver()
+            if macosx_target_ver and split_version(macosx_target_ver) >= [10, 5]:
+                return "-Wl,-rpath," + dir
+            else:  # no support for -rpath on earlier macOS versions
+                return "-L" + dir
+        elif sys.platform[:7] == "freebsd":
+            return "-Wl,-rpath=" + dir
+        elif sys.platform[:5] == "hp-ux":
+            return [
+                "-Wl,+s" if self._is_gcc() else "+s",
+                "-L" + dir,
+            ]
+
+        # For all compilers, `-Wl` is the presumed way to pass a
+        # compiler option to the linker
+        if sysconfig.get_config_var("GNULD") == "yes":
+            return consolidate_linker_args([
+                # Force RUNPATH instead of RPATH
+                "-Wl,--enable-new-dtags",
+                "-Wl,-rpath," + dir,
+            ])
+        else:
+            return "-Wl,-R" + dir
+
+    def library_option(self, lib):
+        return "-l" + lib
+
+    @staticmethod
+    def _library_root(dir):
+        """
+        macOS users can specify an alternate SDK using'-isysroot'.
+        Calculate the SDK root if it is specified.
+
+        Note that, as of Xcode 7, Apple SDKs may contain textual stub
+        libraries with .tbd extensions rather than the normal .dylib
+        shared libraries installed in /.  The Apple compiler tool
+        chain handles this transparently but it can cause problems
+        for programs that are being built with an SDK and searching
+        for specific libraries.  Callers of find_library_file need to
+        keep in mind that the base filename of the returned SDK library
+        file might have a different extension from that of the library
+        file installed on the running system, for example:
+          /Applications/Xcode.app/Contents/Developer/Platforms/
+              MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/
+              usr/lib/libedit.tbd
+        vs
+          /usr/lib/libedit.dylib
+        """
+        cflags = sysconfig.get_config_var('CFLAGS')
+        match = re.search(r'-isysroot\s*(\S+)', cflags)
+
+        apply_root = (
+            sys.platform == 'darwin'
+            and match
+            and (
+                dir.startswith('/System/')
+                or (dir.startswith('/usr/') and not dir.startswith('/usr/local/'))
+            )
+        )
+
+        return os.path.join(match.group(1), dir[1:]) if apply_root else dir
+
+    def find_library_file(self, dirs, lib, debug=False):
+        """
+        Second-guess the linker with not much hard
+        data to go on: GCC seems to prefer the shared library, so
+        assume that *all* Unix C compilers do,
+        ignoring even GCC's "-static" option.
+        """
+        lib_names = (
+            self.library_filename(lib, lib_type=type)
+            for type in 'dylib xcode_stub shared static'.split()
+        )
+
+        roots = map(self._library_root, dirs)
+
+        searched = itertools.starmap(os.path.join, itertools.product(roots, lib_names))
+
+        found = filter(os.path.exists, searched)
+
+        # Return None if it could not be found in any dir.
+        return next(found, None)
diff --git a/setuptools/_distutils/compilers/C/zos.py b/setuptools/_distutils/compilers/C/zos.py
new file mode 100644
index 0000000000..681c63166b
--- /dev/null
+++ b/setuptools/_distutils/compilers/C/zos.py
@@ -0,0 +1,230 @@
+"""distutils.zosccompiler
+
+Contains the selection of the c & c++ compilers on z/OS. There are several
+different c compilers on z/OS, all of them are optional, so the correct
+one needs to be chosen based on the users input. This is compatible with
+the following compilers:
+
+IBM C/C++ For Open Enterprise Languages on z/OS 2.0
+IBM Open XL C/C++ 1.1 for z/OS
+IBM XL C/C++ V2.4.1 for z/OS 2.4 and 2.5
+IBM z/OS XL C/C++
+"""
+
+import os
+
+from ... import sysconfig
+from ...errors import DistutilsExecError
+from . import unix
+from .errors import CompileError
+
+_cc_args = {
+    'ibm-openxl': [
+        '-m64',
+        '-fvisibility=default',
+        '-fzos-le-char-mode=ascii',
+        '-fno-short-enums',
+    ],
+    'ibm-xlclang': [
+        '-q64',
+        '-qexportall',
+        '-qascii',
+        '-qstrict',
+        '-qnocsect',
+        '-Wa,asa,goff',
+        '-Wa,xplink',
+        '-qgonumber',
+        '-qenum=int',
+        '-Wc,DLL',
+    ],
+    'ibm-xlc': [
+        '-q64',
+        '-qexportall',
+        '-qascii',
+        '-qstrict',
+        '-qnocsect',
+        '-Wa,asa,goff',
+        '-Wa,xplink',
+        '-qgonumber',
+        '-qenum=int',
+        '-Wc,DLL',
+        '-qlanglvl=extc99',
+    ],
+}
+
+_cxx_args = {
+    'ibm-openxl': [
+        '-m64',
+        '-fvisibility=default',
+        '-fzos-le-char-mode=ascii',
+        '-fno-short-enums',
+    ],
+    'ibm-xlclang': [
+        '-q64',
+        '-qexportall',
+        '-qascii',
+        '-qstrict',
+        '-qnocsect',
+        '-Wa,asa,goff',
+        '-Wa,xplink',
+        '-qgonumber',
+        '-qenum=int',
+        '-Wc,DLL',
+    ],
+    'ibm-xlc': [
+        '-q64',
+        '-qexportall',
+        '-qascii',
+        '-qstrict',
+        '-qnocsect',
+        '-Wa,asa,goff',
+        '-Wa,xplink',
+        '-qgonumber',
+        '-qenum=int',
+        '-Wc,DLL',
+        '-qlanglvl=extended0x',
+    ],
+}
+
+_asm_args = {
+    'ibm-openxl': ['-fasm', '-fno-integrated-as', '-Wa,--ASA', '-Wa,--GOFF'],
+    'ibm-xlclang': [],
+    'ibm-xlc': [],
+}
+
+_ld_args = {
+    'ibm-openxl': [],
+    'ibm-xlclang': ['-Wl,dll', '-q64'],
+    'ibm-xlc': ['-Wl,dll', '-q64'],
+}
+
+
+# Python on z/OS is built with no compiler specific options in it's CFLAGS.
+# But each compiler requires it's own specific options to build successfully,
+# though some of the options are common between them
+class Compiler(unix.Compiler):
+    src_extensions = ['.c', '.C', '.cc', '.cxx', '.cpp', '.m', '.s']
+    _cpp_extensions = ['.cc', '.cpp', '.cxx', '.C']
+    _asm_extensions = ['.s']
+
+    def _get_zos_compiler_name(self):
+        zos_compiler_names = [
+            os.path.basename(binary)
+            for envvar in ('CC', 'CXX', 'LDSHARED')
+            if (binary := os.environ.get(envvar, None))
+        ]
+        if len(zos_compiler_names) == 0:
+            return 'ibm-openxl'
+
+        zos_compilers = {}
+        for compiler in (
+            'ibm-clang',
+            'ibm-clang64',
+            'ibm-clang++',
+            'ibm-clang++64',
+            'clang',
+            'clang++',
+            'clang-14',
+        ):
+            zos_compilers[compiler] = 'ibm-openxl'
+
+        for compiler in ('xlclang', 'xlclang++', 'njsc', 'njsc++'):
+            zos_compilers[compiler] = 'ibm-xlclang'
+
+        for compiler in ('xlc', 'xlC', 'xlc++'):
+            zos_compilers[compiler] = 'ibm-xlc'
+
+        return zos_compilers.get(zos_compiler_names[0], 'ibm-openxl')
+
+    def __init__(self, verbose=False, force=False):
+        super().__init__(verbose, force=force)
+        self.zos_compiler = self._get_zos_compiler_name()
+        sysconfig.customize_compiler(self)
+
+    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
+        local_args = []
+        if ext in self._cpp_extensions:
+            compiler = self.compiler_cxx
+            local_args.extend(_cxx_args[self.zos_compiler])
+        elif ext in self._asm_extensions:
+            compiler = self.compiler_so
+            local_args.extend(_cc_args[self.zos_compiler])
+            local_args.extend(_asm_args[self.zos_compiler])
+        else:
+            compiler = self.compiler_so
+            local_args.extend(_cc_args[self.zos_compiler])
+        local_args.extend(cc_args)
+
+        try:
+            self.spawn(compiler + local_args + [src, '-o', obj] + extra_postargs)
+        except DistutilsExecError as msg:
+            raise CompileError(msg)
+
+    def runtime_library_dir_option(self, dir):
+        return '-L' + dir
+
+    def link(
+        self,
+        target_desc,
+        objects,
+        output_filename,
+        output_dir=None,
+        libraries=None,
+        library_dirs=None,
+        runtime_library_dirs=None,
+        export_symbols=None,
+        debug=False,
+        extra_preargs=None,
+        extra_postargs=None,
+        build_temp=None,
+        target_lang=None,
+    ):
+        # For a built module to use functions from cpython, it needs to use Pythons
+        # side deck file. The side deck is located beside the libpython3.xx.so
+        ldversion = sysconfig.get_config_var('LDVERSION')
+        if sysconfig.python_build:
+            side_deck_path = os.path.join(
+                sysconfig.get_config_var('abs_builddir'),
+                f'libpython{ldversion}.x',
+            )
+        else:
+            side_deck_path = os.path.join(
+                sysconfig.get_config_var('installed_base'),
+                sysconfig.get_config_var('platlibdir'),
+                f'libpython{ldversion}.x',
+            )
+
+        if os.path.exists(side_deck_path):
+            if extra_postargs:
+                extra_postargs.append(side_deck_path)
+            else:
+                extra_postargs = [side_deck_path]
+
+        # Check and replace libraries included side deck files
+        if runtime_library_dirs:
+            for dir in runtime_library_dirs:
+                for library in libraries[:]:
+                    library_side_deck = os.path.join(dir, f'{library}.x')
+                    if os.path.exists(library_side_deck):
+                        libraries.remove(library)
+                        extra_postargs.append(library_side_deck)
+                        break
+
+        # Any required ld args for the given compiler
+        extra_postargs.extend(_ld_args[self.zos_compiler])
+
+        super().link(
+            target_desc,
+            objects,
+            output_filename,
+            output_dir,
+            libraries,
+            library_dirs,
+            runtime_library_dirs,
+            export_symbols,
+            debug,
+            extra_preargs,
+            extra_postargs,
+            build_temp,
+            target_lang,
+        )
diff --git a/setuptools/_distutils/config.py b/setuptools/_distutils/config.py
deleted file mode 100644
index 9a4044adaf..0000000000
--- a/setuptools/_distutils/config.py
+++ /dev/null
@@ -1,139 +0,0 @@
-"""distutils.pypirc
-
-Provides the PyPIRCCommand class, the base class for the command classes
-that uses .pypirc in the distutils.command package.
-"""
-import os
-from configparser import RawConfigParser
-
-from .cmd import Command
-
-DEFAULT_PYPIRC = """\
-[distutils]
-index-servers =
-    pypi
-
-[pypi]
-username:%s
-password:%s
-"""
-
-
-class PyPIRCCommand(Command):
-    """Base command that knows how to handle the .pypirc file"""
-
-    DEFAULT_REPOSITORY = 'https://upload.pypi.org/legacy/'
-    DEFAULT_REALM = 'pypi'
-    repository = None
-    realm = None
-
-    user_options = [
-        ('repository=', 'r', "url of repository [default: %s]" % DEFAULT_REPOSITORY),
-        ('show-response', None, 'display full response text from server'),
-    ]
-
-    boolean_options = ['show-response']
-
-    def _get_rc_file(self):
-        """Returns rc file path."""
-        return os.path.join(os.path.expanduser('~'), '.pypirc')
-
-    def _store_pypirc(self, username, password):
-        """Creates a default .pypirc file."""
-        rc = self._get_rc_file()
-        with os.fdopen(os.open(rc, os.O_CREAT | os.O_WRONLY, 0o600), 'w') as f:
-            f.write(DEFAULT_PYPIRC % (username, password))
-
-    def _read_pypirc(self):  # noqa: C901
-        """Reads the .pypirc file."""
-        rc = self._get_rc_file()
-        if os.path.exists(rc):
-            self.announce('Using PyPI login from %s' % rc)
-            repository = self.repository or self.DEFAULT_REPOSITORY
-
-            config = RawConfigParser()
-            config.read(rc)
-            sections = config.sections()
-            if 'distutils' in sections:
-                # let's get the list of servers
-                index_servers = config.get('distutils', 'index-servers')
-                _servers = [
-                    server.strip()
-                    for server in index_servers.split('\n')
-                    if server.strip() != ''
-                ]
-                if _servers == []:
-                    # nothing set, let's try to get the default pypi
-                    if 'pypi' in sections:
-                        _servers = ['pypi']
-                    else:
-                        # the file is not properly defined, returning
-                        # an empty dict
-                        return {}
-                for server in _servers:
-                    current = {'server': server}
-                    current['username'] = config.get(server, 'username')
-
-                    # optional params
-                    for key, default in (
-                        ('repository', self.DEFAULT_REPOSITORY),
-                        ('realm', self.DEFAULT_REALM),
-                        ('password', None),
-                    ):
-                        if config.has_option(server, key):
-                            current[key] = config.get(server, key)
-                        else:
-                            current[key] = default
-
-                    # work around people having "repository" for the "pypi"
-                    # section of their config set to the HTTP (rather than
-                    # HTTPS) URL
-                    if server == 'pypi' and repository in (
-                        self.DEFAULT_REPOSITORY,
-                        'pypi',
-                    ):
-                        current['repository'] = self.DEFAULT_REPOSITORY
-                        return current
-
-                    if (
-                        current['server'] == repository
-                        or current['repository'] == repository
-                    ):
-                        return current
-            elif 'server-login' in sections:
-                # old format
-                server = 'server-login'
-                if config.has_option(server, 'repository'):
-                    repository = config.get(server, 'repository')
-                else:
-                    repository = self.DEFAULT_REPOSITORY
-                return {
-                    'username': config.get(server, 'username'),
-                    'password': config.get(server, 'password'),
-                    'repository': repository,
-                    'server': server,
-                    'realm': self.DEFAULT_REALM,
-                }
-
-        return {}
-
-    def _read_pypi_response(self, response):
-        """Read and decode a PyPI HTTP response."""
-        import cgi
-
-        content_type = response.getheader('content-type', 'text/plain')
-        encoding = cgi.parse_header(content_type)[1].get('charset', 'ascii')
-        return response.read().decode(encoding)
-
-    def initialize_options(self):
-        """Initialize options."""
-        self.repository = None
-        self.realm = None
-        self.show_response = 0
-
-    def finalize_options(self):
-        """Finalizes options."""
-        if self.repository is None:
-            self.repository = self.DEFAULT_REPOSITORY
-        if self.realm is None:
-            self.realm = self.DEFAULT_REALM
diff --git a/setuptools/_distutils/core.py b/setuptools/_distutils/core.py
index 05d2971994..bd62546bdd 100644
--- a/setuptools/_distutils/core.py
+++ b/setuptools/_distutils/core.py
@@ -6,26 +6,27 @@
 really defined in distutils.dist and distutils.cmd.
 """
 
+from __future__ import annotations
+
 import os
 import sys
 import tokenize
+from collections.abc import Iterable
 
+from .cmd import Command
 from .debug import DEBUG
+
+# Mainly import these so setup scripts can "from distutils.core import" them.
+from .dist import Distribution
 from .errors import (
-    DistutilsSetupError,
-    DistutilsError,
     CCompilerError,
     DistutilsArgError,
+    DistutilsError,
+    DistutilsSetupError,
 )
-
-# Mainly import these so setup scripts can "from distutils.core import" them.
-from .dist import Distribution
-from .cmd import Command
-from .config import PyPIRCCommand
 from .extension import Extension
 
-
-__all__ = ['Distribution', 'Command', 'PyPIRCCommand', 'Extension', 'setup']
+__all__ = ['Distribution', 'Command', 'Extension', 'setup']
 
 # This is a barebones help message generated displayed when the user
 # runs the setup script with no arguments at all.  More useful help
@@ -147,7 +148,7 @@ class found in 'cmdclass' is used in place of the default, which is
         _setup_distribution = dist = klass(attrs)
     except DistutilsSetupError as msg:
         if 'name' not in attrs:
-            raise SystemExit("error in setup command: %s" % msg)
+            raise SystemExit(f"error in setup command: {msg}")
         else:
             raise SystemExit("error in {} setup command: {}".format(attrs['name'], msg))
 
@@ -171,7 +172,7 @@ class found in 'cmdclass' is used in place of the default, which is
     try:
         ok = dist.parse_command_line()
     except DistutilsArgError as msg:
-        raise SystemExit(gen_usage(dist.script_name) + "\nerror: %s" % msg)
+        raise SystemExit(gen_usage(dist.script_name) + f"\nerror: {msg}")
 
     if DEBUG:
         print("options (after parsing command line):")
@@ -203,10 +204,10 @@ def run_commands(dist):
         raise SystemExit("interrupted")
     except OSError as exc:
         if DEBUG:
-            sys.stderr.write("error: {}\n".format(exc))
+            sys.stderr.write(f"error: {exc}\n")
             raise
         else:
-            raise SystemExit("error: {}".format(exc))
+            raise SystemExit(f"error: {exc}")
 
     except (DistutilsError, CCompilerError) as msg:
         if DEBUG:
@@ -217,7 +218,7 @@ def run_commands(dist):
     return dist
 
 
-def run_setup(script_name, script_args=None, stop_after="run"):
+def run_setup(script_name, script_args: Iterable[str] | None = None, stop_after="run"):
     """Run a setup script in a somewhat controlled environment, and
     return the Distribution instance that drives things.  This is useful
     if you need to find out the distribution meta-data (passed as
@@ -249,7 +250,7 @@ def run_setup(script_name, script_args=None, stop_after="run"):
     used to drive the Distutils.
     """
     if stop_after not in ('init', 'config', 'commandline', 'run'):
-        raise ValueError("invalid value for 'stop_after': {!r}".format(stop_after))
+        raise ValueError(f"invalid value for 'stop_after': {stop_after!r}")
 
     global _setup_stop_after, _setup_distribution
     _setup_stop_after = stop_after
@@ -275,11 +276,8 @@ def run_setup(script_name, script_args=None, stop_after="run"):
 
     if _setup_distribution is None:
         raise RuntimeError(
-            (
-                "'distutils.core.setup()' was never called -- "
-                "perhaps '%s' is not a Distutils setup script?"
-            )
-            % script_name
+            "'distutils.core.setup()' was never called -- "
+            f"perhaps '{script_name}' is not a Distutils setup script?"
         )
 
     # I wonder if the setup script's namespace -- g and l -- would be of
diff --git a/setuptools/_distutils/cygwinccompiler.py b/setuptools/_distutils/cygwinccompiler.py
index 47efa377c5..de89e3cd84 100644
--- a/setuptools/_distutils/cygwinccompiler.py
+++ b/setuptools/_distutils/cygwinccompiler.py
@@ -1,352 +1,27 @@
-"""distutils.cygwinccompiler
-
-Provides the CygwinCCompiler class, a subclass of UnixCCompiler that
-handles the Cygwin port of the GNU C compiler to Windows.  It also contains
-the Mingw32CCompiler class which handles the mingw32 port of GCC (same as
-cygwin in no-cygwin mode).
-"""
-
-import os
-import re
-import sys
-import copy
-import shlex
-import warnings
-from subprocess import check_output
-
-from .unixccompiler import UnixCCompiler
-from .file_util import write_file
-from .errors import (
-    DistutilsExecError,
-    DistutilsPlatformError,
-    CCompilerError,
-    CompileError,
+from .compilers.C import cygwin
+from .compilers.C.cygwin import (
+    CONFIG_H_NOTOK,
+    CONFIG_H_OK,
+    CONFIG_H_UNCERTAIN,
+    check_config_h,
+    get_msvcr,
+    is_cygwincc,
 )
-from .version import LooseVersion, suppress_known_deprecation
-from ._collections import RangeMap
-
-
-_msvcr_lookup = RangeMap.left(
-    {
-        # MSVC 7.0
-        1300: ['msvcr70'],
-        # MSVC 7.1
-        1310: ['msvcr71'],
-        # VS2005 / MSVC 8.0
-        1400: ['msvcr80'],
-        # VS2008 / MSVC 9.0
-        1500: ['msvcr90'],
-        # VS2010 / MSVC 10.0
-        1600: ['msvcr100'],
-        # VS2012 / MSVC 11.0
-        1700: ['msvcr110'],
-        # VS2013 / MSVC 12.0
-        1800: ['msvcr120'],
-        # VS2015 / MSVC 14.0
-        1900: ['vcruntime140'],
-        2000: RangeMap.undefined_value,
-    },
-)
-
-
-def get_msvcr():
-    """Include the appropriate MSVC runtime library if Python was built
-    with MSVC 7.0 or later.
-    """
-    match = re.search(r'MSC v\.(\d{4})', sys.version)
-    try:
-        msc_ver = int(match.group(1))
-    except AttributeError:
-        return
-    try:
-        return _msvcr_lookup[msc_ver]
-    except KeyError:
-        raise ValueError("Unknown MS Compiler version %s " % msc_ver)
-
-
-_runtime_library_dirs_msg = (
-    "Unable to set runtime library search path on Windows, "
-    "usually indicated by `runtime_library_dirs` parameter to Extension"
-)
-
-
-class CygwinCCompiler(UnixCCompiler):
-    """Handles the Cygwin port of the GNU C compiler to Windows."""
-
-    compiler_type = 'cygwin'
-    obj_extension = ".o"
-    static_lib_extension = ".a"
-    shared_lib_extension = ".dll.a"
-    dylib_lib_extension = ".dll"
-    static_lib_format = "lib%s%s"
-    shared_lib_format = "lib%s%s"
-    dylib_lib_format = "cyg%s%s"
-    exe_extension = ".exe"
-
-    def __init__(self, verbose=0, dry_run=0, force=0):
-        super().__init__(verbose, dry_run, force)
-
-        status, details = check_config_h()
-        self.debug_print(
-            "Python's GCC status: {} (details: {})".format(status, details)
-        )
-        if status is not CONFIG_H_OK:
-            self.warn(
-                "Python's pyconfig.h doesn't seem to support your compiler. "
-                "Reason: %s. "
-                "Compiling may fail because of undefined preprocessor macros." % details
-            )
-
-        self.cc = os.environ.get('CC', 'gcc')
-        self.cxx = os.environ.get('CXX', 'g++')
-
-        self.linker_dll = self.cc
-        shared_option = "-shared"
-
-        self.set_executables(
-            compiler='%s -mcygwin -O -Wall' % self.cc,
-            compiler_so='%s -mcygwin -mdll -O -Wall' % self.cc,
-            compiler_cxx='%s -mcygwin -O -Wall' % self.cxx,
-            linker_exe='%s -mcygwin' % self.cc,
-            linker_so=('{} -mcygwin {}'.format(self.linker_dll, shared_option)),
-        )
-
-        # Include the appropriate MSVC runtime library if Python was built
-        # with MSVC 7.0 or later.
-        self.dll_libraries = get_msvcr()
-
-    @property
-    def gcc_version(self):
-        # Older numpy depended on this existing to check for ancient
-        # gcc versions. This doesn't make much sense with clang etc so
-        # just hardcode to something recent.
-        # https://github.com/numpy/numpy/pull/20333
-        warnings.warn(
-            "gcc_version attribute of CygwinCCompiler is deprecated. "
-            "Instead of returning actual gcc version a fixed value 11.2.0 is returned.",
-            DeprecationWarning,
-            stacklevel=2,
-        )
-        with suppress_known_deprecation():
-            return LooseVersion("11.2.0")
-
-    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
-        """Compiles the source by spawning GCC and windres if needed."""
-        if ext in ('.rc', '.res'):
-            # gcc needs '.res' and '.rc' compiled to object files !!!
-            try:
-                self.spawn(["windres", "-i", src, "-o", obj])
-            except DistutilsExecError as msg:
-                raise CompileError(msg)
-        else:  # for other files use the C-compiler
-            try:
-                self.spawn(
-                    self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs
-                )
-            except DistutilsExecError as msg:
-                raise CompileError(msg)
-
-    def link(
-        self,
-        target_desc,
-        objects,
-        output_filename,
-        output_dir=None,
-        libraries=None,
-        library_dirs=None,
-        runtime_library_dirs=None,
-        export_symbols=None,
-        debug=0,
-        extra_preargs=None,
-        extra_postargs=None,
-        build_temp=None,
-        target_lang=None,
-    ):
-        """Link the objects."""
-        # use separate copies, so we can modify the lists
-        extra_preargs = copy.copy(extra_preargs or [])
-        libraries = copy.copy(libraries or [])
-        objects = copy.copy(objects or [])
-
-        if runtime_library_dirs:
-            self.warn(_runtime_library_dirs_msg)
-
-        # Additional libraries
-        libraries.extend(self.dll_libraries)
-
-        # handle export symbols by creating a def-file
-        # with executables this only works with gcc/ld as linker
-        if (export_symbols is not None) and (
-            target_desc != self.EXECUTABLE or self.linker_dll == "gcc"
-        ):
-            # (The linker doesn't do anything if output is up-to-date.
-            # So it would probably better to check if we really need this,
-            # but for this we had to insert some unchanged parts of
-            # UnixCCompiler, and this is not what we want.)
-
-            # we want to put some files in the same directory as the
-            # object files are, build_temp doesn't help much
-            # where are the object files
-            temp_dir = os.path.dirname(objects[0])
-            # name of dll to give the helper files the same base name
-            (dll_name, dll_extension) = os.path.splitext(
-                os.path.basename(output_filename)
-            )
-
-            # generate the filenames for these files
-            def_file = os.path.join(temp_dir, dll_name + ".def")
-
-            # Generate .def file
-            contents = ["LIBRARY %s" % os.path.basename(output_filename), "EXPORTS"]
-            for sym in export_symbols:
-                contents.append(sym)
-            self.execute(write_file, (def_file, contents), "writing %s" % def_file)
-
-            # next add options for def-file
-
-            # for gcc/ld the def-file is specified as any object files
-            objects.append(def_file)
-
-        # end: if ((export_symbols is not None) and
-        #        (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
-
-        # who wants symbols and a many times larger output file
-        # should explicitly switch the debug mode on
-        # otherwise we let ld strip the output file
-        # (On my machine: 10KiB < stripped_file < ??100KiB
-        #   unstripped_file = stripped_file + XXX KiB
-        #  ( XXX=254 for a typical python extension))
-        if not debug:
-            extra_preargs.append("-s")
-
-        UnixCCompiler.link(
-            self,
-            target_desc,
-            objects,
-            output_filename,
-            output_dir,
-            libraries,
-            library_dirs,
-            runtime_library_dirs,
-            None,  # export_symbols, we do this in our def-file
-            debug,
-            extra_preargs,
-            extra_postargs,
-            build_temp,
-            target_lang,
-        )
-
-    def runtime_library_dir_option(self, dir):
-        # cygwin doesn't support rpath. While in theory we could error
-        # out like MSVC does, code might expect it to work like on Unix, so
-        # just warn and hope for the best.
-        self.warn(_runtime_library_dirs_msg)
-        return []
-
-    # -- Miscellaneous methods -----------------------------------------
-
-    def _make_out_path(self, output_dir, strip_dir, src_name):
-        # use normcase to make sure '.rc' is really '.rc' and not '.RC'
-        norm_src_name = os.path.normcase(src_name)
-        return super()._make_out_path(output_dir, strip_dir, norm_src_name)
-
-    @property
-    def out_extensions(self):
-        """
-        Add support for rc and res files.
-        """
-        return {
-            **super().out_extensions,
-            **{ext: ext + self.obj_extension for ext in ('.res', '.rc')},
-        }
-
-
-# the same as cygwin plus some additional parameters
-class Mingw32CCompiler(CygwinCCompiler):
-    """Handles the Mingw32 port of the GNU C compiler to Windows."""
-
-    compiler_type = 'mingw32'
-
-    def __init__(self, verbose=0, dry_run=0, force=0):
-        super().__init__(verbose, dry_run, force)
-
-        shared_option = "-shared"
-
-        if is_cygwincc(self.cc):
-            raise CCompilerError('Cygwin gcc cannot be used with --compiler=mingw32')
-
-        self.set_executables(
-            compiler='%s -O -Wall' % self.cc,
-            compiler_so='%s -mdll -O -Wall' % self.cc,
-            compiler_cxx='%s -O -Wall' % self.cxx,
-            linker_exe='%s' % self.cc,
-            linker_so='{} {}'.format(self.linker_dll, shared_option),
-        )
-
-    def runtime_library_dir_option(self, dir):
-        raise DistutilsPlatformError(_runtime_library_dirs_msg)
-
-
-# Because these compilers aren't configured in Python's pyconfig.h file by
-# default, we should at least warn the user if he is using an unmodified
-# version.
-
-CONFIG_H_OK = "ok"
-CONFIG_H_NOTOK = "not ok"
-CONFIG_H_UNCERTAIN = "uncertain"
-
-
-def check_config_h():
-    """Check if the current Python installation appears amenable to building
-    extensions with GCC.
-
-    Returns a tuple (status, details), where 'status' is one of the following
-    constants:
-
-    - CONFIG_H_OK: all is well, go ahead and compile
-    - CONFIG_H_NOTOK: doesn't look good
-    - CONFIG_H_UNCERTAIN: not sure -- unable to read pyconfig.h
-
-    'details' is a human-readable string explaining the situation.
-
-    Note there are two ways to conclude "OK": either 'sys.version' contains
-    the string "GCC" (implying that this Python was built with GCC), or the
-    installed "pyconfig.h" contains the string "__GNUC__".
-    """
-
-    # XXX since this function also checks sys.version, it's not strictly a
-    # "pyconfig.h" check -- should probably be renamed...
-
-    from distutils import sysconfig
-
-    # if sys.version contains GCC then python was compiled with GCC, and the
-    # pyconfig.h file should be OK
-    if "GCC" in sys.version:
-        return CONFIG_H_OK, "sys.version mentions 'GCC'"
-
-    # Clang would also work
-    if "Clang" in sys.version:
-        return CONFIG_H_OK, "sys.version mentions 'Clang'"
 
-    # let's see if __GNUC__ is mentioned in python.h
-    fn = sysconfig.get_config_h_filename()
-    try:
-        config_h = open(fn)
-        try:
-            if "__GNUC__" in config_h.read():
-                return CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn
-            else:
-                return CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn
-        finally:
-            config_h.close()
-    except OSError as exc:
-        return (CONFIG_H_UNCERTAIN, "couldn't read '{}': {}".format(fn, exc.strerror))
+__all__ = [
+    'CONFIG_H_NOTOK',
+    'CONFIG_H_OK',
+    'CONFIG_H_UNCERTAIN',
+    'CygwinCCompiler',
+    'Mingw32CCompiler',
+    'check_config_h',
+    'get_msvcr',
+    'is_cygwincc',
+]
 
 
-def is_cygwincc(cc):
-    '''Try to determine if the compiler that would be used is from cygwin.'''
-    out_string = check_output(shlex.split(cc) + ['-dumpmachine'])
-    return out_string.strip().endswith(b'cygwin')
+CygwinCCompiler = cygwin.Compiler
+Mingw32CCompiler = cygwin.MinGW32Compiler
 
 
 get_versions = None
diff --git a/setuptools/_distutils/dep_util.py b/setuptools/_distutils/dep_util.py
index 48da8641c6..09a8a2e126 100644
--- a/setuptools/_distutils/dep_util.py
+++ b/setuptools/_distutils/dep_util.py
@@ -1,96 +1,14 @@
-"""distutils.dep_util
+import warnings
 
-Utility functions for simple, timestamp-based dependency of files
-and groups of files; also, function based entirely on such
-timestamp dependency analysis."""
+from . import _modified
 
-import os
-from .errors import DistutilsFileError
 
-
-def newer(source, target):
-    """Return true if 'source' exists and is more recently modified than
-    'target', or if 'source' exists and 'target' doesn't.  Return false if
-    both exist and 'target' is the same age or younger than 'source'.
-    Raise DistutilsFileError if 'source' does not exist.
-    """
-    if not os.path.exists(source):
-        raise DistutilsFileError("file '%s' does not exist" % os.path.abspath(source))
-    if not os.path.exists(target):
-        return 1
-
-    from stat import ST_MTIME
-
-    mtime1 = os.stat(source)[ST_MTIME]
-    mtime2 = os.stat(target)[ST_MTIME]
-
-    return mtime1 > mtime2
-
-
-# newer ()
-
-
-def newer_pairwise(sources, targets):
-    """Walk two filename lists in parallel, testing if each source is newer
-    than its corresponding target.  Return a pair of lists (sources,
-    targets) where source is newer than target, according to the semantics
-    of 'newer()'.
-    """
-    if len(sources) != len(targets):
-        raise ValueError("'sources' and 'targets' must be same length")
-
-    # build a pair of lists (sources, targets) where  source is newer
-    n_sources = []
-    n_targets = []
-    for i in range(len(sources)):
-        if newer(sources[i], targets[i]):
-            n_sources.append(sources[i])
-            n_targets.append(targets[i])
-
-    return (n_sources, n_targets)
-
-
-# newer_pairwise ()
-
-
-def newer_group(sources, target, missing='error'):
-    """Return true if 'target' is out-of-date with respect to any file
-    listed in 'sources'.  In other words, if 'target' exists and is newer
-    than every file in 'sources', return false; otherwise return true.
-    'missing' controls what we do when a source file is missing; the
-    default ("error") is to blow up with an OSError from inside 'stat()';
-    if it is "ignore", we silently drop any missing source files; if it is
-    "newer", any missing source files make us assume that 'target' is
-    out-of-date (this is handy in "dry-run" mode: it'll make you pretend to
-    carry out commands that wouldn't work because inputs are missing, but
-    that doesn't matter because you're not actually going to run the
-    commands).
-    """
-    # If the target doesn't even exist, then it's definitely out-of-date.
-    if not os.path.exists(target):
-        return 1
-
-    # Otherwise we have to find out the hard way: if *any* source file
-    # is more recent than 'target', then 'target' is out-of-date and
-    # we can immediately return true.  If we fall through to the end
-    # of the loop, then 'target' is up-to-date and we return false.
-    from stat import ST_MTIME
-
-    target_mtime = os.stat(target)[ST_MTIME]
-    for source in sources:
-        if not os.path.exists(source):
-            if missing == 'error':  # blow up when we stat() the file
-                pass
-            elif missing == 'ignore':  # missing source dropped from
-                continue  # target's dependency list
-            elif missing == 'newer':  # missing source means target is
-                return 1  # out-of-date
-
-        source_mtime = os.stat(source)[ST_MTIME]
-        if source_mtime > target_mtime:
-            return 1
-    else:
-        return 0
-
-
-# newer_group ()
+def __getattr__(name):
+    if name not in ['newer', 'newer_group', 'newer_pairwise']:
+        raise AttributeError(name)
+    warnings.warn(
+        "dep_util is Deprecated. Use functions from setuptools instead.",
+        DeprecationWarning,
+        stacklevel=2,
+    )
+    return getattr(_modified, name)
diff --git a/setuptools/_distutils/dir_util.py b/setuptools/_distutils/dir_util.py
index 23dc3392a2..61b4575aa0 100644
--- a/setuptools/_distutils/dir_util.py
+++ b/setuptools/_distutils/dir_util.py
@@ -2,117 +2,106 @@
 
 Utility functions for manipulating directories and directory trees."""
 
+import functools
+import itertools
 import os
-import errno
-from .errors import DistutilsInternalError, DistutilsFileError
+import pathlib
+
+from . import file_util
 from ._log import log
+from .errors import DistutilsFileError, DistutilsInternalError
 
-# cache for by mkpath() -- in addition to cheapening redundant calls,
-# eliminates redundant "creating /foo/bar/baz" messages in dry-run mode
-_path_created = {}
 
+class SkipRepeatAbsolutePaths(set):
+    """
+    Cache for mkpath.
 
-def mkpath(name, mode=0o777, verbose=1, dry_run=0):  # noqa: C901
-    """Create a directory and any missing ancestor directories.
+    In addition to cheapening redundant calls, eliminates redundant
+    "creating /foo/bar/baz" messages in dry-run mode.
+    """
 
-    If the directory already exists (or if 'name' is the empty string, which
-    means the current directory, which of course exists), then do nothing.
-    Raise DistutilsFileError if unable to create some directory along the way
-    (eg. some sub-path exists, but is a file rather than a directory).
-    If 'verbose' is true, print a one-line summary of each mkdir to stdout.
-    Return the list of directories actually created.
+    def __init__(self):
+        SkipRepeatAbsolutePaths.instance = self
 
-    os.makedirs is not used because:
+    @classmethod
+    def clear(cls):
+        super(cls, cls.instance).clear()
 
-    a) It's new to Python 1.5.2, and
-    b) it blows up if the directory already exists (in which case it should
-       silently succeed).
-    """
+    def wrap(self, func):
+        @functools.wraps(func)
+        def wrapper(path, *args, **kwargs):
+            if path.absolute() in self:
+                return
+            result = func(path, *args, **kwargs)
+            self.add(path.absolute())
+            return result
 
-    global _path_created
+        return wrapper
 
-    # Detect a common bug -- name is None
-    if not isinstance(name, str):
-        raise DistutilsInternalError(
-            "mkpath: 'name' must be a string (got {!r})".format(name)
-        )
 
-    # XXX what's the better way to handle verbosity? print as we create
-    # each directory in the path (the current behaviour), or only announce
-    # the creation of the whole path? (quite easy to do the latter since
-    # we're not using a recursive algorithm)
+# Python 3.8 compatibility
+wrapper = SkipRepeatAbsolutePaths().wrap
 
-    name = os.path.normpath(name)
-    created_dirs = []
-    if os.path.isdir(name) or name == '':
-        return created_dirs
-    if _path_created.get(os.path.abspath(name)):
-        return created_dirs
 
-    (head, tail) = os.path.split(name)
-    tails = [tail]  # stack of lone dirs to create
+@functools.singledispatch
+@wrapper
+def mkpath(name: pathlib.Path, mode=0o777, verbose=True) -> None:
+    """Create a directory and any missing ancestor directories.
 
-    while head and tail and not os.path.isdir(head):
-        (head, tail) = os.path.split(head)
-        tails.insert(0, tail)  # push next higher dir onto stack
+    If the directory already exists (or if 'name' is the empty string, which
+    means the current directory, which of course exists), then do nothing.
+    Raise DistutilsFileError if unable to create some directory along the way
+    (eg. some sub-path exists, but is a file rather than a directory).
+    If 'verbose' is true, log the directory created.
+    """
+    if verbose and not name.is_dir():
+        log.info("creating %s", name)
 
-    # now 'head' contains the deepest directory that already exists
-    # (that is, the child of 'head' in 'name' is the highest directory
-    # that does *not* exist)
-    for d in tails:
-        # print "head = %s, d = %s: " % (head, d),
-        head = os.path.join(head, d)
-        abs_head = os.path.abspath(head)
+    try:
+        name.mkdir(mode=mode, parents=True, exist_ok=True)
+    except OSError as exc:
+        raise DistutilsFileError(f"could not create '{name}': {exc.args[-1]}")
 
-        if _path_created.get(abs_head):
-            continue
 
-        if verbose >= 1:
-            log.info("creating %s", head)
+@mkpath.register
+def _(name: str, *args, **kwargs):
+    return mkpath(pathlib.Path(name), *args, **kwargs)
 
-        if not dry_run:
-            try:
-                os.mkdir(head, mode)
-            except OSError as exc:
-                if not (exc.errno == errno.EEXIST and os.path.isdir(head)):
-                    raise DistutilsFileError(
-                        "could not create '{}': {}".format(head, exc.args[-1])
-                    )
-            created_dirs.append(head)
 
-        _path_created[abs_head] = 1
-    return created_dirs
+@mkpath.register
+def _(name: None, *args, **kwargs):
+    """
+    Detect a common bug -- name is None.
+    """
+    raise DistutilsInternalError(f"mkpath: 'name' must be a string (got {name!r})")
 
 
-def create_tree(base_dir, files, mode=0o777, verbose=1, dry_run=0):
+def create_tree(base_dir, files, mode=0o777, verbose=True):
     """Create all the empty directories under 'base_dir' needed to put 'files'
     there.
 
     'base_dir' is just the name of a directory which doesn't necessarily
     exist yet; 'files' is a list of filenames to be interpreted relative to
     'base_dir'.  'base_dir' + the directory portion of every file in 'files'
-    will be created if it doesn't already exist.  'mode', 'verbose' and
-    'dry_run' flags are as for 'mkpath()'.
+    will be created if it doesn't already exist.  'mode' and 'verbose'
+    flags are as for 'mkpath()'.
     """
     # First get the list of directories to create
-    need_dir = set()
-    for file in files:
-        need_dir.add(os.path.join(base_dir, os.path.dirname(file)))
+    need_dir = set(os.path.join(base_dir, os.path.dirname(file)) for file in files)
 
     # Now create them
     for dir in sorted(need_dir):
-        mkpath(dir, mode, verbose=verbose, dry_run=dry_run)
+        mkpath(dir, mode, verbose=verbose)
 
 
-def copy_tree(  # noqa: C901
+def copy_tree(
     src,
     dst,
-    preserve_mode=1,
-    preserve_times=1,
-    preserve_symlinks=0,
-    update=0,
-    verbose=1,
-    dry_run=0,
+    preserve_mode=True,
+    preserve_times=True,
+    preserve_symlinks=False,
+    update=False,
+    verbose=True,
 ):
     """Copy an entire directory tree 'src' to a new location 'dst'.
 
@@ -122,7 +111,7 @@ def copy_tree(  # noqa: C901
     file in 'src' is copied to 'dst', and directories under 'src' are
     recursively copied to 'dst'.  Return the list of files that were
     copied or might have been copied, using their output name.  The
-    return value is unaffected by 'update' or 'dry_run': it is simply
+    return value is unaffected by 'update': it is simply
     the list of all files under 'src', with the names changed to be
     under 'dst'.
 
@@ -133,67 +122,73 @@ def copy_tree(  # noqa: C901
     (the default), the destination of the symlink will be copied.
     'update' and 'verbose' are the same as for 'copy_file'.
     """
-    from distutils.file_util import copy_file
-
-    if not dry_run and not os.path.isdir(src):
-        raise DistutilsFileError("cannot copy tree '%s': not a directory" % src)
+    if not os.path.isdir(src):
+        raise DistutilsFileError(f"cannot copy tree '{src}': not a directory")
     try:
         names = os.listdir(src)
     except OSError as e:
-        if dry_run:
-            names = []
-        else:
-            raise DistutilsFileError(
-                "error listing files in '{}': {}".format(src, e.strerror)
-            )
-
-    if not dry_run:
-        mkpath(dst, verbose=verbose)
-
-    outputs = []
-
-    for n in names:
-        src_name = os.path.join(src, n)
-        dst_name = os.path.join(dst, n)
-
-        if n.startswith('.nfs'):
-            # skip NFS rename files
-            continue
-
-        if preserve_symlinks and os.path.islink(src_name):
-            link_dest = os.readlink(src_name)
-            if verbose >= 1:
-                log.info("linking %s -> %s", dst_name, link_dest)
-            if not dry_run:
-                os.symlink(link_dest, dst_name)
-            outputs.append(dst_name)
-
-        elif os.path.isdir(src_name):
-            outputs.extend(
-                copy_tree(
-                    src_name,
-                    dst_name,
-                    preserve_mode,
-                    preserve_times,
-                    preserve_symlinks,
-                    update,
-                    verbose=verbose,
-                    dry_run=dry_run,
-                )
-            )
-        else:
-            copy_file(
-                src_name,
-                dst_name,
-                preserve_mode,
-                preserve_times,
-                update,
-                verbose=verbose,
-                dry_run=dry_run,
-            )
-            outputs.append(dst_name)
+        raise DistutilsFileError(f"error listing files in '{src}': {e.strerror}")
+
+    mkpath(dst, verbose=verbose)
+
+    copy_one = functools.partial(
+        _copy_one,
+        src=src,
+        dst=dst,
+        preserve_symlinks=preserve_symlinks,
+        verbose=verbose,
+        preserve_mode=preserve_mode,
+        preserve_times=preserve_times,
+        update=update,
+    )
+    return list(itertools.chain.from_iterable(map(copy_one, names)))
+
+
+def _copy_one(
+    name,
+    *,
+    src,
+    dst,
+    preserve_symlinks,
+    verbose,
+    preserve_mode,
+    preserve_times,
+    update,
+):
+    src_name = os.path.join(src, name)
+    dst_name = os.path.join(dst, name)
+
+    if name.startswith('.nfs'):
+        # skip NFS rename files
+        return
 
-    return outputs
+    if preserve_symlinks and os.path.islink(src_name):
+        link_dest = os.readlink(src_name)
+        if verbose >= 1:
+            log.info("linking %s -> %s", dst_name, link_dest)
+        os.symlink(link_dest, dst_name)
+        yield dst_name
+
+    elif os.path.isdir(src_name):
+        yield from copy_tree(
+            src_name,
+            dst_name,
+            preserve_mode,
+            preserve_times,
+            preserve_symlinks,
+            update,
+            verbose=verbose,
+        )
+    else:
+        file_util.copy_file(
+            src_name,
+            dst_name,
+            preserve_mode,
+            preserve_times,
+            update,
+            verbose=verbose,
+        )
+        yield dst_name
 
 
 def _build_cmdtuple(path, cmdtuples):
@@ -207,27 +202,21 @@ def _build_cmdtuple(path, cmdtuples):
     cmdtuples.append((os.rmdir, path))
 
 
-def remove_tree(directory, verbose=1, dry_run=0):
+def remove_tree(directory, verbose=True):
     """Recursively remove an entire directory tree.
 
     Any errors are ignored (apart from being reported to stdout if 'verbose'
     is true).
     """
-    global _path_created
-
     if verbose >= 1:
         log.info("removing '%s' (and everything under it)", directory)
-    if dry_run:
-        return
     cmdtuples = []
     _build_cmdtuple(directory, cmdtuples)
     for cmd in cmdtuples:
         try:
             cmd[0](cmd[1])
-            # remove dir from cache if it's already there
-            abspath = os.path.abspath(cmd[1])
-            if abspath in _path_created:
-                _path_created.pop(abspath)
+            # Clear the cache
+            SkipRepeatAbsolutePaths.clear()
         except OSError as exc:
             log.warning("error removing %s: %s", directory, exc)
 
diff --git a/setuptools/_distutils/dist.py b/setuptools/_distutils/dist.py
index 7c0f0e5b78..e04e487b58 100644
--- a/setuptools/_distutils/dist.py
+++ b/setuptools/_distutils/dist.py
@@ -4,29 +4,53 @@
 being built/installed/distributed.
 """
 
-import sys
-import os
-import re
-import pathlib
+from __future__ import annotations
+
 import contextlib
 import logging
+import os
+import pathlib
+import re
+import sys
+import warnings
+from collections.abc import Iterable, MutableMapping
 from email import message_from_file
+from typing import (
+    IO,
+    TYPE_CHECKING,
+    Any,
+    ClassVar,
+    Literal,
+    TypeVar,
+    Union,
+    overload,
+)
 
-try:
-    import warnings
-except ImportError:
-    warnings = None
+from packaging.utils import canonicalize_name, canonicalize_version
 
+from ._log import log
+from .debug import DEBUG
 from .errors import (
-    DistutilsOptionError,
-    DistutilsModuleError,
     DistutilsArgError,
     DistutilsClassError,
+    DistutilsModuleError,
+    DistutilsOptionError,
 )
 from .fancy_getopt import FancyGetopt, translate_longopt
-from .util import check_environ, strtobool, rfc822_escape
-from ._log import log
-from .debug import DEBUG
+from .util import check_environ, rfc822_escape, strtobool
+
+if TYPE_CHECKING:
+    from _typeshed import SupportsWrite
+    from typing_extensions import TypeAlias
+
+    # type-only import because of mutual dependence between these modules
+    from .cmd import Command
+
+_CommandT = TypeVar("_CommandT", bound="Command")
+_OptionsList: TypeAlias = list[
+    Union[tuple[str, Union[str, None], str, int], tuple[str, Union[str, None], str]]
+]
+
 
 # Regex to define acceptable Distutils command names.  This is not *quite*
 # the same as a Python NAME -- I don't allow leading underscores.  The fact
@@ -35,7 +59,7 @@
 command_re = re.compile(r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
 
 
-def _ensure_list(value, fieldname):
+def _ensure_list(value: str | Iterable[str], fieldname) -> str | list[str]:
     if isinstance(value, str):
         # a string containing comma separated values is okay.  It will
         # be converted to a list by Distribution.finalize_options().
@@ -72,17 +96,16 @@ class Distribution:
     # don't want to pollute the commands with too many options that they
     # have minimal control over.
     # The fourth entry for verbose means that it can be repeated.
-    global_options = [
+    global_options: ClassVar[_OptionsList] = [
         ('verbose', 'v', "run verbosely (default)", 1),
         ('quiet', 'q', "run quietly (turns verbosity off)"),
-        ('dry-run', 'n', "don't actually do anything"),
         ('help', 'h', "show detailed help message"),
         ('no-user-cfg', None, 'ignore pydistutils.cfg in your home directory'),
     ]
 
     # 'common_usage' is a short (2-3 line) string describing the common
     # usage of the setup script.
-    common_usage = """\
+    common_usage: ClassVar[str] = """\
 Common commands: (see '--help-commands' for more)
 
   setup.py build      will build the package underneath 'build/'
@@ -90,7 +113,7 @@ class Distribution:
 """
 
     # options that are not propagated to the commands
-    display_options = [
+    display_options: ClassVar[_OptionsList] = [
         ('help-commands', None, "list all available commands"),
         ('name', None, "print package name"),
         ('version', 'V', "print package version"),
@@ -117,14 +140,17 @@ class Distribution:
         ('requires', None, "print the list of packages/modules required"),
         ('obsoletes', None, "print the list of packages/modules made obsolete"),
     ]
-    display_option_names = [translate_longopt(x[0]) for x in display_options]
+    display_option_names: ClassVar[list[str]] = [
+        translate_longopt(x[0]) for x in display_options
+    ]
 
     # negative options are options that exclude other options
-    negative_opt = {'quiet': 'verbose'}
+    negative_opt: ClassVar[dict[str, str]] = {'quiet': 'verbose'}
 
     # -- Creation/initialization methods -------------------------------
 
-    def __init__(self, attrs=None):  # noqa: C901
+    # Can't Unpack a TypedDict with optional properties, so using Any instead
+    def __init__(self, attrs: MutableMapping[str, Any] | None = None) -> None:  # noqa: C901
         """Construct a new Distribution instance: initialize all the
         attributes of a Distribution, and then use 'attrs' (a dictionary
         mapping attribute names to values) to assign some of those
@@ -136,11 +162,10 @@ def __init__(self, attrs=None):  # noqa: C901
         """
 
         # Default values for our command-line options
-        self.verbose = 1
-        self.dry_run = 0
-        self.help = 0
+        self.verbose = True
+        self.help = False
         for attr in self.display_option_names:
-            setattr(self, attr, 0)
+            setattr(self, attr, False)
 
         # Store the distribution meta-data (name, version, author, and so
         # forth) in a separate object -- we're getting to have enough
@@ -156,7 +181,7 @@ def __init__(self, attrs=None):  # noqa: C901
         # can 1) quickly figure out which class to instantiate when
         # we need to create a new command object, and 2) have a way
         # for the setup script to override command classes
-        self.cmdclass = {}
+        self.cmdclass: dict[str, type[Command]] = {}
 
         # 'command_packages' is a list of packages in which commands
         # are searched for.  The factory for command 'foo' is expected
@@ -164,20 +189,20 @@ def __init__(self, attrs=None):  # noqa: C901
         # named here.  This list is searched from the left; an error
         # is raised if no named package provides the command being
         # searched for.  (Always access using get_command_packages().)
-        self.command_packages = None
+        self.command_packages: str | list[str] | None = None
 
         # 'script_name' and 'script_args' are usually set to sys.argv[0]
         # and sys.argv[1:], but they can be overridden when the caller is
         # not necessarily a setup script run from the command-line.
-        self.script_name = None
-        self.script_args = None
+        self.script_name: str | os.PathLike[str] | None = None
+        self.script_args: list[str] | None = None
 
         # 'command_options' is where we store command options between
         # parsing them (from config files, the command-line, etc.) and when
         # they are actually needed -- ie. when the command in question is
         # instantiated.  It is a dictionary of dictionaries of 2-tuples:
         #   command_options = { command_name : { option : (source, value) } }
-        self.command_options = {}
+        self.command_options: dict[str, dict[str, tuple[str, str]]] = {}
 
         # 'dist_files' is the list of (command, pyversion, file) that
         # have been created by any dist commands run so far. This is
@@ -188,13 +213,13 @@ def __init__(self, attrs=None):  # noqa: C901
         # file. pyversion should not be used to specify minimum or
         # maximum required Python versions; use the metainfo for that
         # instead.
-        self.dist_files = []
+        self.dist_files: list[tuple[str, str, str]] = []
 
         # These options are really the business of various commands, rather
         # than of the Distribution itself.  We provide aliases for them in
         # Distribution as a convenience to the developer.
         self.packages = None
-        self.package_data = {}
+        self.package_data: dict[str, list[str]] = {}
         self.package_dir = None
         self.py_modules = None
         self.libraries = None
@@ -211,7 +236,7 @@ def __init__(self, attrs=None):  # noqa: C901
         # the caller at all.  'command_obj' maps command names to
         # Command instances -- that's how we enforce that every command
         # class is a singleton.
-        self.command_obj = {}
+        self.command_obj: dict[str, Command] = {}
 
         # 'have_run' maps command names to boolean values; it keeps track
         # of whether we have actually run a particular command, to make it
@@ -223,7 +248,7 @@ def __init__(self, attrs=None):  # noqa: C901
         # command object is created, and replaced with a true value when
         # the command is successfully run.  Thus it's probably best to use
         # '.get()' rather than a straight lookup.
-        self.have_run = {}
+        self.have_run: dict[str, bool] = {}
 
         # Now we'll use the attrs dictionary (ultimately, keyword args from
         # the setup script) to possibly override any or all of these
@@ -246,10 +271,7 @@ def __init__(self, attrs=None):  # noqa: C901
                 attrs['license'] = attrs['licence']
                 del attrs['licence']
                 msg = "'licence' distribution option is deprecated; use 'license'"
-                if warnings is not None:
-                    warnings.warn(msg)
-                else:
-                    sys.stderr.write(msg + "\n")
+                warnings.warn(msg)
 
             # Now work on the rest of the attributes.  Any attribute that's
             # not already defined is invalid!
@@ -261,7 +283,7 @@ def __init__(self, attrs=None):  # noqa: C901
                 elif hasattr(self, key):
                     setattr(self, key, val)
                 else:
-                    msg = "Unknown distribution option: %s" % repr(key)
+                    msg = f"Unknown distribution option: {key!r}"
                     warnings.warn(msg)
 
         # no-user-cfg is handled before other command line args
@@ -273,6 +295,8 @@ def __init__(self, attrs=None):  # noqa: C901
         self.want_user_cfg = True
 
         if self.script_args is not None:
+            # Coerce any possible iterable from attrs into a list
+            self.script_args = list(self.script_args)
             for arg in self.script_args:
                 if not arg.startswith('-'):
                     break
@@ -293,7 +317,7 @@ def get_option_dict(self, command):
             dict = self.command_options[command] = {}
         return dict
 
-    def dump_option_dicts(self, header=None, commands=None, indent=""):
+    def dump_option_dicts(self, header=None, commands=None, indent: str = "") -> None:
         from pprint import pformat
 
         if commands is None:  # dump all command option dicts
@@ -310,9 +334,9 @@ def dump_option_dicts(self, header=None, commands=None, indent=""):
         for cmd_name in commands:
             opt_dict = self.command_options.get(cmd_name)
             if opt_dict is None:
-                self.announce(indent + "no option dict for '%s' command" % cmd_name)
+                self.announce(indent + f"no option dict for '{cmd_name}' command")
             else:
-                self.announce(indent + "option dict for '%s' command:" % cmd_name)
+                self.announce(indent + f"option dict for '{cmd_name}' command:")
                 out = pformat(opt_dict)
                 for line in out.split('\n'):
                     self.announce(indent + "  " + line)
@@ -338,7 +362,7 @@ def find_config_files(self):
         files = [str(path) for path in self._gen_paths() if os.path.isfile(path)]
 
         if DEBUG:
-            self.announce("using config files: %s" % ', '.join(files))
+            self.announce("using config files: {}".format(', '.join(files)))
 
         return files
 
@@ -351,7 +375,8 @@ def _gen_paths(self):
         prefix = '.' * (os.name == 'posix')
         filename = prefix + 'pydistutils.cfg'
         if self.want_user_cfg:
-            yield pathlib.Path('~').expanduser() / filename
+            with contextlib.suppress(RuntimeError):
+                yield pathlib.Path('~').expanduser() / filename
 
         # All platforms support local setup.cfg
         yield pathlib.Path('setup.cfg')
@@ -394,8 +419,8 @@ def parse_config_files(self, filenames=None):  # noqa: C901
         parser = ConfigParser()
         for filename in filenames:
             if DEBUG:
-                self.announce("  reading %s" % filename)
-            parser.read(filename)
+                self.announce(f"  reading {filename}")
+            parser.read(filename, encoding='utf-8')
             for section in parser.sections():
                 options = parser.options(section)
                 opt_dict = self.get_option_dict(section)
@@ -414,12 +439,12 @@ def parse_config_files(self, filenames=None):  # noqa: C901
         # to set Distribution options.
 
         if 'global' in self.command_options:
-            for opt, (src, val) in self.command_options['global'].items():
+            for opt, (_src, val) in self.command_options['global'].items():
                 alias = self.negative_opt.get(opt)
                 try:
                     if alias:
                         setattr(self, alias, not strtobool(val))
-                    elif opt in ('verbose', 'dry_run'):  # ugh!
+                    elif opt in ('verbose',):  # ugh!
                         setattr(self, opt, strtobool(val))
                     else:
                         setattr(self, opt, val)
@@ -524,7 +549,7 @@ def _parse_command_opts(self, parser, args):  # noqa: C901
         # Pull the current command from the head of the command line
         command = args[0]
         if not command_re.match(command):
-            raise SystemExit("invalid command name '%s'" % command)
+            raise SystemExit(f"invalid command name '{command}'")
         self.commands.append(command)
 
         # Dig up the command class that implements this command, so we
@@ -539,7 +564,7 @@ def _parse_command_opts(self, parser, args):  # noqa: C901
         # to be sure that the basic "command" interface is implemented.
         if not issubclass(cmd_class, Command):
             raise DistutilsClassError(
-                "command class %s must subclass Command" % cmd_class
+                f"command class {cmd_class} must subclass Command"
             )
 
         # Also make sure that the command object provides a list of its
@@ -578,23 +603,22 @@ def _parse_command_opts(self, parser, args):  # noqa: C901
         parser.set_negative_aliases(negative_opt)
         (args, opts) = parser.getopt(args[1:])
         if hasattr(opts, 'help') and opts.help:
-            self._show_help(parser, display_options=0, commands=[cmd_class])
+            self._show_help(parser, display_options=False, commands=[cmd_class])
             return
 
         if hasattr(cmd_class, 'help_options') and isinstance(
             cmd_class.help_options, list
         ):
             help_option_found = 0
-            for help_option, short, desc, func in cmd_class.help_options:
+            for help_option, _short, _desc, func in cmd_class.help_options:
                 if hasattr(opts, parser.get_attr_name(help_option)):
                     help_option_found = 1
                     if callable(func):
                         func()
                     else:
                         raise DistutilsClassError(
-                            "invalid help function %r for help option '%s': "
+                            f"invalid help function {func!r} for help option '{help_option}': "
                             "must be a callable object (function, etc.)"
-                            % (func, help_option)
                         )
 
             if help_option_found:
@@ -608,7 +632,7 @@ def _parse_command_opts(self, parser, args):  # noqa: C901
 
         return args
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         """Set final values for all the options on the Distribution
         instance, analogous to the .finalize_options() method of Command
         objects.
@@ -621,7 +645,9 @@ def finalize_options(self):
                 value = [elm.strip() for elm in value.split(',')]
                 setattr(self.metadata, attr, value)
 
-    def _show_help(self, parser, global_options=1, display_options=1, commands=[]):
+    def _show_help(
+        self, parser, global_options=True, display_options=True, commands: Iterable = ()
+    ):
         """Show help for the setup script command-line in the form of
         several lists of command-line options.  'parser' should be a
         FancyGetopt instance; do not expect it to be returned in the
@@ -635,8 +661,8 @@ def _show_help(self, parser, global_options=1, display_options=1, commands=[]):
         in 'commands'.
         """
         # late import because of mutual dependence between these modules
-        from distutils.core import gen_usage
         from distutils.cmd import Command
+        from distutils.core import gen_usage
 
         if global_options:
             if display_options:
@@ -645,17 +671,16 @@ def _show_help(self, parser, global_options=1, display_options=1, commands=[]):
                 options = self.global_options
             parser.set_option_table(options)
             parser.print_help(self.common_usage + "\nGlobal options:")
-            print('')
+            print()
 
         if display_options:
             parser.set_option_table(self.display_options)
             parser.print_help(
-                "Information display options (just display "
-                + "information, ignore any commands)"
+                "Information display options (just display information, ignore any commands)"
             )
-            print('')
+            print()
 
-        for command in self.commands:
+        for command in commands:
             if isinstance(command, type) and issubclass(command, Command):
                 klass = command
             else:
@@ -666,8 +691,8 @@ def _show_help(self, parser, global_options=1, display_options=1, commands=[]):
                 )
             else:
                 parser.set_option_table(klass.user_options)
-            parser.print_help("Options for '%s' command:" % klass.__name__)
-            print('')
+            parser.print_help(f"Options for '{klass.__name__}' command:")
+            print()
 
         print(gen_usage(self.script_name))
 
@@ -684,7 +709,7 @@ def handle_display_options(self, option_order):
         # we ignore "foo bar").
         if self.help_commands:
             self.print_commands()
-            print('')
+            print()
             print(gen_usage(self.script_name))
             return 1
 
@@ -692,12 +717,12 @@ def handle_display_options(self, option_order):
         # display that metadata in the order in which the user supplied the
         # metadata options.
         any_display_options = 0
-        is_display_option = {}
+        is_display_option = set()
         for option in self.display_options:
-            is_display_option[option[0]] = 1
+            is_display_option.add(option[0])
 
         for opt, val in option_order:
-            if val and is_display_option.get(opt):
+            if val and opt in is_display_option:
                 opt = translate_longopt(opt)
                 value = getattr(self.metadata, "get_" + opt)()
                 if opt in ('keywords', 'platforms'):
@@ -710,7 +735,7 @@ def handle_display_options(self, option_order):
 
         return any_display_options
 
-    def print_command_list(self, commands, header, max_length):
+    def print_command_list(self, commands, header, max_length) -> None:
         """Print a subset of the list of all commands -- used by
         'print_commands()'.
         """
@@ -725,9 +750,9 @@ def print_command_list(self, commands, header, max_length):
             except AttributeError:
                 description = "(no description available)"
 
-            print("  %-*s  %s" % (max_length, cmd, description))
+            print(f"  {cmd:<{max_length}}  {description}")
 
-    def print_commands(self):
+    def print_commands(self) -> None:
         """Print out a help message listing all available commands with a
         description of each.  The list is divided into "standard commands"
         (listed in distutils.command.__all__) and "extra commands"
@@ -738,14 +763,9 @@ def print_commands(self):
         import distutils.command
 
         std_commands = distutils.command.__all__
-        is_std = {}
-        for cmd in std_commands:
-            is_std[cmd] = 1
+        is_std = set(std_commands)
 
-        extra_commands = []
-        for cmd in self.cmdclass.keys():
-            if not is_std.get(cmd):
-                extra_commands.append(cmd)
+        extra_commands = [cmd for cmd in self.cmdclass.keys() if cmd not in is_std]
 
         max_length = 0
         for cmd in std_commands + extra_commands:
@@ -769,14 +789,9 @@ def get_command_list(self):
         import distutils.command
 
         std_commands = distutils.command.__all__
-        is_std = {}
-        for cmd in std_commands:
-            is_std[cmd] = 1
+        is_std = set(std_commands)
 
-        extra_commands = []
-        for cmd in self.cmdclass.keys():
-            if not is_std.get(cmd):
-                extra_commands.append(cmd)
+        extra_commands = [cmd for cmd in self.cmdclass.keys() if cmd not in is_std]
 
         rv = []
         for cmd in std_commands + extra_commands:
@@ -804,7 +819,7 @@ def get_command_packages(self):
             self.command_packages = pkgs
         return pkgs
 
-    def get_command_class(self, command):
+    def get_command_class(self, command: str) -> type[Command]:
         """Return the class that implements the Distutils command named by
         'command'.  First we check the 'cmdclass' dictionary; if the
         command is mentioned there, we fetch the class object from the
@@ -821,7 +836,7 @@ def get_command_class(self, command):
             return klass
 
         for pkgname in self.get_command_packages():
-            module_name = "{}.{}".format(pkgname, command)
+            module_name = f"{pkgname}.{command}"
             klass_name = command
 
             try:
@@ -834,16 +849,23 @@ def get_command_class(self, command):
                 klass = getattr(module, klass_name)
             except AttributeError:
                 raise DistutilsModuleError(
-                    "invalid command '%s' (no class '%s' in module '%s')"
-                    % (command, klass_name, module_name)
+                    f"invalid command '{command}' (no class '{klass_name}' in module '{module_name}')"
                 )
 
             self.cmdclass[command] = klass
             return klass
 
-        raise DistutilsModuleError("invalid command '%s'" % command)
-
-    def get_command_obj(self, command, create=1):
+        raise DistutilsModuleError(f"invalid command '{command}'")
+
+    @overload
+    def get_command_obj(
+        self, command: str, create: Literal[True] = True
+    ) -> Command: ...
+    @overload
+    def get_command_obj(
+        self, command: str, create: Literal[False]
+    ) -> Command | None: ...
+    def get_command_obj(self, command: str, create: bool = True) -> Command | None:
         """Return the command object for 'command'.  Normally this object
         is cached on a previous call to 'get_command_obj()'; if no command
         object for 'command' is in the cache, then we either create and
@@ -854,12 +876,12 @@ def get_command_obj(self, command, create=1):
             if DEBUG:
                 self.announce(
                     "Distribution.get_command_obj(): "
-                    "creating '%s' command object" % command
+                    f"creating '{command}' command object"
                 )
 
             klass = self.get_command_class(command)
             cmd_obj = self.command_obj[command] = klass(self)
-            self.have_run[command] = 0
+            self.have_run[command] = False
 
             # Set any options that were supplied in config files
             # or on the command line.  (NB. support for error
@@ -886,10 +908,10 @@ def _set_command_options(self, command_obj, option_dict=None):  # noqa: C901
             option_dict = self.get_option_dict(command_name)
 
         if DEBUG:
-            self.announce("  setting options for '%s' command:" % command_name)
+            self.announce(f"  setting options for '{command_name}' command:")
         for option, (source, value) in option_dict.items():
             if DEBUG:
-                self.announce("    {} = {} (from {})".format(option, value, source))
+                self.announce(f"    {option} = {value} (from {source})")
             try:
                 bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]
             except AttributeError:
@@ -909,13 +931,22 @@ def _set_command_options(self, command_obj, option_dict=None):  # noqa: C901
                     setattr(command_obj, option, value)
                 else:
                     raise DistutilsOptionError(
-                        "error in %s: command '%s' has no such option '%s'"
-                        % (source, command_name, option)
+                        f"error in {source}: command '{command_name}' has no such option '{option}'"
                     )
             except ValueError as msg:
                 raise DistutilsOptionError(msg)
 
-    def reinitialize_command(self, command, reinit_subcommands=0):
+    @overload
+    def reinitialize_command(
+        self, command: str, reinit_subcommands: bool = False
+    ) -> Command: ...
+    @overload
+    def reinitialize_command(
+        self, command: _CommandT, reinit_subcommands: bool = False
+    ) -> _CommandT: ...
+    def reinitialize_command(
+        self, command: str | Command, reinit_subcommands=False
+    ) -> Command:
         """Reinitializes a command to the state it was in when first
         returned by 'get_command_obj()': ie., initialized but not yet
         finalized.  This provides the opportunity to sneak option
@@ -945,8 +976,8 @@ def reinitialize_command(self, command, reinit_subcommands=0):
         if not command.finalized:
             return command
         command.initialize_options()
-        command.finalized = 0
-        self.have_run[command_name] = 0
+        command.finalized = False
+        self.have_run[command_name] = False
         self._set_command_options(command)
 
         if reinit_subcommands:
@@ -957,10 +988,10 @@ def reinitialize_command(self, command, reinit_subcommands=0):
 
     # -- Methods that operate on the Distribution ----------------------
 
-    def announce(self, msg, level=logging.INFO):
+    def announce(self, msg, level: int = logging.INFO) -> None:
         log.log(level, msg)
 
-    def run_commands(self):
+    def run_commands(self) -> None:
         """Run each command that was seen on the setup script command line.
         Uses the list of commands found and cache of command objects
         created by 'get_command_obj()'.
@@ -970,7 +1001,7 @@ def run_commands(self):
 
     # -- Methods that operate on its Commands --------------------------
 
-    def run_command(self, command):
+    def run_command(self, command: str) -> None:
         """Do whatever it takes to run a command (including nothing at all,
         if the command has already been run).  Specifically: if we have
         already created and run the command named by 'command', return
@@ -986,32 +1017,32 @@ def run_command(self, command):
         cmd_obj = self.get_command_obj(command)
         cmd_obj.ensure_finalized()
         cmd_obj.run()
-        self.have_run[command] = 1
+        self.have_run[command] = True
 
     # -- Distribution query methods ------------------------------------
 
-    def has_pure_modules(self):
+    def has_pure_modules(self) -> bool:
         return len(self.packages or self.py_modules or []) > 0
 
-    def has_ext_modules(self):
+    def has_ext_modules(self) -> bool:
         return self.ext_modules and len(self.ext_modules) > 0
 
-    def has_c_libraries(self):
+    def has_c_libraries(self) -> bool:
         return self.libraries and len(self.libraries) > 0
 
-    def has_modules(self):
+    def has_modules(self) -> bool:
         return self.has_pure_modules() or self.has_ext_modules()
 
-    def has_headers(self):
+    def has_headers(self) -> bool:
         return self.headers and len(self.headers) > 0
 
-    def has_scripts(self):
+    def has_scripts(self) -> bool:
         return self.scripts and len(self.scripts) > 0
 
-    def has_data_files(self):
+    def has_data_files(self) -> bool:
         return self.data_files and len(self.data_files) > 0
 
-    def is_pure(self):
+    def is_pure(self) -> bool:
         return (
             self.has_pure_modules()
             and not self.has_ext_modules()
@@ -1024,6 +1055,53 @@ def is_pure(self):
     # they are defined in a sneaky way: the constructor binds self.get_XXX
     # to self.metadata.get_XXX.  The actual code is in the
     # DistributionMetadata class, below.
+    if TYPE_CHECKING:
+        # Unfortunately this means we need to specify them manually or not expose statically
+        def _(self) -> None:
+            self.get_name = self.metadata.get_name
+            self.get_version = self.metadata.get_version
+            self.get_fullname = self.metadata.get_fullname
+            self.get_author = self.metadata.get_author
+            self.get_author_email = self.metadata.get_author_email
+            self.get_maintainer = self.metadata.get_maintainer
+            self.get_maintainer_email = self.metadata.get_maintainer_email
+            self.get_contact = self.metadata.get_contact
+            self.get_contact_email = self.metadata.get_contact_email
+            self.get_url = self.metadata.get_url
+            self.get_license = self.metadata.get_license
+            self.get_licence = self.metadata.get_licence
+            self.get_description = self.metadata.get_description
+            self.get_long_description = self.metadata.get_long_description
+            self.get_keywords = self.metadata.get_keywords
+            self.get_platforms = self.metadata.get_platforms
+            self.get_classifiers = self.metadata.get_classifiers
+            self.get_download_url = self.metadata.get_download_url
+            self.get_requires = self.metadata.get_requires
+            self.get_provides = self.metadata.get_provides
+            self.get_obsoletes = self.metadata.get_obsoletes
+
+        # Default attributes generated in __init__ from self.display_option_names
+        help_commands: bool
+        name: str | Literal[False]
+        version: str | Literal[False]
+        fullname: str | Literal[False]
+        author: str | Literal[False]
+        author_email: str | Literal[False]
+        maintainer: str | Literal[False]
+        maintainer_email: str | Literal[False]
+        contact: str | Literal[False]
+        contact_email: str | Literal[False]
+        url: str | Literal[False]
+        license: str | Literal[False]
+        licence: str | Literal[False]
+        description: str | Literal[False]
+        long_description: str | Literal[False]
+        platforms: str | list[str] | Literal[False]
+        classifiers: str | list[str] | Literal[False]
+        keywords: str | list[str] | Literal[False]
+        provides: list[str] | Literal[False]
+        requires: list[str] | Literal[False]
+        obsoletes: list[str] | Literal[False]
 
 
 class DistributionMetadata:
@@ -1055,37 +1133,40 @@ class DistributionMetadata:
         "obsoletes",
     )
 
-    def __init__(self, path=None):
+    def __init__(
+        self, path: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = None
+    ) -> None:
         if path is not None:
             self.read_pkg_file(open(path))
         else:
-            self.name = None
-            self.version = None
-            self.author = None
-            self.author_email = None
-            self.maintainer = None
-            self.maintainer_email = None
-            self.url = None
-            self.license = None
-            self.description = None
-            self.long_description = None
-            self.keywords = None
-            self.platforms = None
-            self.classifiers = None
-            self.download_url = None
+            self.name: str | None = None
+            self.version: str | None = None
+            self.author: str | None = None
+            self.author_email: str | None = None
+            self.maintainer: str | None = None
+            self.maintainer_email: str | None = None
+            self.url: str | None = None
+            self.license: str | None = None
+            self.description: str | None = None
+            self.long_description: str | None = None
+            self.keywords: str | list[str] | None = None
+            self.platforms: str | list[str] | None = None
+            self.classifiers: str | list[str] | None = None
+            self.download_url: str | None = None
             # PEP 314
-            self.provides = None
-            self.requires = None
-            self.obsoletes = None
+            self.provides: str | list[str] | None = None
+            self.requires: str | list[str] | None = None
+            self.obsoletes: str | list[str] | None = None
 
-    def read_pkg_file(self, file):
+    def read_pkg_file(self, file: IO[str]) -> None:
         """Reads the metadata values from a file object."""
         msg = message_from_file(file)
 
-        def _read_field(name):
+        def _read_field(name: str) -> str | None:
             value = msg[name]
             if value and value != "UNKNOWN":
                 return value
+            return None
 
         def _read_list(name):
             values = msg.get_all(name, None)
@@ -1129,14 +1210,14 @@ def _read_list(name):
             self.provides = None
             self.obsoletes = None
 
-    def write_pkg_info(self, base_dir):
+    def write_pkg_info(self, base_dir: str | os.PathLike[str]) -> None:
         """Write the PKG-INFO file into the release tree."""
         with open(
             os.path.join(base_dir, 'PKG-INFO'), 'w', encoding='UTF-8'
         ) as pkg_info:
             self.write_pkg_file(pkg_info)
 
-    def write_pkg_file(self, file):
+    def write_pkg_file(self, file: SupportsWrite[str]) -> None:
         """Write the PKG-INFO format data to a file object."""
         version = '1.0'
         if (
@@ -1149,9 +1230,9 @@ def write_pkg_file(self, file):
             version = '1.1'
 
         # required fields
-        file.write('Metadata-Version: %s\n' % version)
-        file.write('Name: %s\n' % self.get_name())
-        file.write('Version: %s\n' % self.get_version())
+        file.write(f'Metadata-Version: {version}\n')
+        file.write(f'Name: {self.get_name()}\n')
+        file.write(f'Version: {self.get_version()}\n')
 
         def maybe_write(header, val):
             if val:
@@ -1178,87 +1259,106 @@ def maybe_write(header, val):
     def _write_list(self, file, name, values):
         values = values or []
         for value in values:
-            file.write('{}: {}\n'.format(name, value))
+            file.write(f'{name}: {value}\n')
 
     # -- Metadata query methods ----------------------------------------
 
-    def get_name(self):
+    def get_name(self) -> str:
         return self.name or "UNKNOWN"
 
-    def get_version(self):
+    def get_version(self) -> str:
         return self.version or "0.0.0"
 
-    def get_fullname(self):
-        return "{}-{}".format(self.get_name(), self.get_version())
+    def get_fullname(self) -> str:
+        return self._fullname(self.get_name(), self.get_version())
+
+    @staticmethod
+    def _fullname(name: str, version: str) -> str:
+        """
+        >>> DistributionMetadata._fullname('setup.tools', '1.0-2')
+        'setup_tools-1.0.post2'
+        >>> DistributionMetadata._fullname('setup-tools', '1.2post2')
+        'setup_tools-1.2.post2'
+        >>> DistributionMetadata._fullname('setup-tools', '1.0-r2')
+        'setup_tools-1.0.post2'
+        >>> DistributionMetadata._fullname('setup.tools', '1.0.post')
+        'setup_tools-1.0.post0'
+        >>> DistributionMetadata._fullname('setup.tools', '1.0+ubuntu-1')
+        'setup_tools-1.0+ubuntu.1'
+        """
+        return "{}-{}".format(
+            canonicalize_name(name).replace('-', '_'),
+            canonicalize_version(version, strip_trailing_zero=False),
+        )
 
-    def get_author(self):
+    def get_author(self) -> str | None:
         return self.author
 
-    def get_author_email(self):
+    def get_author_email(self) -> str | None:
         return self.author_email
 
-    def get_maintainer(self):
+    def get_maintainer(self) -> str | None:
         return self.maintainer
 
-    def get_maintainer_email(self):
+    def get_maintainer_email(self) -> str | None:
         return self.maintainer_email
 
-    def get_contact(self):
+    def get_contact(self) -> str | None:
         return self.maintainer or self.author
 
-    def get_contact_email(self):
+    def get_contact_email(self) -> str | None:
         return self.maintainer_email or self.author_email
 
-    def get_url(self):
+    def get_url(self) -> str | None:
         return self.url
 
-    def get_license(self):
+    def get_license(self) -> str | None:
         return self.license
 
     get_licence = get_license
 
-    def get_description(self):
+    def get_description(self) -> str | None:
         return self.description
 
-    def get_long_description(self):
+    def get_long_description(self) -> str | None:
         return self.long_description
 
-    def get_keywords(self):
+    def get_keywords(self) -> str | list[str]:
         return self.keywords or []
 
-    def set_keywords(self, value):
+    def set_keywords(self, value: str | Iterable[str]) -> None:
         self.keywords = _ensure_list(value, 'keywords')
 
-    def get_platforms(self):
+    def get_platforms(self) -> str | list[str] | None:
         return self.platforms
 
-    def set_platforms(self, value):
+    def set_platforms(self, value: str | Iterable[str]) -> None:
         self.platforms = _ensure_list(value, 'platforms')
 
-    def get_classifiers(self):
+    def get_classifiers(self) -> str | list[str]:
         return self.classifiers or []
 
-    def set_classifiers(self, value):
+    def set_classifiers(self, value: str | Iterable[str]) -> None:
         self.classifiers = _ensure_list(value, 'classifiers')
 
-    def get_download_url(self):
+    def get_download_url(self) -> str | None:
         return self.download_url
 
     # PEP 314
-    def get_requires(self):
+    def get_requires(self) -> str | list[str]:
         return self.requires or []
 
-    def set_requires(self, value):
+    def set_requires(self, value: Iterable[str]) -> None:
         import distutils.versionpredicate
 
         for v in value:
             distutils.versionpredicate.VersionPredicate(v)
         self.requires = list(value)
 
-    def get_provides(self):
+    def get_provides(self) -> str | list[str]:
         return self.provides or []
 
-    def set_provides(self, value):
+    def set_provides(self, value: Iterable[str]) -> None:
         value = [v.strip() for v in value]
         for v in value:
             import distutils.versionpredicate
@@ -1266,10 +1366,10 @@ def set_provides(self, value):
             distutils.versionpredicate.split_provision(v)
         self.provides = value
 
-    def get_obsoletes(self):
+    def get_obsoletes(self) -> str | list[str]:
         return self.obsoletes or []
 
-    def set_obsoletes(self, value):
+    def set_obsoletes(self, value: Iterable[str]) -> None:
         import distutils.versionpredicate
 
         for v in value:
@@ -1281,7 +1381,4 @@ def fix_help_options(options):
     """Convert a 4-tuple 'help_options' list as found in various command
     classes to the 3-tuple form required by FancyGetopt.
     """
-    new_options = []
-    for help_tuple in options:
-        new_options.append(help_tuple[0:3])
-    return new_options
+    return [opt[0:3] for opt in options]
diff --git a/setuptools/_distutils/errors.py b/setuptools/_distutils/errors.py
index 626254c321..409d21faa2 100644
--- a/setuptools/_distutils/errors.py
+++ b/setuptools/_distutils/errors.py
@@ -1,12 +1,20 @@
-"""distutils.errors
+"""
+Exceptions used by the Distutils modules.
 
-Provides exceptions used by the Distutils modules.  Note that Distutils
-modules may raise standard exceptions; in particular, SystemExit is
-usually raised for errors that are obviously the end-user's fault
-(eg. bad command-line arguments).
+Distutils modules may raise these or standard exceptions,
+including :exc:`SystemExit`.
+"""
 
-This module is safe to use in "from ... import *" mode; it only exports
-symbols whose names start with "Distutils" and end with "Error"."""
+# compiler exceptions aliased for compatibility
+from .compilers.C.errors import CompileError as CompileError
+from .compilers.C.errors import Error as _Error
+from .compilers.C.errors import LibError as LibError
+from .compilers.C.errors import LinkError as LinkError
+from .compilers.C.errors import PreprocessError as PreprocessError
+from .compilers.C.errors import UnknownFileType as _UnknownFileType
+
+CCompilerError = _Error
+UnknownFileError = _UnknownFileType
 
 
 class DistutilsError(Exception):
@@ -98,30 +106,3 @@ class DistutilsTemplateError(DistutilsError):
 
 class DistutilsByteCompileError(DistutilsError):
     """Byte compile error."""
-
-
-# Exception classes used by the CCompiler implementation classes
-class CCompilerError(Exception):
-    """Some compile/link operation failed."""
-
-
-class PreprocessError(CCompilerError):
-    """Failure to preprocess one or more C/C++ files."""
-
-
-class CompileError(CCompilerError):
-    """Failure to compile one or more C/C++ source files."""
-
-
-class LibError(CCompilerError):
-    """Failure to create a static library from one or more C/C++ object
-    files."""
-
-
-class LinkError(CCompilerError):
-    """Failure to link one or more C/C++ object files into an executable
-    or shared library file."""
-
-
-class UnknownFileError(CCompilerError):
-    """Attempt to process an unknown file type."""
diff --git a/setuptools/_distutils/extension.py b/setuptools/_distutils/extension.py
index 6b8575de29..f51411266e 100644
--- a/setuptools/_distutils/extension.py
+++ b/setuptools/_distutils/extension.py
@@ -3,8 +3,11 @@
 Provides the Extension class, used to describe C/C++ extension
 modules in setup scripts."""
 
+from __future__ import annotations
+
 import os
 import warnings
+from collections.abc import Iterable
 
 # This class is really only used by the "build_ext" command, so it might
 # make sense to put it in distutils.command.build_ext.  However, that
@@ -26,12 +29,14 @@ class Extension:
       name : string
         the full name of the extension, including any packages -- ie.
         *not* a filename or pathname, but Python dotted name
-      sources : [string]
-        list of source filenames, relative to the distribution root
-        (where the setup script lives), in Unix form (slash-separated)
-        for portability.  Source files may be C, C++, SWIG (.i),
-        platform-specific resource files, or whatever else is recognized
-        by the "build_ext" command as source for a Python extension.
+      sources : Iterable[string | os.PathLike]
+        iterable of source filenames (except strings, which could be misinterpreted
+        as a single filename), relative to the distribution root (where the setup
+        script lives), in Unix form (slash-separated) for portability. Can be any
+        non-string iterable (list, tuple, set, etc.) containing strings or
+        PathLike objects. Source files may be C, C++, SWIG (.i), platform-specific
+        resource files, or whatever else is recognized by the "build_ext" command
+        as source for a Python extension.
       include_dirs : [string]
         list of directories to search for C/C++ header files (in Unix
         form for portability)
@@ -86,31 +91,42 @@ class Extension:
     # setup_keywords in core.py.
     def __init__(
         self,
-        name,
-        sources,
-        include_dirs=None,
-        define_macros=None,
-        undef_macros=None,
-        library_dirs=None,
-        libraries=None,
-        runtime_library_dirs=None,
-        extra_objects=None,
-        extra_compile_args=None,
-        extra_link_args=None,
-        export_symbols=None,
-        swig_opts=None,
-        depends=None,
-        language=None,
-        optional=None,
-        **kw  # To catch unknown keywords
+        name: str,
+        sources: Iterable[str | os.PathLike[str]],
+        include_dirs: list[str] | None = None,
+        define_macros: list[tuple[str, str | None]] | None = None,
+        undef_macros: list[str] | None = None,
+        library_dirs: list[str] | None = None,
+        libraries: list[str] | None = None,
+        runtime_library_dirs: list[str] | None = None,
+        extra_objects: list[str] | None = None,
+        extra_compile_args: list[str] | None = None,
+        extra_link_args: list[str] | None = None,
+        export_symbols: list[str] | None = None,
+        swig_opts: list[str] | None = None,
+        depends: list[str] | None = None,
+        language: str | None = None,
+        optional: bool | None = None,
+        **kw,  # To catch unknown keywords
     ):
         if not isinstance(name, str):
-            raise AssertionError("'name' must be a string")
-        if not (isinstance(sources, list) and all(isinstance(v, str) for v in sources)):
-            raise AssertionError("'sources' must be a list of strings")
+            raise TypeError("'name' must be a string")
+
+        # handle the string case first; since strings are iterable, disallow them
+        if isinstance(sources, str):
+            raise TypeError(
+                "'sources' must be an iterable of strings or PathLike objects, not a string"
+            )
+
+        # now we check if it's iterable and contains valid types
+        try:
+            self.sources = list(map(os.fspath, sources))
+        except TypeError:
+            raise TypeError(
+                "'sources' must be an iterable of strings or PathLike objects"
+            )
 
         self.name = name
-        self.sources = sources
         self.include_dirs = include_dirs or []
         self.define_macros = define_macros or []
         self.undef_macros = undef_macros or []
@@ -130,22 +146,16 @@ def __init__(
         if len(kw) > 0:
             options = [repr(option) for option in kw]
             options = ', '.join(sorted(options))
-            msg = "Unknown Extension options: %s" % options
+            msg = f"Unknown Extension options: {options}"
             warnings.warn(msg)
 
     def __repr__(self):
-        return '<{}.{}({!r}) at {:#x}>'.format(
-            self.__class__.__module__,
-            self.__class__.__qualname__,
-            self.name,
-            id(self),
-        )
+        return f'<{self.__class__.__module__}.{self.__class__.__qualname__}({self.name!r}) at {id(self):#x}>'
 
 
 def read_setup_file(filename):  # noqa: C901
     """Reads a Setup file and returns Extension instances."""
-    from distutils.sysconfig import parse_makefile, expand_makefile_vars, _variable_rx
-
+    from distutils.sysconfig import _variable_rx, expand_makefile_vars, parse_makefile
     from distutils.text_file import TextFile
     from distutils.util import split_quoted
 
@@ -156,11 +166,11 @@ def read_setup_file(filename):  # noqa: C901
     #    ... [ ...] [ ...] [ ...]
     file = TextFile(
         filename,
-        strip_comments=1,
-        skip_blanks=1,
-        join_lines=1,
-        lstrip_ws=1,
-        rstrip_ws=1,
+        strip_comments=True,
+        skip_blanks=True,
+        join_lines=True,
+        lstrip_ws=True,
+        rstrip_ws=True,
     )
     try:
         extensions = []
@@ -173,7 +183,7 @@ def read_setup_file(filename):  # noqa: C901
                 continue
 
             if line[0] == line[-1] == "*":
-                file.warn("'%s' lines not handled yet" % line)
+                file.warn(f"'{line}' lines not handled yet")
                 continue
 
             line = expand_makefile_vars(line, vars)
@@ -239,7 +249,7 @@ def read_setup_file(filename):  # noqa: C901
                     # and append it to sources.  Hmmmm.
                     ext.extra_objects.append(word)
                 else:
-                    file.warn("unrecognized argument '%s'" % word)
+                    file.warn(f"unrecognized argument '{word}'")
 
             extensions.append(ext)
     finally:
diff --git a/setuptools/_distutils/fancy_getopt.py b/setuptools/_distutils/fancy_getopt.py
index 3b887dc5a4..1a1d3a05da 100644
--- a/setuptools/_distutils/fancy_getopt.py
+++ b/setuptools/_distutils/fancy_getopt.py
@@ -8,21 +8,26 @@
   * options set attributes of a passed-in object
 """
 
-import sys
-import string
-import re
+from __future__ import annotations
+
 import getopt
-from .errors import DistutilsGetoptError, DistutilsArgError
+import re
+import string
+import sys
+from collections.abc import Sequence
+from typing import Any
+
+from .errors import DistutilsArgError, DistutilsGetoptError
 
 # Much like command_re in distutils.core, this is close to but not quite
 # the same as a Python NAME -- except, in the spirit of most GNU
 # utilities, we use '-' in place of '_'.  (The spirit of LISP lives on!)
 # The similarities to NAME are again not a coincidence...
 longopt_pat = r'[a-zA-Z](?:[a-zA-Z0-9-]*)'
-longopt_re = re.compile(r'^%s$' % longopt_pat)
+longopt_re = re.compile(rf'^{longopt_pat}$')
 
 # For recognizing "negative alias" options, eg. "quiet=!verbose"
-neg_alias_re = re.compile("^({})=!({})$".format(longopt_pat, longopt_pat))
+neg_alias_re = re.compile(f"^({longopt_pat})=!({longopt_pat})$")
 
 # This is used to translate long options to legitimate Python identifiers
 # (for use as attributes of some object).
@@ -93,7 +98,7 @@ def set_option_table(self, option_table):
     def add_option(self, long_option, short_option=None, help_string=None):
         if long_option in self.option_index:
             raise DistutilsGetoptError(
-                "option conflict: already an option '%s'" % long_option
+                f"option conflict: already an option '{long_option}'"
             )
         else:
             option = (long_option, short_option, help_string)
@@ -116,13 +121,11 @@ def _check_alias_dict(self, aliases, what):
         for alias, opt in aliases.items():
             if alias not in self.option_index:
                 raise DistutilsGetoptError(
-                    ("invalid %s '%s': " "option '%s' not defined")
-                    % (what, alias, alias)
+                    f"invalid {what} '{alias}': option '{alias}' not defined"
                 )
             if opt not in self.option_index:
                 raise DistutilsGetoptError(
-                    ("invalid %s '%s': " "aliased option '%s' not defined")
-                    % (what, alias, opt)
+                    f"invalid {what} '{alias}': aliased option '{opt}' not defined"
                 )
 
     def set_aliases(self, alias):
@@ -157,19 +160,17 @@ def _grok_option_table(self):  # noqa: C901
             else:
                 # the option table is part of the code, so simply
                 # assert that it is correct
-                raise ValueError("invalid option tuple: {!r}".format(option))
+                raise ValueError(f"invalid option tuple: {option!r}")
 
             # Type- and value-check the option names
             if not isinstance(long, str) or len(long) < 2:
                 raise DistutilsGetoptError(
-                    ("invalid long option '%s': " "must be a string of length >= 2")
-                    % long
+                    f"invalid long option '{long}': must be a string of length >= 2"
                 )
 
             if not ((short is None) or (isinstance(short, str) and len(short) == 1)):
                 raise DistutilsGetoptError(
-                    "invalid short option '%s': "
-                    "must a single character or None" % short
+                    f"invalid short option '{short}': must a single character or None"
                 )
 
             self.repeat[long] = repeat
@@ -179,7 +180,7 @@ def _grok_option_table(self):  # noqa: C901
                 if short:
                     short = short + ':'
                 long = long[0:-1]
-                self.takes_arg[long] = 1
+                self.takes_arg[long] = True
             else:
                 # Is option is a "negative alias" for some other option (eg.
                 # "quiet" == "!verbose")?
@@ -187,12 +188,12 @@ def _grok_option_table(self):  # noqa: C901
                 if alias_to is not None:
                     if self.takes_arg[alias_to]:
                         raise DistutilsGetoptError(
-                            "invalid negative alias '%s': "
-                            "aliased option '%s' takes a value" % (long, alias_to)
+                            f"invalid negative alias '{long}': "
+                            f"aliased option '{alias_to}' takes a value"
                         )
 
                     self.long_opts[-1] = long  # XXX redundant?!
-                self.takes_arg[long] = 0
+                self.takes_arg[long] = False
 
             # If this is an alias option, make sure its "takes arg" flag is
             # the same as the option it's aliased to.
@@ -200,9 +201,9 @@ def _grok_option_table(self):  # noqa: C901
             if alias_to is not None:
                 if self.takes_arg[long] != self.takes_arg[alias_to]:
                     raise DistutilsGetoptError(
-                        "invalid alias '%s': inconsistent with "
-                        "aliased option '%s' (one of them takes a value, "
-                        "the other doesn't" % (long, alias_to)
+                        f"invalid alias '{long}': inconsistent with "
+                        f"aliased option '{alias_to}' (one of them takes a value, "
+                        "the other doesn't"
                     )
 
             # Now enforce some bondage on the long option name, so we can
@@ -211,8 +212,8 @@ def _grok_option_table(self):  # noqa: C901
             # '='.
             if not longopt_re.match(long):
                 raise DistutilsGetoptError(
-                    "invalid long option name '%s' "
-                    "(must be letters, numbers, hyphens only" % long
+                    f"invalid long option name '{long}' "
+                    "(must be letters, numbers, hyphens only"
                 )
 
             self.attr_name[long] = self.get_attr_name(long)
@@ -220,7 +221,7 @@ def _grok_option_table(self):  # noqa: C901
                 self.short_opts.append(short)
                 self.short2long[short[0]] = long
 
-    def getopt(self, args=None, object=None):  # noqa: C901
+    def getopt(self, args: Sequence[str] | None = None, object=None):  # noqa: C901
         """Parse command-line options in args. Store as attributes on object.
 
         If 'args' is None or not supplied, uses 'sys.argv[1:]'.  If
@@ -269,7 +270,7 @@ def getopt(self, args=None, object=None):  # noqa: C901
 
             attr = self.attr_name[opt]
             # The only repeating option at the moment is 'verbose'.
-            # It has a negative option -q quiet, which should set verbose = 0.
+            # It has a negative option -q quiet, which should set verbose = False.
             if val and self.repeat.get(attr) is not None:
                 val = getattr(object, attr, 0) + 1
             setattr(object, attr, val)
@@ -352,18 +353,18 @@ def generate_help(self, header=None):  # noqa: C901
             # Case 1: no short option at all (makes life easy)
             if short is None:
                 if text:
-                    lines.append("  --%-*s  %s" % (max_opt, long, text[0]))
+                    lines.append(f"  --{long:<{max_opt}}  {text[0]}")
                 else:
-                    lines.append("  --%-*s  " % (max_opt, long))
+                    lines.append(f"  --{long:<{max_opt}}")
 
             # Case 2: we have a short option, so we have to include it
             # just after the long option
             else:
-                opt_names = "{} (-{})".format(long, short)
+                opt_names = f"{long} (-{short})"
                 if text:
-                    lines.append("  --%-*s  %s" % (max_opt, opt_names, text[0]))
+                    lines.append(f"  --{opt_names:<{max_opt}}  {text[0]}")
                 else:
-                    lines.append("  --%-*s" % opt_names)
+                    lines.append(f"  --{opt_names:<{max_opt}}")
 
             for ell in text[1:]:
                 lines.append(big_indent + ell)
@@ -376,7 +377,7 @@ def print_help(self, header=None, file=None):
             file.write(line + "\n")
 
 
-def fancy_getopt(options, negative_opt, object, args):
+def fancy_getopt(options, negative_opt, object, args: Sequence[str] | None):
     parser = FancyGetopt(options)
     parser.set_negative_aliases(negative_opt)
     return parser.getopt(args, object)
@@ -450,7 +451,7 @@ class OptionDummy:
     """Dummy class just used as a place to hold command-line option
     values as instance attributes."""
 
-    def __init__(self, options=[]):
+    def __init__(self, options: Sequence[Any] = []):
         """Create a new OptionDummy instance.  The attributes listed in
         'options' will be initialized to None."""
         for opt in options:
@@ -465,6 +466,6 @@ def __init__(self, options=[]):
 say, "How should I know?"].)"""
 
     for w in (10, 20, 30, 40):
-        print("width: %d" % w)
+        print(f"width: {w}")
         print("\n".join(wrap_text(text, w)))
         print()
diff --git a/setuptools/_distutils/file_util.py b/setuptools/_distutils/file_util.py
index 7c69906646..a9724b1779 100644
--- a/setuptools/_distutils/file_util.py
+++ b/setuptools/_distutils/file_util.py
@@ -4,8 +4,9 @@
 """
 
 import os
-from .errors import DistutilsFileError
+
 from ._log import log
+from .errors import DistutilsFileError
 
 # for generating verbose output in 'copy_file()'
 _copy_action = {None: 'copying', 'hard': 'hard linking', 'sym': 'symbolically linking'}
@@ -26,30 +27,24 @@ def _copy_file_contents(src, dst, buffer_size=16 * 1024):  # noqa: C901
         try:
             fsrc = open(src, 'rb')
         except OSError as e:
-            raise DistutilsFileError("could not open '{}': {}".format(src, e.strerror))
+            raise DistutilsFileError(f"could not open '{src}': {e.strerror}")
 
         if os.path.exists(dst):
             try:
                 os.unlink(dst)
             except OSError as e:
-                raise DistutilsFileError(
-                    "could not delete '{}': {}".format(dst, e.strerror)
-                )
+                raise DistutilsFileError(f"could not delete '{dst}': {e.strerror}")
 
         try:
             fdst = open(dst, 'wb')
         except OSError as e:
-            raise DistutilsFileError(
-                "could not create '{}': {}".format(dst, e.strerror)
-            )
+            raise DistutilsFileError(f"could not create '{dst}': {e.strerror}")
 
         while True:
             try:
                 buf = fsrc.read(buffer_size)
             except OSError as e:
-                raise DistutilsFileError(
-                    "could not read from '{}': {}".format(src, e.strerror)
-                )
+                raise DistutilsFileError(f"could not read from '{src}': {e.strerror}")
 
             if not buf:
                 break
@@ -57,9 +52,7 @@ def _copy_file_contents(src, dst, buffer_size=16 * 1024):  # noqa: C901
             try:
                 fdst.write(buf)
             except OSError as e:
-                raise DistutilsFileError(
-                    "could not write to '{}': {}".format(dst, e.strerror)
-                )
+                raise DistutilsFileError(f"could not write to '{dst}': {e.strerror}")
     finally:
         if fdst:
             fdst.close()
@@ -70,12 +63,11 @@ def _copy_file_contents(src, dst, buffer_size=16 * 1024):  # noqa: C901
 def copy_file(  # noqa: C901
     src,
     dst,
-    preserve_mode=1,
-    preserve_times=1,
-    update=0,
+    preserve_mode=True,
+    preserve_times=True,
+    update=False,
     link=None,
-    verbose=1,
-    dry_run=0,
+    verbose=True,
 ):
     """Copy a file 'src' to 'dst'.  If 'dst' is a directory, then 'src' is
     copied there with the same name; otherwise, it must be a filename.  (If
@@ -98,8 +90,7 @@ def copy_file(  # noqa: C901
     other systems, uses '_copy_file_contents()' to copy file contents.
 
     Return a tuple (dest_name, copied): 'dest_name' is the actual name of
-    the output file, and 'copied' is true if the file was copied (or would
-    have been copied, if 'dry_run' true).
+    the output file, and 'copied' is true if the file was copied.
     """
     # XXX if the destination file already exists, we clobber it if
     # copying, but blow up if linking.  Hmmm.  And I don't know what
@@ -108,12 +99,12 @@ def copy_file(  # noqa: C901
     # changing it (ie. it's not already a hard/soft link to src OR
     # (not update) and (src newer than dst).
 
-    from distutils.dep_util import newer
-    from stat import ST_ATIME, ST_MTIME, ST_MODE, S_IMODE
+    from distutils._modified import newer
+    from stat import S_IMODE, ST_ATIME, ST_MODE, ST_MTIME
 
     if not os.path.isfile(src):
         raise DistutilsFileError(
-            "can't copy '%s': doesn't exist or not a regular file" % src
+            f"can't copy '{src}': doesn't exist or not a regular file"
         )
 
     if os.path.isdir(dst):
@@ -125,12 +116,12 @@ def copy_file(  # noqa: C901
     if update and not newer(src, dst):
         if verbose >= 1:
             log.debug("not copying %s (output up-to-date)", src)
-        return (dst, 0)
+        return (dst, False)
 
     try:
         action = _copy_action[link]
     except KeyError:
-        raise ValueError("invalid value '%s' for 'link' argument" % link)
+        raise ValueError(f"invalid value '{link}' for 'link' argument")
 
     if verbose >= 1:
         if os.path.basename(dst) == os.path.basename(src):
@@ -138,25 +129,23 @@ def copy_file(  # noqa: C901
         else:
             log.info("%s %s -> %s", action, src, dst)
 
-    if dry_run:
-        return (dst, 1)
-
     # If linking (hard or symbolic), use the appropriate system call
     # (Unix only, of course, but that's the caller's responsibility)
-    elif link == 'hard':
+    if link == 'hard':
         if not (os.path.exists(dst) and os.path.samefile(src, dst)):
             try:
                 os.link(src, dst)
-                return (dst, 1)
             except OSError:
                 # If hard linking fails, fall back on copying file
                 # (some special filesystems don't support hard linking
                 #  even under Unix, see issue #8876).
                 pass
+            else:
+                return (dst, True)
     elif link == 'sym':
         if not (os.path.exists(dst) and os.path.samefile(src, dst)):
             os.symlink(src, dst)
-            return (dst, 1)
+            return (dst, True)
 
     # Otherwise (non-Mac, not linking), copy the file contents and
     # (optionally) copy the times and mode.
@@ -171,11 +160,11 @@ def copy_file(  # noqa: C901
         if preserve_mode:
             os.chmod(dst, S_IMODE(st[ST_MODE]))
 
-    return (dst, 1)
+    return (dst, True)
 
 
 # XXX I suspect this is Unix-specific -- need porting help!
-def move_file(src, dst, verbose=1, dry_run=0):  # noqa: C901
+def move_file(src, dst, verbose=True):  # noqa: C901
     """Move a file 'src' to 'dst'.  If 'dst' is a directory, the file will
     be moved into it with the same name; otherwise, 'src' is just renamed
     to 'dst'.  Return the new full name of the file.
@@ -183,28 +172,25 @@ def move_file(src, dst, verbose=1, dry_run=0):  # noqa: C901
     Handles cross-device moves on Unix using 'copy_file()'.  What about
     other systems???
     """
-    from os.path import exists, isfile, isdir, basename, dirname
     import errno
+    from os.path import basename, dirname, exists, isdir, isfile
 
     if verbose >= 1:
         log.info("moving %s -> %s", src, dst)
 
-    if dry_run:
-        return dst
-
     if not isfile(src):
-        raise DistutilsFileError("can't move '%s': not a regular file" % src)
+        raise DistutilsFileError(f"can't move '{src}': not a regular file")
 
     if isdir(dst):
         dst = os.path.join(dst, basename(src))
     elif exists(dst):
         raise DistutilsFileError(
-            "can't move '{}': destination '{}' already exists".format(src, dst)
+            f"can't move '{src}': destination '{dst}' already exists"
         )
 
     if not isdir(dirname(dst)):
         raise DistutilsFileError(
-            "can't move '{}': destination '{}' not a valid path".format(src, dst)
+            f"can't move '{src}': destination '{dst}' not a valid path"
         )
 
     copy_it = False
@@ -215,9 +201,7 @@ def move_file(src, dst, verbose=1, dry_run=0):  # noqa: C901
         if num == errno.EXDEV:
             copy_it = True
         else:
-            raise DistutilsFileError(
-                "couldn't move '{}' to '{}': {}".format(src, dst, msg)
-            )
+            raise DistutilsFileError(f"couldn't move '{src}' to '{dst}': {msg}")
 
     if copy_it:
         copy_file(src, dst, verbose=verbose)
@@ -230,8 +214,8 @@ def move_file(src, dst, verbose=1, dry_run=0):  # noqa: C901
             except OSError:
                 pass
             raise DistutilsFileError(
-                "couldn't move '%s' to '%s' by copy/delete: "
-                "delete '%s' failed: %s" % (src, dst, src, msg)
+                f"couldn't move '{src}' to '{dst}' by copy/delete: "
+                f"delete '{src}' failed: {msg}"
             )
     return dst
 
@@ -240,9 +224,5 @@ def write_file(filename, contents):
     """Create a file with the specified name and write 'contents' (a
     sequence of strings without line terminators) to it.
     """
-    f = open(filename, "w")
-    try:
-        for line in contents:
-            f.write(line + "\n")
-    finally:
-        f.close()
+    with open(filename, 'w', encoding='utf-8') as f:
+        f.writelines(line + '\n' for line in contents)
diff --git a/setuptools/_distutils/filelist.py b/setuptools/_distutils/filelist.py
index 6dadf923d7..70dc0fdebc 100644
--- a/setuptools/_distutils/filelist.py
+++ b/setuptools/_distutils/filelist.py
@@ -4,14 +4,18 @@
 and building lists of files.
 """
 
-import os
-import re
+from __future__ import annotations
+
 import fnmatch
 import functools
+import os
+import re
+from collections.abc import Iterable
+from typing import Literal, overload
 
-from .util import convert_path
-from .errors import DistutilsTemplateError, DistutilsInternalError
 from ._log import log
+from .errors import DistutilsInternalError, DistutilsTemplateError
+from .util import convert_path
 
 
 class FileList:
@@ -29,19 +33,19 @@ class FileList:
         filtering applied)
     """
 
-    def __init__(self, warn=None, debug_print=None):
+    def __init__(self, warn: object = None, debug_print: object = None) -> None:
         # ignore argument to FileList, but keep them for backwards
         # compatibility
-        self.allfiles = None
-        self.files = []
+        self.allfiles: Iterable[str] | None = None
+        self.files: list[str] = []
 
-    def set_allfiles(self, allfiles):
+    def set_allfiles(self, allfiles: Iterable[str]) -> None:
         self.allfiles = allfiles
 
-    def findall(self, dir=os.curdir):
+    def findall(self, dir: str | os.PathLike[str] = os.curdir) -> None:
         self.allfiles = findall(dir)
 
-    def debug_print(self, msg):
+    def debug_print(self, msg: object) -> None:
         """Print 'msg' to stdout if the global DEBUG (taken from the
         DISTUTILS_DEBUG environment variable) flag is true.
         """
@@ -52,13 +56,13 @@ def debug_print(self, msg):
 
     # Collection methods
 
-    def append(self, item):
+    def append(self, item: str) -> None:
         self.files.append(item)
 
-    def extend(self, items):
+    def extend(self, items: Iterable[str]) -> None:
         self.files.extend(items)
 
-    def sort(self):
+    def sort(self) -> None:
         # Not a strict lexical sort!
         sortable_files = sorted(map(os.path.split, self.files))
         self.files = []
@@ -67,7 +71,7 @@ def sort(self):
 
     # Other miscellaneous utility methods
 
-    def remove_duplicates(self):
+    def remove_duplicates(self) -> None:
         # Assumes list has been sorted!
         for i in range(len(self.files) - 1, 0, -1):
             if self.files[i] == self.files[i - 1]:
@@ -84,28 +88,28 @@ def _parse_template_line(self, line):
         if action in ('include', 'exclude', 'global-include', 'global-exclude'):
             if len(words) < 2:
                 raise DistutilsTemplateError(
-                    "'%s' expects   ..." % action
+                    f"'{action}' expects   ..."
                 )
             patterns = [convert_path(w) for w in words[1:]]
         elif action in ('recursive-include', 'recursive-exclude'):
             if len(words) < 3:
                 raise DistutilsTemplateError(
-                    "'%s' expects    ..." % action
+                    f"'{action}' expects    ..."
                 )
             dir = convert_path(words[1])
             patterns = [convert_path(w) for w in words[2:]]
         elif action in ('graft', 'prune'):
             if len(words) != 2:
                 raise DistutilsTemplateError(
-                    "'%s' expects a single " % action
+                    f"'{action}' expects a single "
                 )
             dir_pattern = convert_path(words[1])
         else:
-            raise DistutilsTemplateError("unknown action '%s'" % action)
+            raise DistutilsTemplateError(f"unknown action '{action}'")
 
         return (action, patterns, dir, dir_pattern)
 
-    def process_template_line(self, line):  # noqa: C901
+    def process_template_line(self, line: str) -> None:  # noqa: C901
         # Parse the line: split it up, make sure the right number of words
         # is there, and return the relevant words.  'action' is always
         # defined: it's the first word of the line.  Which of the other
@@ -119,25 +123,22 @@ def process_template_line(self, line):  # noqa: C901
         if action == 'include':
             self.debug_print("include " + ' '.join(patterns))
             for pattern in patterns:
-                if not self.include_pattern(pattern, anchor=1):
+                if not self.include_pattern(pattern, anchor=True):
                     log.warning("warning: no files found matching '%s'", pattern)
 
         elif action == 'exclude':
             self.debug_print("exclude " + ' '.join(patterns))
             for pattern in patterns:
-                if not self.exclude_pattern(pattern, anchor=1):
+                if not self.exclude_pattern(pattern, anchor=True):
                     log.warning(
-                        (
-                            "warning: no previously-included files "
-                            "found matching '%s'"
-                        ),
+                        "warning: no previously-included files found matching '%s'",
                         pattern,
                     )
 
         elif action == 'global-include':
             self.debug_print("global-include " + ' '.join(patterns))
             for pattern in patterns:
-                if not self.include_pattern(pattern, anchor=0):
+                if not self.include_pattern(pattern, anchor=False):
                     log.warning(
                         (
                             "warning: no files found matching '%s' "
@@ -149,7 +150,7 @@ def process_template_line(self, line):  # noqa: C901
         elif action == 'global-exclude':
             self.debug_print("global-exclude " + ' '.join(patterns))
             for pattern in patterns:
-                if not self.exclude_pattern(pattern, anchor=0):
+                if not self.exclude_pattern(pattern, anchor=False):
                     log.warning(
                         (
                             "warning: no previously-included files matching "
@@ -162,9 +163,7 @@ def process_template_line(self, line):  # noqa: C901
             self.debug_print("recursive-include {} {}".format(dir, ' '.join(patterns)))
             for pattern in patterns:
                 if not self.include_pattern(pattern, prefix=dir):
-                    msg = (
-                        "warning: no files found matching '%s' " "under directory '%s'"
-                    )
+                    msg = "warning: no files found matching '%s' under directory '%s'"
                     log.warning(msg, pattern, dir)
 
         elif action == 'recursive-exclude':
@@ -189,17 +188,47 @@ def process_template_line(self, line):  # noqa: C901
             self.debug_print("prune " + dir_pattern)
             if not self.exclude_pattern(None, prefix=dir_pattern):
                 log.warning(
-                    ("no previously-included directories found " "matching '%s'"),
+                    ("no previously-included directories found matching '%s'"),
                     dir_pattern,
                 )
         else:
             raise DistutilsInternalError(
-                "this cannot happen: invalid action '%s'" % action
+                f"this cannot happen: invalid action '{action}'"
             )
 
     # Filtering/selection methods
-
-    def include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
+    @overload
+    def include_pattern(
+        self,
+        pattern: str,
+        anchor: bool = True,
+        prefix: str | None = None,
+        is_regex: Literal[False] = False,
+    ) -> bool: ...
+    @overload
+    def include_pattern(
+        self,
+        pattern: str | re.Pattern[str],
+        anchor: bool = True,
+        prefix: str | None = None,
+        *,
+        is_regex: Literal[True],
+    ) -> bool: ...
+    @overload
+    def include_pattern(
+        self,
+        pattern: str | re.Pattern[str],
+        anchor: bool,
+        prefix: str | None,
+        is_regex: Literal[True],
+    ) -> bool: ...
+    def include_pattern(
+        self,
+        pattern: str | re.Pattern,
+        anchor: bool = True,
+        prefix: str | None = None,
+        is_regex: bool = False,
+    ) -> bool:
         """Select strings (presumably filenames) from 'self.files' that
         match 'pattern', a Unix-style wildcard (glob) pattern.  Patterns
         are not quite the same as implemented by the 'fnmatch' module: '*'
@@ -227,7 +256,7 @@ def include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
         # XXX docstring lying about what the special chars are?
         files_found = False
         pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
-        self.debug_print("include_pattern: applying regex r'%s'" % pattern_re.pattern)
+        self.debug_print(f"include_pattern: applying regex r'{pattern_re.pattern}'")
 
         # delayed loading of allfiles list
         if self.allfiles is None:
@@ -240,7 +269,38 @@ def include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
                 files_found = True
         return files_found
 
-    def exclude_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
+    @overload
+    def exclude_pattern(
+        self,
+        pattern: str,
+        anchor: bool = True,
+        prefix: str | None = None,
+        is_regex: Literal[False] = False,
+    ) -> bool: ...
+    @overload
+    def exclude_pattern(
+        self,
+        pattern: str | re.Pattern[str],
+        anchor: bool = True,
+        prefix: str | None = None,
+        *,
+        is_regex: Literal[True],
+    ) -> bool: ...
+    @overload
+    def exclude_pattern(
+        self,
+        pattern: str | re.Pattern[str],
+        anchor: bool,
+        prefix: str | None,
+        is_regex: Literal[True],
+    ) -> bool: ...
+    def exclude_pattern(
+        self,
+        pattern: str | re.Pattern,
+        anchor: bool = True,
+        prefix: str | None = None,
+        is_regex: bool = False,
+    ) -> bool:
         """Remove strings (presumably filenames) from 'files' that match
         'pattern'.  Other parameters are the same as for
         'include_pattern()', above.
@@ -249,7 +309,7 @@ def exclude_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
         """
         files_found = False
         pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
-        self.debug_print("exclude_pattern: applying regex r'%s'" % pattern_re.pattern)
+        self.debug_print(f"exclude_pattern: applying regex r'{pattern_re.pattern}'")
         for i in range(len(self.files) - 1, -1, -1):
             if pattern_re.search(self.files[i]):
                 self.debug_print(" removing " + self.files[i])
@@ -299,7 +359,7 @@ def filter(cls, items):
         return filter(cls(), items)
 
 
-def findall(dir=os.curdir):
+def findall(dir: str | os.PathLike[str] = os.curdir):
     """
     Find all files under 'dir' and return the list of full filenames.
     Unless dir is '.', return full filenames with dir prepended.
@@ -329,12 +389,12 @@ def glob_to_re(pattern):
         # we're using a regex to manipulate a regex, so we need
         # to escape the backslash twice
         sep = r'\\\\'
-    escaped = r'\1[^%s]' % sep
+    escaped = rf'\1[^{sep}]'
     pattern_re = re.sub(r'((? 2**32
-if NATIVE_WIN64:
-    # Visual C++ is a 32-bit application, so we need to look in
-    # the corresponding registry branch, if we're running a
-    # 64-bit Python on Win64
-    VS_BASE = r"Software\Wow6432Node\Microsoft\VisualStudio\%0.1f"
-    WINSDK_BASE = r"Software\Wow6432Node\Microsoft\Microsoft SDKs\Windows"
-    NET_BASE = r"Software\Wow6432Node\Microsoft\.NETFramework"
-else:
-    VS_BASE = r"Software\Microsoft\VisualStudio\%0.1f"
-    WINSDK_BASE = r"Software\Microsoft\Microsoft SDKs\Windows"
-    NET_BASE = r"Software\Microsoft\.NETFramework"
-
-# A map keyed by get_platform() return values to values accepted by
-# 'vcvarsall.bat'.  Note a cross-compile may combine these (eg, 'x86_amd64' is
-# the param to cross-compile on x86 targeting amd64.)
-PLAT_TO_VCVARS = {
-    'win32': 'x86',
-    'win-amd64': 'amd64',
-}
-
-
-class Reg:
-    """Helper class to read values from the registry"""
-
-    def get_value(cls, path, key):
-        for base in HKEYS:
-            d = cls.read_values(base, path)
-            if d and key in d:
-                return d[key]
-        raise KeyError(key)
-
-    get_value = classmethod(get_value)
-
-    def read_keys(cls, base, key):
-        """Return list of registry keys."""
-        try:
-            handle = RegOpenKeyEx(base, key)
-        except RegError:
-            return None
-        L = []
-        i = 0
-        while True:
-            try:
-                k = RegEnumKey(handle, i)
-            except RegError:
-                break
-            L.append(k)
-            i += 1
-        return L
-
-    read_keys = classmethod(read_keys)
-
-    def read_values(cls, base, key):
-        """Return dict of registry keys and values.
-
-        All names are converted to lowercase.
-        """
-        try:
-            handle = RegOpenKeyEx(base, key)
-        except RegError:
-            return None
-        d = {}
-        i = 0
-        while True:
-            try:
-                name, value, type = RegEnumValue(handle, i)
-            except RegError:
-                break
-            name = name.lower()
-            d[cls.convert_mbcs(name)] = cls.convert_mbcs(value)
-            i += 1
-        return d
-
-    read_values = classmethod(read_values)
-
-    def convert_mbcs(s):
-        dec = getattr(s, "decode", None)
-        if dec is not None:
-            try:
-                s = dec("mbcs")
-            except UnicodeError:
-                pass
-        return s
-
-    convert_mbcs = staticmethod(convert_mbcs)
-
-
-class MacroExpander:
-    def __init__(self, version):
-        self.macros = {}
-        self.vsbase = VS_BASE % version
-        self.load_macros(version)
-
-    def set_macro(self, macro, path, key):
-        self.macros["$(%s)" % macro] = Reg.get_value(path, key)
-
-    def load_macros(self, version):
-        self.set_macro("VCInstallDir", self.vsbase + r"\Setup\VC", "productdir")
-        self.set_macro("VSInstallDir", self.vsbase + r"\Setup\VS", "productdir")
-        self.set_macro("FrameworkDir", NET_BASE, "installroot")
-        try:
-            if version >= 8.0:
-                self.set_macro("FrameworkSDKDir", NET_BASE, "sdkinstallrootv2.0")
-            else:
-                raise KeyError("sdkinstallrootv2.0")
-        except KeyError:
-            raise DistutilsPlatformError(
-                """Python was built with Visual Studio 2008;
-extensions must be built with a compiler than can generate compatible binaries.
-Visual Studio 2008 was not found on this system. If you have Cygwin installed,
-you can try compiling with MingW32, by passing "-c mingw32" to setup.py."""
-            )
-
-        if version >= 9.0:
-            self.set_macro("FrameworkVersion", self.vsbase, "clr version")
-            self.set_macro("WindowsSdkDir", WINSDK_BASE, "currentinstallfolder")
-        else:
-            p = r"Software\Microsoft\NET Framework Setup\Product"
-            for base in HKEYS:
-                try:
-                    h = RegOpenKeyEx(base, p)
-                except RegError:
-                    continue
-                key = RegEnumKey(h, 0)
-                d = Reg.get_value(base, r"{}\{}".format(p, key))
-                self.macros["$(FrameworkVersion)"] = d["version"]
-
-    def sub(self, s):
-        for k, v in self.macros.items():
-            s = s.replace(k, v)
-        return s
-
-
-def get_build_version():
-    """Return the version of MSVC that was used to build Python.
-
-    For Python 2.3 and up, the version number is included in
-    sys.version.  For earlier versions, assume the compiler is MSVC 6.
-    """
-    prefix = "MSC v."
-    i = sys.version.find(prefix)
-    if i == -1:
-        return 6
-    i = i + len(prefix)
-    s, rest = sys.version[i:].split(" ", 1)
-    majorVersion = int(s[:-2]) - 6
-    if majorVersion >= 13:
-        # v13 was skipped and should be v14
-        majorVersion += 1
-    minorVersion = int(s[2:3]) / 10.0
-    # I don't think paths are affected by minor version in version 6
-    if majorVersion == 6:
-        minorVersion = 0
-    if majorVersion >= 6:
-        return majorVersion + minorVersion
-    # else we don't know what version of the compiler this is
-    return None
-
-
-def normalize_and_reduce_paths(paths):
-    """Return a list of normalized paths with duplicates removed.
-
-    The current order of paths is maintained.
-    """
-    # Paths are normalized so things like:  /a and /a/ aren't both preserved.
-    reduced_paths = []
-    for p in paths:
-        np = os.path.normpath(p)
-        # XXX(nnorwitz): O(n**2), if reduced_paths gets long perhaps use a set.
-        if np not in reduced_paths:
-            reduced_paths.append(np)
-    return reduced_paths
-
-
-def removeDuplicates(variable):
-    """Remove duplicate values of an environment variable."""
-    oldList = variable.split(os.pathsep)
-    newList = []
-    for i in oldList:
-        if i not in newList:
-            newList.append(i)
-    newVariable = os.pathsep.join(newList)
-    return newVariable
-
-
-def find_vcvarsall(version):
-    """Find the vcvarsall.bat file
-
-    At first it tries to find the productdir of VS 2008 in the registry. If
-    that fails it falls back to the VS90COMNTOOLS env var.
-    """
-    vsbase = VS_BASE % version
-    try:
-        productdir = Reg.get_value(r"%s\Setup\VC" % vsbase, "productdir")
-    except KeyError:
-        log.debug("Unable to find productdir in registry")
-        productdir = None
-
-    if not productdir or not os.path.isdir(productdir):
-        toolskey = "VS%0.f0COMNTOOLS" % version
-        toolsdir = os.environ.get(toolskey, None)
-
-        if toolsdir and os.path.isdir(toolsdir):
-            productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC")
-            productdir = os.path.abspath(productdir)
-            if not os.path.isdir(productdir):
-                log.debug("%s is not a valid directory" % productdir)
-                return None
-        else:
-            log.debug("Env var %s is not set or invalid" % toolskey)
-    if not productdir:
-        log.debug("No productdir found")
-        return None
-    vcvarsall = os.path.join(productdir, "vcvarsall.bat")
-    if os.path.isfile(vcvarsall):
-        return vcvarsall
-    log.debug("Unable to find vcvarsall.bat")
-    return None
-
-
-def query_vcvarsall(version, arch="x86"):
-    """Launch vcvarsall.bat and read the settings from its environment"""
-    vcvarsall = find_vcvarsall(version)
-    interesting = {"include", "lib", "libpath", "path"}
-    result = {}
-
-    if vcvarsall is None:
-        raise DistutilsPlatformError("Unable to find vcvarsall.bat")
-    log.debug("Calling 'vcvarsall.bat %s' (version=%s)", arch, version)
-    popen = subprocess.Popen(
-        '"{}" {} & set'.format(vcvarsall, arch),
-        stdout=subprocess.PIPE,
-        stderr=subprocess.PIPE,
-    )
-    try:
-        stdout, stderr = popen.communicate()
-        if popen.wait() != 0:
-            raise DistutilsPlatformError(stderr.decode("mbcs"))
-
-        stdout = stdout.decode("mbcs")
-        for line in stdout.split("\n"):
-            line = Reg.convert_mbcs(line)
-            if '=' not in line:
-                continue
-            line = line.strip()
-            key, value = line.split('=', 1)
-            key = key.lower()
-            if key in interesting:
-                if value.endswith(os.pathsep):
-                    value = value[:-1]
-                result[key] = removeDuplicates(value)
-
-    finally:
-        popen.stdout.close()
-        popen.stderr.close()
-
-    if len(result) != len(interesting):
-        raise ValueError(str(list(result.keys())))
-
-    return result
-
-
-# More globals
-VERSION = get_build_version()
-# MACROS = MacroExpander(VERSION)
-
-
-class MSVCCompiler(CCompiler):
-    """Concrete class that implements an interface to Microsoft Visual C++,
-    as defined by the CCompiler abstract class."""
-
-    compiler_type = 'msvc'
-
-    # Just set this so CCompiler's constructor doesn't barf.  We currently
-    # don't use the 'set_executables()' bureaucracy provided by CCompiler,
-    # as it really isn't necessary for this sort of single-compiler class.
-    # Would be nice to have a consistent interface with UnixCCompiler,
-    # though, so it's worth thinking about.
-    executables = {}
-
-    # Private class data (need to distinguish C from C++ source for compiler)
-    _c_extensions = ['.c']
-    _cpp_extensions = ['.cc', '.cpp', '.cxx']
-    _rc_extensions = ['.rc']
-    _mc_extensions = ['.mc']
-
-    # Needed for the filename generation methods provided by the
-    # base class, CCompiler.
-    src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions
-    res_extension = '.res'
-    obj_extension = '.obj'
-    static_lib_extension = '.lib'
-    shared_lib_extension = '.dll'
-    static_lib_format = shared_lib_format = '%s%s'
-    exe_extension = '.exe'
-
-    def __init__(self, verbose=0, dry_run=0, force=0):
-        super().__init__(verbose, dry_run, force)
-        self.__version = VERSION
-        self.__root = r"Software\Microsoft\VisualStudio"
-        # self.__macros = MACROS
-        self.__paths = []
-        # target platform (.plat_name is consistent with 'bdist')
-        self.plat_name = None
-        self.__arch = None  # deprecated name
-        self.initialized = False
-
-    def initialize(self, plat_name=None):  # noqa: C901
-        # multi-init means we would need to check platform same each time...
-        assert not self.initialized, "don't init multiple times"
-        if self.__version < 8.0:
-            raise DistutilsPlatformError(
-                "VC %0.1f is not supported by this module" % self.__version
-            )
-        if plat_name is None:
-            plat_name = get_platform()
-        # sanity check for platforms to prevent obscure errors later.
-        ok_plats = 'win32', 'win-amd64'
-        if plat_name not in ok_plats:
-            raise DistutilsPlatformError(
-                "--plat-name must be one of {}".format(ok_plats)
-            )
-
-        if (
-            "DISTUTILS_USE_SDK" in os.environ
-            and "MSSdk" in os.environ
-            and self.find_exe("cl.exe")
-        ):
-            # Assume that the SDK set up everything alright; don't try to be
-            # smarter
-            self.cc = "cl.exe"
-            self.linker = "link.exe"
-            self.lib = "lib.exe"
-            self.rc = "rc.exe"
-            self.mc = "mc.exe"
-        else:
-            # On x86, 'vcvars32.bat amd64' creates an env that doesn't work;
-            # to cross compile, you use 'x86_amd64'.
-            # On AMD64, 'vcvars32.bat amd64' is a native build env; to cross
-            # compile use 'x86' (ie, it runs the x86 compiler directly)
-            if plat_name in (get_platform(), 'win32'):
-                # native build or cross-compile to win32
-                plat_spec = PLAT_TO_VCVARS[plat_name]
-            else:
-                # cross compile from win32 -> some 64bit
-                plat_spec = (
-                    PLAT_TO_VCVARS[get_platform()] + '_' + PLAT_TO_VCVARS[plat_name]
-                )
-
-            vc_env = query_vcvarsall(VERSION, plat_spec)
-
-            self.__paths = vc_env['path'].split(os.pathsep)
-            os.environ['lib'] = vc_env['lib']
-            os.environ['include'] = vc_env['include']
-
-            if len(self.__paths) == 0:
-                raise DistutilsPlatformError(
-                    "Python was built with %s, "
-                    "and extensions need to be built with the same "
-                    "version of the compiler, but it isn't installed." % self.__product
-                )
-
-            self.cc = self.find_exe("cl.exe")
-            self.linker = self.find_exe("link.exe")
-            self.lib = self.find_exe("lib.exe")
-            self.rc = self.find_exe("rc.exe")  # resource compiler
-            self.mc = self.find_exe("mc.exe")  # message compiler
-            # self.set_path_env_var('lib')
-            # self.set_path_env_var('include')
-
-        # extend the MSVC path with the current path
-        try:
-            for p in os.environ['path'].split(';'):
-                self.__paths.append(p)
-        except KeyError:
-            pass
-        self.__paths = normalize_and_reduce_paths(self.__paths)
-        os.environ['path'] = ";".join(self.__paths)
-
-        self.preprocess_options = None
-        if self.__arch == "x86":
-            self.compile_options = ['/nologo', '/O2', '/MD', '/W3', '/DNDEBUG']
-            self.compile_options_debug = [
-                '/nologo',
-                '/Od',
-                '/MDd',
-                '/W3',
-                '/Z7',
-                '/D_DEBUG',
-            ]
-        else:
-            # Win64
-            self.compile_options = ['/nologo', '/O2', '/MD', '/W3', '/GS-', '/DNDEBUG']
-            self.compile_options_debug = [
-                '/nologo',
-                '/Od',
-                '/MDd',
-                '/W3',
-                '/GS-',
-                '/Z7',
-                '/D_DEBUG',
-            ]
-
-        self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']
-        if self.__version >= 7:
-            self.ldflags_shared_debug = ['/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG']
-        self.ldflags_static = ['/nologo']
-
-        self.initialized = True
-
-    # -- Worker methods ------------------------------------------------
-
-    def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
-        # Copied from ccompiler.py, extended to return .res as 'object'-file
-        # for .rc input file
-        if output_dir is None:
-            output_dir = ''
-        obj_names = []
-        for src_name in source_filenames:
-            (base, ext) = os.path.splitext(src_name)
-            base = os.path.splitdrive(base)[1]  # Chop off the drive
-            base = base[os.path.isabs(base) :]  # If abs, chop off leading /
-            if ext not in self.src_extensions:
-                # Better to raise an exception instead of silently continuing
-                # and later complain about sources and targets having
-                # different lengths
-                raise CompileError("Don't know how to compile %s" % src_name)
-            if strip_dir:
-                base = os.path.basename(base)
-            if ext in self._rc_extensions:
-                obj_names.append(os.path.join(output_dir, base + self.res_extension))
-            elif ext in self._mc_extensions:
-                obj_names.append(os.path.join(output_dir, base + self.res_extension))
-            else:
-                obj_names.append(os.path.join(output_dir, base + self.obj_extension))
-        return obj_names
-
-    def compile(  # noqa: C901
-        self,
-        sources,
-        output_dir=None,
-        macros=None,
-        include_dirs=None,
-        debug=0,
-        extra_preargs=None,
-        extra_postargs=None,
-        depends=None,
-    ):
-        if not self.initialized:
-            self.initialize()
-        compile_info = self._setup_compile(
-            output_dir, macros, include_dirs, sources, depends, extra_postargs
-        )
-        macros, objects, extra_postargs, pp_opts, build = compile_info
-
-        compile_opts = extra_preargs or []
-        compile_opts.append('/c')
-        if debug:
-            compile_opts.extend(self.compile_options_debug)
-        else:
-            compile_opts.extend(self.compile_options)
-
-        for obj in objects:
-            try:
-                src, ext = build[obj]
-            except KeyError:
-                continue
-            if debug:
-                # pass the full pathname to MSVC in debug mode,
-                # this allows the debugger to find the source file
-                # without asking the user to browse for it
-                src = os.path.abspath(src)
-
-            if ext in self._c_extensions:
-                input_opt = "/Tc" + src
-            elif ext in self._cpp_extensions:
-                input_opt = "/Tp" + src
-            elif ext in self._rc_extensions:
-                # compile .RC to .RES file
-                input_opt = src
-                output_opt = "/fo" + obj
-                try:
-                    self.spawn([self.rc] + pp_opts + [output_opt] + [input_opt])
-                except DistutilsExecError as msg:
-                    raise CompileError(msg)
-                continue
-            elif ext in self._mc_extensions:
-                # Compile .MC to .RC file to .RES file.
-                #   * '-h dir' specifies the directory for the
-                #     generated include file
-                #   * '-r dir' specifies the target directory of the
-                #     generated RC file and the binary message resource
-                #     it includes
-                #
-                # For now (since there are no options to change this),
-                # we use the source-directory for the include file and
-                # the build directory for the RC file and message
-                # resources. This works at least for win32all.
-                h_dir = os.path.dirname(src)
-                rc_dir = os.path.dirname(obj)
-                try:
-                    # first compile .MC to .RC and .H file
-                    self.spawn([self.mc] + ['-h', h_dir, '-r', rc_dir] + [src])
-                    base, _ = os.path.splitext(os.path.basename(src))
-                    rc_file = os.path.join(rc_dir, base + '.rc')
-                    # then compile .RC to .RES file
-                    self.spawn([self.rc] + ["/fo" + obj] + [rc_file])
-
-                except DistutilsExecError as msg:
-                    raise CompileError(msg)
-                continue
-            else:
-                # how to handle this file?
-                raise CompileError(
-                    "Don't know how to compile {} to {}".format(src, obj)
-                )
-
-            output_opt = "/Fo" + obj
-            try:
-                self.spawn(
-                    [self.cc]
-                    + compile_opts
-                    + pp_opts
-                    + [input_opt, output_opt]
-                    + extra_postargs
-                )
-            except DistutilsExecError as msg:
-                raise CompileError(msg)
-
-        return objects
-
-    def create_static_lib(
-        self, objects, output_libname, output_dir=None, debug=0, target_lang=None
-    ):
-        if not self.initialized:
-            self.initialize()
-        (objects, output_dir) = self._fix_object_args(objects, output_dir)
-        output_filename = self.library_filename(output_libname, output_dir=output_dir)
-
-        if self._need_link(objects, output_filename):
-            lib_args = objects + ['/OUT:' + output_filename]
-            if debug:
-                pass  # XXX what goes here?
-            try:
-                self.spawn([self.lib] + lib_args)
-            except DistutilsExecError as msg:
-                raise LibError(msg)
-        else:
-            log.debug("skipping %s (up-to-date)", output_filename)
-
-    def link(  # noqa: C901
-        self,
-        target_desc,
-        objects,
-        output_filename,
-        output_dir=None,
-        libraries=None,
-        library_dirs=None,
-        runtime_library_dirs=None,
-        export_symbols=None,
-        debug=0,
-        extra_preargs=None,
-        extra_postargs=None,
-        build_temp=None,
-        target_lang=None,
-    ):
-        if not self.initialized:
-            self.initialize()
-        (objects, output_dir) = self._fix_object_args(objects, output_dir)
-        fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
-        (libraries, library_dirs, runtime_library_dirs) = fixed_args
-
-        if runtime_library_dirs:
-            self.warn(
-                "I don't know what to do with 'runtime_library_dirs': "
-                + str(runtime_library_dirs)
-            )
-
-        lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
-        if output_dir is not None:
-            output_filename = os.path.join(output_dir, output_filename)
-
-        if self._need_link(objects, output_filename):
-            if target_desc == CCompiler.EXECUTABLE:
-                if debug:
-                    ldflags = self.ldflags_shared_debug[1:]
-                else:
-                    ldflags = self.ldflags_shared[1:]
-            else:
-                if debug:
-                    ldflags = self.ldflags_shared_debug
-                else:
-                    ldflags = self.ldflags_shared
-
-            export_opts = []
-            for sym in export_symbols or []:
-                export_opts.append("/EXPORT:" + sym)
-
-            ld_args = (
-                ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename]
-            )
-
-            # The MSVC linker generates .lib and .exp files, which cannot be
-            # suppressed by any linker switches. The .lib files may even be
-            # needed! Make sure they are generated in the temporary build
-            # directory. Since they have different names for debug and release
-            # builds, they can go into the same directory.
-            build_temp = os.path.dirname(objects[0])
-            if export_symbols is not None:
-                (dll_name, dll_ext) = os.path.splitext(
-                    os.path.basename(output_filename)
-                )
-                implib_file = os.path.join(build_temp, self.library_filename(dll_name))
-                ld_args.append('/IMPLIB:' + implib_file)
-
-            self.manifest_setup_ldargs(output_filename, build_temp, ld_args)
-
-            if extra_preargs:
-                ld_args[:0] = extra_preargs
-            if extra_postargs:
-                ld_args.extend(extra_postargs)
-
-            self.mkpath(os.path.dirname(output_filename))
-            try:
-                self.spawn([self.linker] + ld_args)
-            except DistutilsExecError as msg:
-                raise LinkError(msg)
-
-            # embed the manifest
-            # XXX - this is somewhat fragile - if mt.exe fails, distutils
-            # will still consider the DLL up-to-date, but it will not have a
-            # manifest.  Maybe we should link to a temp file?  OTOH, that
-            # implies a build environment error that shouldn't go undetected.
-            mfinfo = self.manifest_get_embed_info(target_desc, ld_args)
-            if mfinfo is not None:
-                mffilename, mfid = mfinfo
-                out_arg = '-outputresource:{};{}'.format(output_filename, mfid)
-                try:
-                    self.spawn(['mt.exe', '-nologo', '-manifest', mffilename, out_arg])
-                except DistutilsExecError as msg:
-                    raise LinkError(msg)
-        else:
-            log.debug("skipping %s (up-to-date)", output_filename)
-
-    def manifest_setup_ldargs(self, output_filename, build_temp, ld_args):
-        # If we need a manifest at all, an embedded manifest is recommended.
-        # See MSDN article titled
-        # "How to: Embed a Manifest Inside a C/C++ Application"
-        # (currently at http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx)
-        # Ask the linker to generate the manifest in the temp dir, so
-        # we can check it, and possibly embed it, later.
-        temp_manifest = os.path.join(
-            build_temp, os.path.basename(output_filename) + ".manifest"
-        )
-        ld_args.append('/MANIFESTFILE:' + temp_manifest)
-
-    def manifest_get_embed_info(self, target_desc, ld_args):
-        # If a manifest should be embedded, return a tuple of
-        # (manifest_filename, resource_id).  Returns None if no manifest
-        # should be embedded.  See http://bugs.python.org/issue7833 for why
-        # we want to avoid any manifest for extension modules if we can)
-        for arg in ld_args:
-            if arg.startswith("/MANIFESTFILE:"):
-                temp_manifest = arg.split(":", 1)[1]
-                break
-        else:
-            # no /MANIFESTFILE so nothing to do.
-            return None
-        if target_desc == CCompiler.EXECUTABLE:
-            # by default, executables always get the manifest with the
-            # CRT referenced.
-            mfid = 1
-        else:
-            # Extension modules try and avoid any manifest if possible.
-            mfid = 2
-            temp_manifest = self._remove_visual_c_ref(temp_manifest)
-        if temp_manifest is None:
-            return None
-        return temp_manifest, mfid
-
-    def _remove_visual_c_ref(self, manifest_file):
-        try:
-            # Remove references to the Visual C runtime, so they will
-            # fall through to the Visual C dependency of Python.exe.
-            # This way, when installed for a restricted user (e.g.
-            # runtimes are not in WinSxS folder, but in Python's own
-            # folder), the runtimes do not need to be in every folder
-            # with .pyd's.
-            # Returns either the filename of the modified manifest or
-            # None if no manifest should be embedded.
-            manifest_f = open(manifest_file)
-            try:
-                manifest_buf = manifest_f.read()
-            finally:
-                manifest_f.close()
-            pattern = re.compile(
-                r"""|)""",
-                re.DOTALL,
-            )
-            manifest_buf = re.sub(pattern, "", manifest_buf)
-            pattern = r"\s*"
-            manifest_buf = re.sub(pattern, "", manifest_buf)
-            # Now see if any other assemblies are referenced - if not, we
-            # don't want a manifest embedded.
-            pattern = re.compile(
-                r"""|)""",
-                re.DOTALL,
-            )
-            if re.search(pattern, manifest_buf) is None:
-                return None
-
-            manifest_f = open(manifest_file, 'w')
-            try:
-                manifest_f.write(manifest_buf)
-                return manifest_file
-            finally:
-                manifest_f.close()
-        except OSError:
-            pass
-
-    # -- Miscellaneous methods -----------------------------------------
-    # These are all used by the 'gen_lib_options() function, in
-    # ccompiler.py.
-
-    def library_dir_option(self, dir):
-        return "/LIBPATH:" + dir
-
-    def runtime_library_dir_option(self, dir):
-        raise DistutilsPlatformError(
-            "don't know how to set runtime library search path for MSVC++"
-        )
-
-    def library_option(self, lib):
-        return self.library_filename(lib)
-
-    def find_library_file(self, dirs, lib, debug=0):
-        # Prefer a debugging library if found (and requested), but deal
-        # with it if we don't have one.
-        if debug:
-            try_names = [lib + "_d", lib]
-        else:
-            try_names = [lib]
-        for dir in dirs:
-            for name in try_names:
-                libfile = os.path.join(dir, self.library_filename(name))
-                if os.path.exists(libfile):
-                    return libfile
-        else:
-            # Oops, didn't find it in *any* of 'dirs'
-            return None
-
-    # Helper methods for using the MSVC registry settings
-
-    def find_exe(self, exe):
-        """Return path to an MSVC executable program.
-
-        Tries to find the program in several places: first, one of the
-        MSVC program search paths from the registry; next, the directories
-        in the PATH environment variable.  If any of those work, return an
-        absolute path that is known to exist.  If none of them work, just
-        return the original program name, 'exe'.
-        """
-        for p in self.__paths:
-            fn = os.path.join(os.path.abspath(p), exe)
-            if os.path.isfile(fn):
-                return fn
-
-        # didn't find it; try existing path
-        for p in os.environ['Path'].split(';'):
-            fn = os.path.join(os.path.abspath(p), exe)
-            if os.path.isfile(fn):
-                return fn
-
-        return exe
diff --git a/setuptools/_distutils/msvccompiler.py b/setuptools/_distutils/msvccompiler.py
deleted file mode 100644
index c3823e257e..0000000000
--- a/setuptools/_distutils/msvccompiler.py
+++ /dev/null
@@ -1,692 +0,0 @@
-"""distutils.msvccompiler
-
-Contains MSVCCompiler, an implementation of the abstract CCompiler class
-for the Microsoft Visual Studio.
-"""
-
-# Written by Perry Stoll
-# hacked by Robin Becker and Thomas Heller to do a better job of
-#   finding DevStudio (through the registry)
-
-import sys
-import os
-import warnings
-from .errors import (
-    DistutilsExecError,
-    DistutilsPlatformError,
-    CompileError,
-    LibError,
-    LinkError,
-)
-from .ccompiler import CCompiler, gen_lib_options
-from ._log import log
-
-_can_read_reg = False
-try:
-    import winreg
-
-    _can_read_reg = True
-    hkey_mod = winreg
-
-    RegOpenKeyEx = winreg.OpenKeyEx
-    RegEnumKey = winreg.EnumKey
-    RegEnumValue = winreg.EnumValue
-    RegError = winreg.error
-
-except ImportError:
-    try:
-        import win32api
-        import win32con
-
-        _can_read_reg = True
-        hkey_mod = win32con
-
-        RegOpenKeyEx = win32api.RegOpenKeyEx
-        RegEnumKey = win32api.RegEnumKey
-        RegEnumValue = win32api.RegEnumValue
-        RegError = win32api.error
-    except ImportError:
-        log.info(
-            "Warning: Can't read registry to find the "
-            "necessary compiler setting\n"
-            "Make sure that Python modules winreg, "
-            "win32api or win32con are installed."
-        )
-        pass
-
-if _can_read_reg:
-    HKEYS = (
-        hkey_mod.HKEY_USERS,
-        hkey_mod.HKEY_CURRENT_USER,
-        hkey_mod.HKEY_LOCAL_MACHINE,
-        hkey_mod.HKEY_CLASSES_ROOT,
-    )
-
-
-warnings.warn(
-    "msvccompiler is deprecated and slated to be removed "
-    "in the future. Please discontinue use or file an issue "
-    "with pypa/distutils describing your use case.",
-    DeprecationWarning,
-)
-
-
-def read_keys(base, key):
-    """Return list of registry keys."""
-    try:
-        handle = RegOpenKeyEx(base, key)
-    except RegError:
-        return None
-    L = []
-    i = 0
-    while True:
-        try:
-            k = RegEnumKey(handle, i)
-        except RegError:
-            break
-        L.append(k)
-        i += 1
-    return L
-
-
-def read_values(base, key):
-    """Return dict of registry keys and values.
-
-    All names are converted to lowercase.
-    """
-    try:
-        handle = RegOpenKeyEx(base, key)
-    except RegError:
-        return None
-    d = {}
-    i = 0
-    while True:
-        try:
-            name, value, type = RegEnumValue(handle, i)
-        except RegError:
-            break
-        name = name.lower()
-        d[convert_mbcs(name)] = convert_mbcs(value)
-        i += 1
-    return d
-
-
-def convert_mbcs(s):
-    dec = getattr(s, "decode", None)
-    if dec is not None:
-        try:
-            s = dec("mbcs")
-        except UnicodeError:
-            pass
-    return s
-
-
-class MacroExpander:
-    def __init__(self, version):
-        self.macros = {}
-        self.load_macros(version)
-
-    def set_macro(self, macro, path, key):
-        for base in HKEYS:
-            d = read_values(base, path)
-            if d:
-                self.macros["$(%s)" % macro] = d[key]
-                break
-
-    def load_macros(self, version):
-        vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version
-        self.set_macro("VCInstallDir", vsbase + r"\Setup\VC", "productdir")
-        self.set_macro("VSInstallDir", vsbase + r"\Setup\VS", "productdir")
-        net = r"Software\Microsoft\.NETFramework"
-        self.set_macro("FrameworkDir", net, "installroot")
-        try:
-            if version > 7.0:
-                self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")
-            else:
-                self.set_macro("FrameworkSDKDir", net, "sdkinstallroot")
-        except KeyError:
-            raise DistutilsPlatformError(
-                """Python was built with Visual Studio 2003;
-extensions must be built with a compiler than can generate compatible binaries.
-Visual Studio 2003 was not found on this system. If you have Cygwin installed,
-you can try compiling with MingW32, by passing "-c mingw32" to setup.py."""
-            )
-
-        p = r"Software\Microsoft\NET Framework Setup\Product"
-        for base in HKEYS:
-            try:
-                h = RegOpenKeyEx(base, p)
-            except RegError:
-                continue
-            key = RegEnumKey(h, 0)
-            d = read_values(base, r"{}\{}".format(p, key))
-            self.macros["$(FrameworkVersion)"] = d["version"]
-
-    def sub(self, s):
-        for k, v in self.macros.items():
-            s = s.replace(k, v)
-        return s
-
-
-def get_build_version():
-    """Return the version of MSVC that was used to build Python.
-
-    For Python 2.3 and up, the version number is included in
-    sys.version.  For earlier versions, assume the compiler is MSVC 6.
-    """
-    prefix = "MSC v."
-    i = sys.version.find(prefix)
-    if i == -1:
-        return 6
-    i = i + len(prefix)
-    s, rest = sys.version[i:].split(" ", 1)
-    majorVersion = int(s[:-2]) - 6
-    if majorVersion >= 13:
-        # v13 was skipped and should be v14
-        majorVersion += 1
-    minorVersion = int(s[2:3]) / 10.0
-    # I don't think paths are affected by minor version in version 6
-    if majorVersion == 6:
-        minorVersion = 0
-    if majorVersion >= 6:
-        return majorVersion + minorVersion
-    # else we don't know what version of the compiler this is
-    return None
-
-
-def get_build_architecture():
-    """Return the processor architecture.
-
-    Possible results are "Intel" or "AMD64".
-    """
-
-    prefix = " bit ("
-    i = sys.version.find(prefix)
-    if i == -1:
-        return "Intel"
-    j = sys.version.find(")", i)
-    return sys.version[i + len(prefix) : j]
-
-
-def normalize_and_reduce_paths(paths):
-    """Return a list of normalized paths with duplicates removed.
-
-    The current order of paths is maintained.
-    """
-    # Paths are normalized so things like:  /a and /a/ aren't both preserved.
-    reduced_paths = []
-    for p in paths:
-        np = os.path.normpath(p)
-        # XXX(nnorwitz): O(n**2), if reduced_paths gets long perhaps use a set.
-        if np not in reduced_paths:
-            reduced_paths.append(np)
-    return reduced_paths
-
-
-class MSVCCompiler(CCompiler):
-    """Concrete class that implements an interface to Microsoft Visual C++,
-    as defined by the CCompiler abstract class."""
-
-    compiler_type = 'msvc'
-
-    # Just set this so CCompiler's constructor doesn't barf.  We currently
-    # don't use the 'set_executables()' bureaucracy provided by CCompiler,
-    # as it really isn't necessary for this sort of single-compiler class.
-    # Would be nice to have a consistent interface with UnixCCompiler,
-    # though, so it's worth thinking about.
-    executables = {}
-
-    # Private class data (need to distinguish C from C++ source for compiler)
-    _c_extensions = ['.c']
-    _cpp_extensions = ['.cc', '.cpp', '.cxx']
-    _rc_extensions = ['.rc']
-    _mc_extensions = ['.mc']
-
-    # Needed for the filename generation methods provided by the
-    # base class, CCompiler.
-    src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions
-    res_extension = '.res'
-    obj_extension = '.obj'
-    static_lib_extension = '.lib'
-    shared_lib_extension = '.dll'
-    static_lib_format = shared_lib_format = '%s%s'
-    exe_extension = '.exe'
-
-    def __init__(self, verbose=0, dry_run=0, force=0):
-        super().__init__(verbose, dry_run, force)
-        self.__version = get_build_version()
-        self.__arch = get_build_architecture()
-        if self.__arch == "Intel":
-            # x86
-            if self.__version >= 7:
-                self.__root = r"Software\Microsoft\VisualStudio"
-                self.__macros = MacroExpander(self.__version)
-            else:
-                self.__root = r"Software\Microsoft\Devstudio"
-            self.__product = "Visual Studio version %s" % self.__version
-        else:
-            # Win64. Assume this was built with the platform SDK
-            self.__product = "Microsoft SDK compiler %s" % (self.__version + 6)
-
-        self.initialized = False
-
-    def initialize(self):
-        self.__paths = []
-        if (
-            "DISTUTILS_USE_SDK" in os.environ
-            and "MSSdk" in os.environ
-            and self.find_exe("cl.exe")
-        ):
-            # Assume that the SDK set up everything alright; don't try to be
-            # smarter
-            self.cc = "cl.exe"
-            self.linker = "link.exe"
-            self.lib = "lib.exe"
-            self.rc = "rc.exe"
-            self.mc = "mc.exe"
-        else:
-            self.__paths = self.get_msvc_paths("path")
-
-            if len(self.__paths) == 0:
-                raise DistutilsPlatformError(
-                    "Python was built with %s, "
-                    "and extensions need to be built with the same "
-                    "version of the compiler, but it isn't installed." % self.__product
-                )
-
-            self.cc = self.find_exe("cl.exe")
-            self.linker = self.find_exe("link.exe")
-            self.lib = self.find_exe("lib.exe")
-            self.rc = self.find_exe("rc.exe")  # resource compiler
-            self.mc = self.find_exe("mc.exe")  # message compiler
-            self.set_path_env_var('lib')
-            self.set_path_env_var('include')
-
-        # extend the MSVC path with the current path
-        try:
-            for p in os.environ['path'].split(';'):
-                self.__paths.append(p)
-        except KeyError:
-            pass
-        self.__paths = normalize_and_reduce_paths(self.__paths)
-        os.environ['path'] = ";".join(self.__paths)
-
-        self.preprocess_options = None
-        if self.__arch == "Intel":
-            self.compile_options = ['/nologo', '/O2', '/MD', '/W3', '/GX', '/DNDEBUG']
-            self.compile_options_debug = [
-                '/nologo',
-                '/Od',
-                '/MDd',
-                '/W3',
-                '/GX',
-                '/Z7',
-                '/D_DEBUG',
-            ]
-        else:
-            # Win64
-            self.compile_options = ['/nologo', '/O2', '/MD', '/W3', '/GS-', '/DNDEBUG']
-            self.compile_options_debug = [
-                '/nologo',
-                '/Od',
-                '/MDd',
-                '/W3',
-                '/GS-',
-                '/Z7',
-                '/D_DEBUG',
-            ]
-
-        self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']
-        if self.__version >= 7:
-            self.ldflags_shared_debug = ['/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG']
-        else:
-            self.ldflags_shared_debug = [
-                '/DLL',
-                '/nologo',
-                '/INCREMENTAL:no',
-                '/pdb:None',
-                '/DEBUG',
-            ]
-        self.ldflags_static = ['/nologo']
-
-        self.initialized = True
-
-    # -- Worker methods ------------------------------------------------
-
-    def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
-        # Copied from ccompiler.py, extended to return .res as 'object'-file
-        # for .rc input file
-        if output_dir is None:
-            output_dir = ''
-        obj_names = []
-        for src_name in source_filenames:
-            (base, ext) = os.path.splitext(src_name)
-            base = os.path.splitdrive(base)[1]  # Chop off the drive
-            base = base[os.path.isabs(base) :]  # If abs, chop off leading /
-            if ext not in self.src_extensions:
-                # Better to raise an exception instead of silently continuing
-                # and later complain about sources and targets having
-                # different lengths
-                raise CompileError("Don't know how to compile %s" % src_name)
-            if strip_dir:
-                base = os.path.basename(base)
-            if ext in self._rc_extensions:
-                obj_names.append(os.path.join(output_dir, base + self.res_extension))
-            elif ext in self._mc_extensions:
-                obj_names.append(os.path.join(output_dir, base + self.res_extension))
-            else:
-                obj_names.append(os.path.join(output_dir, base + self.obj_extension))
-        return obj_names
-
-    def compile(  # noqa: C901
-        self,
-        sources,
-        output_dir=None,
-        macros=None,
-        include_dirs=None,
-        debug=0,
-        extra_preargs=None,
-        extra_postargs=None,
-        depends=None,
-    ):
-        if not self.initialized:
-            self.initialize()
-        compile_info = self._setup_compile(
-            output_dir, macros, include_dirs, sources, depends, extra_postargs
-        )
-        macros, objects, extra_postargs, pp_opts, build = compile_info
-
-        compile_opts = extra_preargs or []
-        compile_opts.append('/c')
-        if debug:
-            compile_opts.extend(self.compile_options_debug)
-        else:
-            compile_opts.extend(self.compile_options)
-
-        for obj in objects:
-            try:
-                src, ext = build[obj]
-            except KeyError:
-                continue
-            if debug:
-                # pass the full pathname to MSVC in debug mode,
-                # this allows the debugger to find the source file
-                # without asking the user to browse for it
-                src = os.path.abspath(src)
-
-            if ext in self._c_extensions:
-                input_opt = "/Tc" + src
-            elif ext in self._cpp_extensions:
-                input_opt = "/Tp" + src
-            elif ext in self._rc_extensions:
-                # compile .RC to .RES file
-                input_opt = src
-                output_opt = "/fo" + obj
-                try:
-                    self.spawn([self.rc] + pp_opts + [output_opt] + [input_opt])
-                except DistutilsExecError as msg:
-                    raise CompileError(msg)
-                continue
-            elif ext in self._mc_extensions:
-                # Compile .MC to .RC file to .RES file.
-                #   * '-h dir' specifies the directory for the
-                #     generated include file
-                #   * '-r dir' specifies the target directory of the
-                #     generated RC file and the binary message resource
-                #     it includes
-                #
-                # For now (since there are no options to change this),
-                # we use the source-directory for the include file and
-                # the build directory for the RC file and message
-                # resources. This works at least for win32all.
-                h_dir = os.path.dirname(src)
-                rc_dir = os.path.dirname(obj)
-                try:
-                    # first compile .MC to .RC and .H file
-                    self.spawn([self.mc] + ['-h', h_dir, '-r', rc_dir] + [src])
-                    base, _ = os.path.splitext(os.path.basename(src))
-                    rc_file = os.path.join(rc_dir, base + '.rc')
-                    # then compile .RC to .RES file
-                    self.spawn([self.rc] + ["/fo" + obj] + [rc_file])
-
-                except DistutilsExecError as msg:
-                    raise CompileError(msg)
-                continue
-            else:
-                # how to handle this file?
-                raise CompileError(
-                    "Don't know how to compile {} to {}".format(src, obj)
-                )
-
-            output_opt = "/Fo" + obj
-            try:
-                self.spawn(
-                    [self.cc]
-                    + compile_opts
-                    + pp_opts
-                    + [input_opt, output_opt]
-                    + extra_postargs
-                )
-            except DistutilsExecError as msg:
-                raise CompileError(msg)
-
-        return objects
-
-    def create_static_lib(
-        self, objects, output_libname, output_dir=None, debug=0, target_lang=None
-    ):
-        if not self.initialized:
-            self.initialize()
-        (objects, output_dir) = self._fix_object_args(objects, output_dir)
-        output_filename = self.library_filename(output_libname, output_dir=output_dir)
-
-        if self._need_link(objects, output_filename):
-            lib_args = objects + ['/OUT:' + output_filename]
-            if debug:
-                pass  # XXX what goes here?
-            try:
-                self.spawn([self.lib] + lib_args)
-            except DistutilsExecError as msg:
-                raise LibError(msg)
-        else:
-            log.debug("skipping %s (up-to-date)", output_filename)
-
-    def link(  # noqa: C901
-        self,
-        target_desc,
-        objects,
-        output_filename,
-        output_dir=None,
-        libraries=None,
-        library_dirs=None,
-        runtime_library_dirs=None,
-        export_symbols=None,
-        debug=0,
-        extra_preargs=None,
-        extra_postargs=None,
-        build_temp=None,
-        target_lang=None,
-    ):
-        if not self.initialized:
-            self.initialize()
-        (objects, output_dir) = self._fix_object_args(objects, output_dir)
-        fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
-        (libraries, library_dirs, runtime_library_dirs) = fixed_args
-
-        if runtime_library_dirs:
-            self.warn(
-                "I don't know what to do with 'runtime_library_dirs': "
-                + str(runtime_library_dirs)
-            )
-
-        lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
-        if output_dir is not None:
-            output_filename = os.path.join(output_dir, output_filename)
-
-        if self._need_link(objects, output_filename):
-            if target_desc == CCompiler.EXECUTABLE:
-                if debug:
-                    ldflags = self.ldflags_shared_debug[1:]
-                else:
-                    ldflags = self.ldflags_shared[1:]
-            else:
-                if debug:
-                    ldflags = self.ldflags_shared_debug
-                else:
-                    ldflags = self.ldflags_shared
-
-            export_opts = []
-            for sym in export_symbols or []:
-                export_opts.append("/EXPORT:" + sym)
-
-            ld_args = (
-                ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename]
-            )
-
-            # The MSVC linker generates .lib and .exp files, which cannot be
-            # suppressed by any linker switches. The .lib files may even be
-            # needed! Make sure they are generated in the temporary build
-            # directory. Since they have different names for debug and release
-            # builds, they can go into the same directory.
-            if export_symbols is not None:
-                (dll_name, dll_ext) = os.path.splitext(
-                    os.path.basename(output_filename)
-                )
-                implib_file = os.path.join(
-                    os.path.dirname(objects[0]), self.library_filename(dll_name)
-                )
-                ld_args.append('/IMPLIB:' + implib_file)
-
-            if extra_preargs:
-                ld_args[:0] = extra_preargs
-            if extra_postargs:
-                ld_args.extend(extra_postargs)
-
-            self.mkpath(os.path.dirname(output_filename))
-            try:
-                self.spawn([self.linker] + ld_args)
-            except DistutilsExecError as msg:
-                raise LinkError(msg)
-
-        else:
-            log.debug("skipping %s (up-to-date)", output_filename)
-
-    # -- Miscellaneous methods -----------------------------------------
-    # These are all used by the 'gen_lib_options() function, in
-    # ccompiler.py.
-
-    def library_dir_option(self, dir):
-        return "/LIBPATH:" + dir
-
-    def runtime_library_dir_option(self, dir):
-        raise DistutilsPlatformError(
-            "don't know how to set runtime library search path for MSVC++"
-        )
-
-    def library_option(self, lib):
-        return self.library_filename(lib)
-
-    def find_library_file(self, dirs, lib, debug=0):
-        # Prefer a debugging library if found (and requested), but deal
-        # with it if we don't have one.
-        if debug:
-            try_names = [lib + "_d", lib]
-        else:
-            try_names = [lib]
-        for dir in dirs:
-            for name in try_names:
-                libfile = os.path.join(dir, self.library_filename(name))
-                if os.path.exists(libfile):
-                    return libfile
-        else:
-            # Oops, didn't find it in *any* of 'dirs'
-            return None
-
-    # Helper methods for using the MSVC registry settings
-
-    def find_exe(self, exe):
-        """Return path to an MSVC executable program.
-
-        Tries to find the program in several places: first, one of the
-        MSVC program search paths from the registry; next, the directories
-        in the PATH environment variable.  If any of those work, return an
-        absolute path that is known to exist.  If none of them work, just
-        return the original program name, 'exe'.
-        """
-        for p in self.__paths:
-            fn = os.path.join(os.path.abspath(p), exe)
-            if os.path.isfile(fn):
-                return fn
-
-        # didn't find it; try existing path
-        for p in os.environ['Path'].split(';'):
-            fn = os.path.join(os.path.abspath(p), exe)
-            if os.path.isfile(fn):
-                return fn
-
-        return exe
-
-    def get_msvc_paths(self, path, platform='x86'):
-        """Get a list of devstudio directories (include, lib or path).
-
-        Return a list of strings.  The list will be empty if unable to
-        access the registry or appropriate registry keys not found.
-        """
-        if not _can_read_reg:
-            return []
-
-        path = path + " dirs"
-        if self.__version >= 7:
-            key = r"{}\{:0.1f}\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories".format(
-                self.__root,
-                self.__version,
-            )
-        else:
-            key = (
-                r"%s\6.0\Build System\Components\Platforms"
-                r"\Win32 (%s)\Directories" % (self.__root, platform)
-            )
-
-        for base in HKEYS:
-            d = read_values(base, key)
-            if d:
-                if self.__version >= 7:
-                    return self.__macros.sub(d[path]).split(";")
-                else:
-                    return d[path].split(";")
-        # MSVC 6 seems to create the registry entries we need only when
-        # the GUI is run.
-        if self.__version == 6:
-            for base in HKEYS:
-                if read_values(base, r"%s\6.0" % self.__root) is not None:
-                    self.warn(
-                        "It seems you have Visual Studio 6 installed, "
-                        "but the expected registry settings are not present.\n"
-                        "You must at least run the Visual Studio GUI once "
-                        "so that these entries are created."
-                    )
-                    break
-        return []
-
-    def set_path_env_var(self, name):
-        """Set environment variable 'name' to an MSVC path type value.
-
-        This is equivalent to a SET command prior to execution of spawned
-        commands.
-        """
-
-        if name == "lib":
-            p = self.get_msvc_paths("library")
-        else:
-            p = self.get_msvc_paths(name)
-        if p:
-            os.environ[name] = ';'.join(p)
-
-
-if get_build_version() >= 8.0:
-    log.debug("Importing new compiler from distutils.msvc9compiler")
-    OldMSVCCompiler = MSVCCompiler
-    from distutils.msvc9compiler import MSVCCompiler
-
-    # get_build_architecture not really relevant now we support cross-compile
-    from distutils.msvc9compiler import MacroExpander  # noqa: F811
diff --git a/setuptools/_distutils/py38compat.py b/setuptools/_distutils/py38compat.py
deleted file mode 100644
index 59224e71e5..0000000000
--- a/setuptools/_distutils/py38compat.py
+++ /dev/null
@@ -1,8 +0,0 @@
-def aix_platform(osname, version, release):
-    try:
-        import _aix_support
-
-        return _aix_support.aix_platform()
-    except ImportError:
-        pass
-    return "{}-{}.{}".format(osname, version, release)
diff --git a/setuptools/_distutils/py39compat.py b/setuptools/_distutils/py39compat.py
deleted file mode 100644
index c43e5f10fd..0000000000
--- a/setuptools/_distutils/py39compat.py
+++ /dev/null
@@ -1,22 +0,0 @@
-import sys
-import platform
-
-
-def add_ext_suffix_39(vars):
-    """
-    Ensure vars contains 'EXT_SUFFIX'. pypa/distutils#130
-    """
-    import _imp
-
-    ext_suffix = _imp.extension_suffixes()[0]
-    vars.update(
-        EXT_SUFFIX=ext_suffix,
-        # sysconfig sets SO to match EXT_SUFFIX, so maintain
-        # that expectation.
-        # https://github.com/python/cpython/blob/785cc6770588de087d09e89a69110af2542be208/Lib/sysconfig.py#L671-L673
-        SO=ext_suffix,
-    )
-
-
-needs_ext_suffix = sys.version_info < (3, 10) and platform.system() == 'Windows'
-add_ext_suffix = add_ext_suffix_39 if needs_ext_suffix else lambda vars: None
diff --git a/setuptools/_distutils/ruff.toml b/setuptools/_distutils/ruff.toml
new file mode 100644
index 0000000000..00fee625a5
--- /dev/null
+++ b/setuptools/_distutils/ruff.toml
@@ -0,0 +1 @@
+exclude = ["*"]
diff --git a/setuptools/_distutils/spawn.py b/setuptools/_distutils/spawn.py
index afefe525ef..e47f1d1927 100644
--- a/setuptools/_distutils/spawn.py
+++ b/setuptools/_distutils/spawn.py
@@ -2,20 +2,62 @@
 
 Provides the 'spawn()' function, a front-end to various platform-
 specific functions for launching another program in a sub-process.
-Also provides the 'find_executable()' to search the path for a given
-executable name.
 """
 
-import sys
+from __future__ import annotations
+
 import os
+import platform
+import shutil
 import subprocess
+import sys
+import warnings
+from collections.abc import Mapping, MutableSequence
+from typing import TYPE_CHECKING, TypeVar, overload
 
-from .errors import DistutilsExecError
-from .debug import DEBUG
 from ._log import log
+from .debug import DEBUG
+from .errors import DistutilsExecError
 
+if TYPE_CHECKING:
+    from subprocess import _ENV
+
+
+_MappingT = TypeVar("_MappingT", bound=Mapping)
+
+
+def _debug(cmd):
+    """
+    Render a subprocess command differently depending on DEBUG.
+    """
+    return cmd if DEBUG else cmd[0]
 
-def spawn(cmd, search_path=1, verbose=0, dry_run=0, env=None):  # noqa: C901
+
+def _inject_macos_ver(env: _MappingT | None) -> _MappingT | dict[str, str | int] | None:
+    if platform.system() != 'Darwin':
+        return env
+
+    from .util import MACOSX_VERSION_VAR, get_macosx_target_ver
+
+    target_ver = get_macosx_target_ver()
+    update = {MACOSX_VERSION_VAR: target_ver} if target_ver else {}
+    return {**_resolve(env), **update}
+
+
+@overload
+def _resolve(env: None) -> os._Environ[str]: ...
+@overload
+def _resolve(env: _MappingT) -> _MappingT: ...
+def _resolve(env: _MappingT | None) -> _MappingT | os._Environ[str]:
+    return os.environ if env is None else env
+
+
+def spawn(
+    cmd: MutableSequence[bytes | str | os.PathLike[str]],
+    search_path: bool = True,
+    verbose: bool = False,
+    env: _ENV | None = None,
+) -> None:
     """Run another program, specified as a command list 'cmd', in a new process.
 
     'cmd' is just the argument list for the new process, ie.
@@ -25,59 +67,39 @@ def spawn(cmd, search_path=1, verbose=0, dry_run=0, env=None):  # noqa: C901
 
     If 'search_path' is true (the default), the system's executable
     search path will be used to find the program; otherwise, cmd[0]
-    must be the exact path to the executable.  If 'dry_run' is true,
-    the command will not actually be run.
+    must be the exact path to the executable.
 
     Raise DistutilsExecError if running the program fails in any way; just
     return on success.
     """
-    # cmd is documented as a list, but just in case some code passes a tuple
-    # in, protect our %-formatting code against horrible death
-    cmd = list(cmd)
-
     log.info(subprocess.list2cmdline(cmd))
-    if dry_run:
-        return
 
     if search_path:
-        executable = find_executable(cmd[0])
+        executable = shutil.which(cmd[0])
         if executable is not None:
             cmd[0] = executable
 
-    env = env if env is not None else dict(os.environ)
-
-    if sys.platform == 'darwin':
-        from distutils.util import MACOSX_VERSION_VAR, get_macosx_target_ver
-
-        macosx_target_ver = get_macosx_target_ver()
-        if macosx_target_ver:
-            env[MACOSX_VERSION_VAR] = macosx_target_ver
-
     try:
-        proc = subprocess.Popen(cmd, env=env)
-        proc.wait()
-        exitcode = proc.returncode
+        subprocess.check_call(cmd, env=_inject_macos_ver(env))
     except OSError as exc:
-        if not DEBUG:
-            cmd = cmd[0]
         raise DistutilsExecError(
-            "command {!r} failed: {}".format(cmd, exc.args[-1])
+            f"command {_debug(cmd)!r} failed: {exc.args[-1]}"
         ) from exc
-
-    if exitcode:
-        if not DEBUG:
-            cmd = cmd[0]
+    except subprocess.CalledProcessError as err:
         raise DistutilsExecError(
-            "command {!r} failed with exit code {}".format(cmd, exitcode)
-        )
+            f"command {_debug(cmd)!r} failed with exit code {err.returncode}"
+        ) from err
 
 
-def find_executable(executable, path=None):
+def find_executable(executable: str, path: str | None = None) -> str | None:
     """Tries to find 'executable' in the directories listed in 'path'.
 
     A string listing directories separated by 'os.pathsep'; defaults to
     os.environ['PATH'].  Returns the complete filename or None if not found.
     """
+    warnings.warn(
+        'Use shutil.which instead of find_executable', DeprecationWarning, stacklevel=2
+    )
     _, ext = os.path.splitext(executable)
     if (sys.platform == 'win32') and (ext != '.exe'):
         executable = executable + '.exe'
@@ -87,14 +109,13 @@ def find_executable(executable, path=None):
 
     if path is None:
         path = os.environ.get('PATH', None)
+        # bpo-35755: Don't fall through if PATH is the empty string
         if path is None:
             try:
                 path = os.confstr("CS_PATH")
             except (AttributeError, ValueError):
                 # os.confstr() or CS_PATH is not available
                 path = os.defpath
-        # bpo-35755: Don't use os.defpath if the PATH environment variable is
-        # set to an empty string
 
     # PATH='' doesn't match, whereas PATH=':' looks in the current directory
     if not path:
diff --git a/setuptools/_distutils/sysconfig.py b/setuptools/_distutils/sysconfig.py
index a40a7231b3..7ddc869ab5 100644
--- a/setuptools/_distutils/sysconfig.py
+++ b/setuptools/_distutils/sysconfig.py
@@ -9,15 +9,30 @@
 Email:        
 """
 
+from __future__ import annotations
+
+import functools
 import os
+import pathlib
 import re
 import sys
 import sysconfig
-import pathlib
+from typing import TYPE_CHECKING, Literal, overload
+
+from jaraco.functools import pass_none
 
+from .ccompiler import CCompiler
+from .compat import py39
 from .errors import DistutilsPlatformError
-from . import py39compat
-from ._functools import pass_none
+from .util import is_mingw
+
+if TYPE_CHECKING:
+    from typing_extensions import deprecated
+else:
+
+    def deprecated(message):
+        return lambda fn: fn
+
 
 IS_PYPY = '__pypy__' in sys.builtin_module_names
 
@@ -104,10 +119,10 @@ def get_python_version():
     leaving off the patchlevel.  Sample return values could be '1.5'
     or '2.2'.
     """
-    return '%d.%d' % sys.version_info[:2]
+    return f'{sys.version_info.major}.{sys.version_info.minor}'
 
 
-def get_python_inc(plat_specific=0, prefix=None):
+def get_python_inc(plat_specific: bool = False, prefix: str | None = None) -> str:
     """Return the directory containing installed Python header files.
 
     If 'plat_specific' is false (the default), this is the path to the
@@ -120,12 +135,14 @@ def get_python_inc(plat_specific=0, prefix=None):
     """
     default_prefix = BASE_EXEC_PREFIX if plat_specific else BASE_PREFIX
     resolved_prefix = prefix if prefix is not None else default_prefix
+    # MinGW imitates posix like layout, but os.name != posix
+    os_name = "posix" if is_mingw() else os.name
     try:
-        getter = globals()[f'_get_python_inc_{os.name}']
+        getter = globals()[f'_get_python_inc_{os_name}']
     except KeyError:
         raise DistutilsPlatformError(
             "I don't know where Python installs its C header files "
-            "on platform '%s'" % os.name
+            f"on platform '{os.name}'"
         )
     return getter(resolved_prefix, prefix, plat_specific)
 
@@ -139,8 +156,6 @@ def _extant(path):
 
 
 def _get_python_inc_posix(prefix, spec_prefix, plat_specific):
-    if IS_PYPY and sys.version_info < (3, 8):
-        return os.path.join(prefix, 'include')
     return (
         _get_python_inc_posix_python(plat_specific)
         or _extant(_get_python_inc_from_config(plat_specific, spec_prefix))
@@ -195,12 +210,11 @@ def _get_python_inc_posix_prefix(prefix):
 
 def _get_python_inc_nt(prefix, spec_prefix, plat_specific):
     if python_build:
-        # Include both the include and PC dir to ensure we can find
-        # pyconfig.h
+        # Include both include dirs to ensure we can find pyconfig.h
         return (
             os.path.join(prefix, "include")
             + os.path.pathsep
-            + os.path.join(prefix, "PC")
+            + os.path.dirname(sysconfig.get_config_h_filename())
         )
     return os.path.join(prefix, "include")
 
@@ -213,7 +227,9 @@ def _posix_lib(standard_lib, libpython, early_prefix, prefix):
         return os.path.join(libpython, "site-packages")
 
 
-def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
+def get_python_lib(
+    plat_specific: bool = False, standard_lib: bool = False, prefix: str | None = None
+) -> str:
     """Return the directory containing the Python library (standard or
     site additions).
 
@@ -228,14 +244,6 @@ def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
     sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
     """
 
-    if IS_PYPY and sys.version_info < (3, 8):
-        # PyPy-specific schema
-        if prefix is None:
-            prefix = PREFIX
-        if standard_lib:
-            return os.path.join(prefix, "lib-python", sys.version[0])
-        return os.path.join(prefix, 'site-packages')
-
     early_prefix = prefix
 
     if prefix is None:
@@ -244,7 +252,7 @@ def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
         else:
             prefix = plat_specific and EXEC_PREFIX or PREFIX
 
-    if os.name == "posix":
+    if os.name == "posix" or is_mingw():
         if plat_specific or standard_lib:
             # Platform-specific modules (any module from a non-pure-Python
             # module distribution) or standard Python library modules.
@@ -262,34 +270,38 @@ def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
             return os.path.join(prefix, "Lib", "site-packages")
     else:
         raise DistutilsPlatformError(
-            "I don't know where Python installs its library "
-            "on platform '%s'" % os.name
+            f"I don't know where Python installs its library on platform '{os.name}'"
         )
 
 
-def customize_compiler(compiler):  # noqa: C901
+@functools.lru_cache
+def _customize_macos():
+    """
+    Perform first-time customization of compiler-related
+    config vars on macOS. Use after a compiler is known
+    to be needed. This customization exists primarily to support Pythons
+    from binary installers. The kind and paths to build tools on
+    the user system may vary significantly from the system
+    that Python itself was built on.  Also the user OS
+    version and build tools may not support the same set
+    of CPU architectures for universal builds.
+    """
+
+    sys.platform == "darwin" and __import__('_osx_support').customize_compiler(
+        get_config_vars()
+    )
+
+
+def customize_compiler(compiler: CCompiler) -> None:
     """Do any platform-specific customization of a CCompiler instance.
 
     Mainly needed on Unix, so we can plug in the information that
     varies across Unices and is stored in Python's Makefile.
     """
-    if compiler.compiler_type == "unix":
-        if sys.platform == "darwin":
-            # Perform first-time customization of compiler-related
-            # config vars on OS X now that we know we need a compiler.
-            # This is primarily to support Pythons from binary
-            # installers.  The kind and paths to build tools on
-            # the user system may vary significantly from the system
-            # that Python itself was built on.  Also the user OS
-            # version and build tools may not support the same set
-            # of CPU architectures for universal builds.
-            global _config_vars
-            # Use get_config_var() to ensure _config_vars is initialized.
-            if not get_config_var('CUSTOMIZED_OSX_COMPILER'):
-                import _osx_support
-
-                _osx_support.customize_compiler(_config_vars)
-                _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True'
+    if compiler.compiler_type in ["unix", "cygwin"] or (
+        compiler.compiler_type == "mingw32" and is_mingw()
+    ):
+        _customize_macos()
 
         (
             cc,
@@ -297,6 +309,7 @@ def customize_compiler(compiler):  # noqa: C901
             cflags,
             ccshared,
             ldshared,
+            ldcxxshared,
             shlib_suffix,
             ar,
             ar_flags,
@@ -306,11 +319,14 @@ def customize_compiler(compiler):  # noqa: C901
             'CFLAGS',
             'CCSHARED',
             'LDSHARED',
+            'LDCXXSHARED',
             'SHLIB_SUFFIX',
             'AR',
             'ARFLAGS',
         )
 
+        cxxflags = cflags
+
         if 'CC' in os.environ:
             newcc = os.environ['CC']
             if 'LDSHARED' not in os.environ and ldshared.startswith(cc):
@@ -318,38 +334,42 @@ def customize_compiler(compiler):  # noqa: C901
                 #       command for LDSHARED as well
                 ldshared = newcc + ldshared[len(cc) :]
             cc = newcc
-        if 'CXX' in os.environ:
-            cxx = os.environ['CXX']
-        if 'LDSHARED' in os.environ:
-            ldshared = os.environ['LDSHARED']
-        if 'CPP' in os.environ:
-            cpp = os.environ['CPP']
-        else:
-            cpp = cc + " -E"  # not always
-        if 'LDFLAGS' in os.environ:
-            ldshared = ldshared + ' ' + os.environ['LDFLAGS']
-        if 'CFLAGS' in os.environ:
-            cflags = cflags + ' ' + os.environ['CFLAGS']
-            ldshared = ldshared + ' ' + os.environ['CFLAGS']
-        if 'CPPFLAGS' in os.environ:
-            cpp = cpp + ' ' + os.environ['CPPFLAGS']
-            cflags = cflags + ' ' + os.environ['CPPFLAGS']
-            ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
-        if 'AR' in os.environ:
-            ar = os.environ['AR']
-        if 'ARFLAGS' in os.environ:
-            archiver = ar + ' ' + os.environ['ARFLAGS']
-        else:
-            archiver = ar + ' ' + ar_flags
+        cxx = os.environ.get('CXX', cxx)
+        ldshared = os.environ.get('LDSHARED', ldshared)
+        ldcxxshared = os.environ.get('LDCXXSHARED', ldcxxshared)
+        cpp = os.environ.get(
+            'CPP',
+            cc + " -E",  # not always
+        )
 
+        ldshared = _add_flags(ldshared, 'LD')
+        ldcxxshared = _add_flags(ldcxxshared, 'LD')
+        cflags = os.environ.get('CFLAGS', cflags)
+        ldshared = _add_flags(ldshared, 'C')
+        cxxflags = os.environ.get('CXXFLAGS', cxxflags)
+        ldcxxshared = _add_flags(ldcxxshared, 'CXX')
+        cpp = _add_flags(cpp, 'CPP')
+        cflags = _add_flags(cflags, 'CPP')
+        cxxflags = _add_flags(cxxflags, 'CPP')
+        ldshared = _add_flags(ldshared, 'CPP')
+        ldcxxshared = _add_flags(ldcxxshared, 'CPP')
+
+        ar = os.environ.get('AR', ar)
+
+        archiver = ar + ' ' + os.environ.get('ARFLAGS', ar_flags)
         cc_cmd = cc + ' ' + cflags
+        cxx_cmd = cxx + ' ' + cxxflags
+
         compiler.set_executables(
             preprocessor=cpp,
             compiler=cc_cmd,
             compiler_so=cc_cmd + ' ' + ccshared,
-            compiler_cxx=cxx,
+            compiler_cxx=cxx_cmd,
+            compiler_so_cxx=cxx_cmd + ' ' + ccshared,
             linker_so=ldshared,
+            linker_so_cxx=ldcxxshared,
             linker_exe=cc,
+            linker_exe_cxx=cxx,
             archiver=archiver,
         )
 
@@ -359,19 +379,12 @@ def customize_compiler(compiler):  # noqa: C901
         compiler.shared_lib_extension = shlib_suffix
 
 
-def get_config_h_filename():
+def get_config_h_filename() -> str:
     """Return full pathname of installed pyconfig.h file."""
-    if python_build:
-        if os.name == "nt":
-            inc_dir = os.path.join(_sys_home or project_base, "PC")
-        else:
-            inc_dir = _sys_home or project_base
-        return os.path.join(inc_dir, 'pyconfig.h')
-    else:
-        return sysconfig.get_config_h_filename()
+    return sysconfig.get_config_h_filename()
 
 
-def get_makefile_filename():
+def get_makefile_filename() -> str:
     """Return full pathname of installed Makefile from the Python build."""
     return sysconfig.get_makefile_filename()
 
@@ -403,7 +416,11 @@ def parse_makefile(fn, g=None):  # noqa: C901
     from distutils.text_file import TextFile
 
     fp = TextFile(
-        fn, strip_comments=1, skip_blanks=1, join_lines=1, errors="surrogateescape"
+        fn,
+        strip_comments=True,
+        skip_blanks=True,
+        join_lines=True,
+        errors="surrogateescape",
     )
 
     if g is None:
@@ -529,7 +546,11 @@ def expand_makefile_vars(s, vars):
 _config_vars = None
 
 
-def get_config_vars(*args):
+@overload
+def get_config_vars() -> dict[str, str | int]: ...
+@overload
+def get_config_vars(arg: str, /, *args: str) -> list[str | int]: ...
+def get_config_vars(*args: str) -> list[str | int] | dict[str, str | int]:
     """With no arguments, return a dictionary of all configuration
     variables relevant for the current platform.  Generally this includes
     everything needed to build extensions and install both pure modules and
@@ -542,12 +563,19 @@ def get_config_vars(*args):
     global _config_vars
     if _config_vars is None:
         _config_vars = sysconfig.get_config_vars().copy()
-        py39compat.add_ext_suffix(_config_vars)
+        py39.add_ext_suffix(_config_vars)
 
     return [_config_vars.get(name) for name in args] if args else _config_vars
 
 
-def get_config_var(name):
+@overload
+@deprecated(
+    "SO is deprecated, use EXT_SUFFIX. Support will be removed when this module is synchronized with stdlib Python 3.11"
+)
+def get_config_var(name: Literal["SO"]) -> int | str | None: ...
+@overload
+def get_config_var(name: str) -> int | str | None: ...
+def get_config_var(name: str) -> int | str | None:
     """Return the value of a single variable using the dictionary
     returned by 'get_config_vars()'.  Equivalent to
     get_config_vars().get(name)
@@ -557,3 +585,14 @@ def get_config_var(name):
 
         warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)
     return get_config_vars().get(name)
+
+
+@pass_none
+def _add_flags(value: str, type: str) -> str:
+    """
+    Add any flags from the environment for the given type.
+
+    type is the prefix to FLAGS in the environment key (e.g. "C" for "CFLAGS").
+    """
+    flags = os.environ.get(f'{type}FLAGS')
+    return f'{value} {flags}' if flags else value
diff --git a/setuptools/_distutils/tests/__init__.py b/setuptools/_distutils/tests/__init__.py
index 27e73393a0..5a8ab06100 100644
--- a/setuptools/_distutils/tests/__init__.py
+++ b/setuptools/_distutils/tests/__init__.py
@@ -6,3 +6,37 @@
 distutils.command.tests package, since command identification is done
 by import rather than matching pre-defined names.
 """
+
+import shutil
+from collections.abc import Sequence
+
+
+def missing_compiler_executable(cmd_names: Sequence[str] = []):  # pragma: no cover
+    """Check if the compiler components used to build the interpreter exist.
+
+    Check for the existence of the compiler executables whose names are listed
+    in 'cmd_names' or all the compiler executables when 'cmd_names' is empty
+    and return the first missing executable or None when none is found
+    missing.
+
+    """
+    from distutils import ccompiler, errors, sysconfig
+
+    compiler = ccompiler.new_compiler()
+    sysconfig.customize_compiler(compiler)
+    if compiler.compiler_type == "msvc":
+        # MSVC has no executables, so check whether initialization succeeds
+        try:
+            compiler.initialize()
+        except errors.DistutilsPlatformError:
+            return "msvc"
+    for name in compiler.executables:
+        if cmd_names and name not in cmd_names:
+            continue
+        cmd = getattr(compiler, name)
+        if cmd_names:
+            assert cmd is not None, f"the '{name}' executable is not configured"
+        elif not cmd:
+            continue
+        if shutil.which(cmd[0]) is None:
+            return cmd[0]
diff --git a/pkg_resources/_vendor/__init__.py b/setuptools/_distutils/tests/compat/__init__.py
similarity index 100%
rename from pkg_resources/_vendor/__init__.py
rename to setuptools/_distutils/tests/compat/__init__.py
diff --git a/setuptools/_distutils/tests/compat/py39.py b/setuptools/_distutils/tests/compat/py39.py
new file mode 100644
index 0000000000..aca3939a0c
--- /dev/null
+++ b/setuptools/_distutils/tests/compat/py39.py
@@ -0,0 +1,40 @@
+import sys
+
+if sys.version_info >= (3, 10):
+    from test.support.import_helper import (
+        CleanImport as CleanImport,
+    )
+    from test.support.import_helper import (
+        DirsOnSysPath as DirsOnSysPath,
+    )
+    from test.support.os_helper import (
+        EnvironmentVarGuard as EnvironmentVarGuard,
+    )
+    from test.support.os_helper import (
+        rmtree as rmtree,
+    )
+    from test.support.os_helper import (
+        skip_unless_symlink as skip_unless_symlink,
+    )
+    from test.support.os_helper import (
+        unlink as unlink,
+    )
+else:
+    from test.support import (
+        CleanImport as CleanImport,
+    )
+    from test.support import (
+        DirsOnSysPath as DirsOnSysPath,
+    )
+    from test.support import (
+        EnvironmentVarGuard as EnvironmentVarGuard,
+    )
+    from test.support import (
+        rmtree as rmtree,
+    )
+    from test.support import (
+        skip_unless_symlink as skip_unless_symlink,
+    )
+    from test.support import (
+        unlink as unlink,
+    )
diff --git a/setuptools/_distutils/tests/py37compat.py b/setuptools/_distutils/tests/py37compat.py
deleted file mode 100644
index e5d406a3b6..0000000000
--- a/setuptools/_distutils/tests/py37compat.py
+++ /dev/null
@@ -1,18 +0,0 @@
-import os
-import sys
-import platform
-
-
-def subprocess_args_compat(*args):
-    return list(map(os.fspath, args))
-
-
-def subprocess_args_passthrough(*args):
-    return list(args)
-
-
-subprocess_args = (
-    subprocess_args_compat
-    if platform.system() == "Windows" and sys.version_info < (3, 8)
-    else subprocess_args_passthrough
-)
diff --git a/setuptools/_distutils/tests/py38compat.py b/setuptools/_distutils/tests/py38compat.py
deleted file mode 100644
index 211d3a6c50..0000000000
--- a/setuptools/_distutils/tests/py38compat.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# flake8: noqa
-
-import contextlib
-import builtins
-import sys
-
-from test.support import requires_zlib
-import test.support
-
-
-ModuleNotFoundError = getattr(builtins, 'ModuleNotFoundError', ImportError)
-
-try:
-    from test.support.warnings_helper import check_warnings
-except (ModuleNotFoundError, ImportError):
-    from test.support import check_warnings
-
-
-try:
-    from test.support.os_helper import (
-        rmtree,
-        EnvironmentVarGuard,
-        unlink,
-        skip_unless_symlink,
-        temp_dir,
-    )
-except (ModuleNotFoundError, ImportError):
-    from test.support import (
-        rmtree,
-        EnvironmentVarGuard,
-        unlink,
-        skip_unless_symlink,
-        temp_dir,
-    )
-
-
-try:
-    from test.support.import_helper import (
-        DirsOnSysPath,
-        CleanImport,
-    )
-except (ModuleNotFoundError, ImportError):
-    from test.support import (
-        DirsOnSysPath,
-        CleanImport,
-    )
-
-
-if sys.version_info < (3, 9):
-    requires_zlib = lambda: test.support.requires_zlib
diff --git a/setuptools/_distutils/tests/support.py b/setuptools/_distutils/tests/support.py
index fd4b11bf75..9cd2b8a9ee 100644
--- a/setuptools/_distutils/tests/support.py
+++ b/setuptools/_distutils/tests/support.py
@@ -1,17 +1,17 @@
 """Support code for distutils test cases."""
+
+import itertools
 import os
-import sys
+import pathlib
 import shutil
-import tempfile
+import sys
 import sysconfig
-import itertools
-import pathlib
+import tempfile
+from distutils.core import Distribution
 
 import pytest
 from more_itertools import always_iterable
 
-from distutils.core import Distribution
-
 
 @pytest.mark.usefixtures('distutils_managed_tempdir')
 class TempdirManager:
@@ -33,7 +33,7 @@ def write_file(self, path, content='xxx'):
 
         path can be a string or a sequence.
         """
-        pathlib.Path(*always_iterable(path)).write_text(content)
+        pathlib.Path(*always_iterable(path)).write_text(content, encoding='utf-8')
 
     def create_dist(self, pkg_name='foo', **kw):
         """Will generate a test environment.
diff --git a/setuptools/_distutils/tests/test_archive_util.py b/setuptools/_distutils/tests/test_archive_util.py
index 89c415d761..a9cc5eb009 100644
--- a/setuptools/_distutils/tests/test_archive_util.py
+++ b/setuptools/_distutils/tests/test_archive_util.py
@@ -1,30 +1,28 @@
 """Tests for distutils.archive_util."""
-import os
-import sys
-import tarfile
-from os.path import splitdrive
-import warnings
+
 import functools
 import operator
+import os
 import pathlib
-
-import pytest
-import path
-
+import sys
+import tarfile
 from distutils import archive_util
 from distutils.archive_util import (
+    ARCHIVE_FORMATS,
     check_archive_formats,
+    make_archive,
     make_tarball,
     make_zipfile,
-    make_archive,
-    ARCHIVE_FORMATS,
 )
 from distutils.spawn import spawn
 from distutils.tests import support
+from os.path import splitdrive
+
+import path
+import pytest
 from test.support import patch
-from .unix_compat import require_unix_id, require_uid_0, grp, pwd, UID_0_SUPPORT
 
-from .py38compat import check_warnings
+from .unix_compat import UID_0_SUPPORT, grp, pwd, require_uid_0, require_unix_id
 
 
 def can_fs_encode(filename):
@@ -135,7 +133,7 @@ def _create_files(self):
         return tmpdir
 
     @pytest.mark.usefixtures('needs_zlib')
-    @pytest.mark.skipif("not (find_executable('tar') and find_executable('gzip'))")
+    @pytest.mark.skipif("not (shutil.which('tar') and shutil.which('gzip'))")
     def test_tarfile_vs_tar(self):
         tmpdir = self._create_files()
         tmpdir2 = self.mkdtemp()
@@ -179,48 +177,6 @@ def test_tarfile_vs_tar(self):
         tarball = base_name + '.tar'
         assert os.path.exists(tarball)
 
-        # now for a dry_run
-        base_name = os.path.join(tmpdir2, 'archive')
-        old_dir = os.getcwd()
-        os.chdir(tmpdir)
-        try:
-            make_tarball(base_name, 'dist', compress=None, dry_run=True)
-        finally:
-            os.chdir(old_dir)
-        tarball = base_name + '.tar'
-        assert os.path.exists(tarball)
-
-    @pytest.mark.skipif("not find_executable('compress')")
-    def test_compress_deprecated(self):
-        tmpdir = self._create_files()
-        base_name = os.path.join(self.mkdtemp(), 'archive')
-
-        # using compress and testing the DeprecationWarning
-        old_dir = os.getcwd()
-        os.chdir(tmpdir)
-        try:
-            with check_warnings() as w:
-                warnings.simplefilter("always")
-                make_tarball(base_name, 'dist', compress='compress')
-        finally:
-            os.chdir(old_dir)
-        tarball = base_name + '.tar.Z'
-        assert os.path.exists(tarball)
-        assert len(w.warnings) == 1
-
-        # same test with dry_run
-        os.remove(tarball)
-        old_dir = os.getcwd()
-        os.chdir(tmpdir)
-        try:
-            with check_warnings() as w:
-                warnings.simplefilter("always")
-                make_tarball(base_name, 'dist', compress='compress', dry_run=True)
-        finally:
-            os.chdir(old_dir)
-        assert not os.path.exists(tarball)
-        assert len(w.warnings) == 1
-
     @pytest.mark.usefixtures('needs_zlib')
     def test_make_zipfile(self):
         zipfile = pytest.importorskip('zipfile')
diff --git a/setuptools/_distutils/tests/test_bdist.py b/setuptools/_distutils/tests/test_bdist.py
index af330a06e7..d5696fc3dc 100644
--- a/setuptools/_distutils/tests/test_bdist.py
+++ b/setuptools/_distutils/tests/test_bdist.py
@@ -1,4 +1,5 @@
 """Tests for distutils.command.bdist."""
+
 from distutils.command.bdist import bdist
 from distutils.tests import support
 
@@ -30,7 +31,7 @@ def test_skip_build(self):
         # bug #10946: bdist --skip-build should trickle down to subcommands
         dist = self.create_dist()[1]
         cmd = bdist(dist)
-        cmd.skip_build = 1
+        cmd.skip_build = True
         cmd.ensure_finalized()
         dist.command_obj['bdist'] = cmd
 
@@ -43,4 +44,4 @@ def test_skip_build(self):
             if getattr(subcmd, '_unsupported', False):
                 # command is not supported on this build
                 continue
-            assert subcmd.skip_build, '%s should take --skip-build from bdist' % name
+            assert subcmd.skip_build, f'{name} should take --skip-build from bdist'
diff --git a/setuptools/_distutils/tests/test_bdist_dumb.py b/setuptools/_distutils/tests/test_bdist_dumb.py
index 6fb50c4b8e..1fc51d244a 100644
--- a/setuptools/_distutils/tests/test_bdist_dumb.py
+++ b/setuptools/_distutils/tests/test_bdist_dumb.py
@@ -3,13 +3,12 @@
 import os
 import sys
 import zipfile
-
-import pytest
-
-from distutils.core import Distribution
 from distutils.command.bdist_dumb import bdist_dumb
+from distutils.core import Distribution
 from distutils.tests import support
 
+import pytest
+
 SETUP_PY = """\
 from distutils.core import setup
 import foo
@@ -38,16 +37,14 @@ def test_simple_built(self):
         self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
         self.write_file((pkg_dir, 'README'), '')
 
-        dist = Distribution(
-            {
-                'name': 'foo',
-                'version': '0.1',
-                'py_modules': ['foo'],
-                'url': 'xxx',
-                'author': 'xxx',
-                'author_email': 'xxx',
-            }
-        )
+        dist = Distribution({
+            'name': 'foo',
+            'version': '0.1',
+            'py_modules': ['foo'],
+            'url': 'xxx',
+            'author': 'xxx',
+            'author_email': 'xxx',
+        })
         dist.script_name = 'setup.py'
         os.chdir(pkg_dir)
 
@@ -63,7 +60,7 @@ def test_simple_built(self):
 
         # see what we have
         dist_created = os.listdir(os.path.join(pkg_dir, 'dist'))
-        base = "{}.{}.zip".format(dist.get_fullname(), cmd.plat_name)
+        base = f"{dist.get_fullname()}.{cmd.plat_name}.zip"
 
         assert dist_created == [base]
 
@@ -75,7 +72,7 @@ def test_simple_built(self):
             fp.close()
 
         contents = sorted(filter(None, map(os.path.basename, contents)))
-        wanted = ['foo-0.1-py%s.%s.egg-info' % sys.version_info[:2], 'foo.py']
+        wanted = ['foo-0.1-py{}.{}.egg-info'.format(*sys.version_info[:2]), 'foo.py']
         if not sys.dont_write_bytecode:
-            wanted.append('foo.%s.pyc' % sys.implementation.cache_tag)
+            wanted.append(f'foo.{sys.implementation.cache_tag}.pyc')
         assert contents == sorted(wanted)
diff --git a/setuptools/_distutils/tests/test_bdist_rpm.py b/setuptools/_distutils/tests/test_bdist_rpm.py
index 4a702fb913..75051430e2 100644
--- a/setuptools/_distutils/tests/test_bdist_rpm.py
+++ b/setuptools/_distutils/tests/test_bdist_rpm.py
@@ -1,17 +1,14 @@
 """Tests for distutils.command.bdist_rpm."""
 
-import sys
 import os
-
-import pytest
-
-from distutils.core import Distribution
+import shutil  # noqa: F401
+import sys
 from distutils.command.bdist_rpm import bdist_rpm
+from distutils.core import Distribution
 from distutils.tests import support
-from distutils.spawn import find_executable  # noqa: F401
-
-from .py38compat import requires_zlib
 
+import pytest
+from test.support import requires_zlib
 
 SETUP_PY = """\
 from distutils.core import setup
@@ -45,8 +42,8 @@ class TestBuildRpm(
 ):
     @mac_woes
     @requires_zlib()
-    @pytest.mark.skipif("not find_executable('rpm')")
-    @pytest.mark.skipif("not find_executable('rpmbuild')")
+    @pytest.mark.skipif("not shutil.which('rpm')")
+    @pytest.mark.skipif("not shutil.which('rpmbuild')")
     def test_quiet(self):
         # let's create a package
         tmp_dir = self.mkdtemp()
@@ -58,16 +55,14 @@ def test_quiet(self):
         self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
         self.write_file((pkg_dir, 'README'), '')
 
-        dist = Distribution(
-            {
-                'name': 'foo',
-                'version': '0.1',
-                'py_modules': ['foo'],
-                'url': 'xxx',
-                'author': 'xxx',
-                'author_email': 'xxx',
-            }
-        )
+        dist = Distribution({
+            'name': 'foo',
+            'version': '0.1',
+            'py_modules': ['foo'],
+            'url': 'xxx',
+            'author': 'xxx',
+            'author_email': 'xxx',
+        })
         dist.script_name = 'setup.py'
         os.chdir(pkg_dir)
 
@@ -76,7 +71,7 @@ def test_quiet(self):
         cmd.fix_python = True
 
         # running in quiet mode
-        cmd.quiet = 1
+        cmd.quiet = True
         cmd.ensure_finalized()
         cmd.run()
 
@@ -89,9 +84,9 @@ def test_quiet(self):
 
     @mac_woes
     @requires_zlib()
-    # http://bugs.python.org/issue1533164
-    @pytest.mark.skipif("not find_executable('rpm')")
-    @pytest.mark.skipif("not find_executable('rpmbuild')")
+    # https://bugs.python.org/issue1533164
+    @pytest.mark.skipif("not shutil.which('rpm')")
+    @pytest.mark.skipif("not shutil.which('rpmbuild')")
     def test_no_optimize_flag(self):
         # let's create a package that breaks bdist_rpm
         tmp_dir = self.mkdtemp()
@@ -103,16 +98,14 @@ def test_no_optimize_flag(self):
         self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
         self.write_file((pkg_dir, 'README'), '')
 
-        dist = Distribution(
-            {
-                'name': 'foo',
-                'version': '0.1',
-                'py_modules': ['foo'],
-                'url': 'xxx',
-                'author': 'xxx',
-                'author_email': 'xxx',
-            }
-        )
+        dist = Distribution({
+            'name': 'foo',
+            'version': '0.1',
+            'py_modules': ['foo'],
+            'url': 'xxx',
+            'author': 'xxx',
+            'author_email': 'xxx',
+        })
         dist.script_name = 'setup.py'
         os.chdir(pkg_dir)
 
@@ -120,7 +113,7 @@ def test_no_optimize_flag(self):
         cmd = bdist_rpm(dist)
         cmd.fix_python = True
 
-        cmd.quiet = 1
+        cmd.quiet = True
         cmd.ensure_finalized()
         cmd.run()
 
diff --git a/setuptools/_distutils/tests/test_build.py b/setuptools/_distutils/tests/test_build.py
index 66d8af50ac..f7fe69acd1 100644
--- a/setuptools/_distutils/tests/test_build.py
+++ b/setuptools/_distutils/tests/test_build.py
@@ -1,10 +1,10 @@
 """Tests for distutils.command.build."""
+
 import os
 import sys
-
 from distutils.command.build import build
 from distutils.tests import support
-from sysconfig import get_platform
+from sysconfig import get_config_var, get_platform
 
 
 class TestBuild(support.TempdirManager):
@@ -23,7 +23,9 @@ def test_finalize_options(self):
         # build_platlib is 'build/lib.platform-cache_tag[-pydebug]'
         # examples:
         #   build/lib.macosx-10.3-i386-cpython39
-        plat_spec = '.{}-{}'.format(cmd.plat_name, sys.implementation.cache_tag)
+        plat_spec = f'.{cmd.plat_name}-{sys.implementation.cache_tag}'
+        if get_config_var('Py_GIL_DISABLED'):
+            plat_spec += 't'
         if hasattr(sys, 'gettotalrefcount'):
             assert cmd.build_platlib.endswith('-pydebug')
             plat_spec += '-pydebug'
@@ -38,7 +40,9 @@ def test_finalize_options(self):
         assert cmd.build_temp == wanted
 
         # build_scripts is build/scripts-x.x
-        wanted = os.path.join(cmd.build_base, 'scripts-%d.%d' % sys.version_info[:2])
+        wanted = os.path.join(
+            cmd.build_base, f'scripts-{sys.version_info.major}.{sys.version_info.minor}'
+        )
         assert cmd.build_scripts == wanted
 
         # executable is os.path.normpath(sys.executable)
diff --git a/setuptools/_distutils/tests/test_build_clib.py b/setuptools/_distutils/tests/test_build_clib.py
index b5a392a85f..f76f26bcea 100644
--- a/setuptools/_distutils/tests/test_build_clib.py
+++ b/setuptools/_distutils/tests/test_build_clib.py
@@ -1,13 +1,11 @@
 """Tests for distutils.command.build_clib."""
-import os
-
-from test.support import missing_compiler_executable
-
-import pytest
 
+import os
 from distutils.command.build_clib import build_clib
 from distutils.errors import DistutilsSetupError
-from distutils.tests import support
+from distutils.tests import missing_compiler_executable, support
+
+import pytest
 
 
 class TestBuildCLib(support.TempdirManager):
@@ -127,7 +125,7 @@ def test_run(self):
         # all commands are present on the system.
         ccmd = missing_compiler_executable()
         if ccmd is not None:
-            self.skipTest('The %r command is not found' % ccmd)
+            self.skipTest(f'The {ccmd!r} command is not found')
 
         # this should work
         cmd.run()
diff --git a/setuptools/_distutils/tests/test_build_ext.py b/setuptools/_distutils/tests/test_build_ext.py
index cb61ad7455..dab0507f3d 100644
--- a/setuptools/_distutils/tests/test_build_ext.py
+++ b/setuptools/_distutils/tests/test_build_ext.py
@@ -1,42 +1,43 @@
-import sys
-import os
-from io import StringIO
-import textwrap
-import site
 import contextlib
-import platform
-import tempfile
+import glob
 import importlib
-import shutil
+import os.path
+import platform
 import re
-
-import path
-import pytest
-
-from distutils.core import Distribution
-from distutils.command.build_ext import build_ext
+import shutil
+import site
+import subprocess
+import sys
+import tempfile
+import textwrap
+import time
 from distutils import sysconfig
-from distutils.tests.support import (
-    TempdirManager,
-    copy_xxmodule_c,
-    fixup_build_ext,
-)
-from distutils.extension import Extension
+from distutils.command.build_ext import build_ext
+from distutils.core import Distribution
 from distutils.errors import (
     CompileError,
     DistutilsPlatformError,
     DistutilsSetupError,
     UnknownFileError,
 )
+from distutils.extension import Extension
+from distutils.tests import missing_compiler_executable
+from distutils.tests.support import TempdirManager, copy_xxmodule_c, fixup_build_ext
+from io import StringIO
 
+import jaraco.path
+import path
+import pytest
 from test import support
-from . import py38compat as import_helper
+
+from .compat import py39 as import_helper
 
 
 @pytest.fixture()
 def user_site_dir(request):
     self = request.instance
     self.tmp_dir = self.mkdtemp()
+    self.tmp_path = path.Path(self.tmp_dir)
     from distutils.command import build_ext
 
     orig_user_base = site.USER_BASE
@@ -47,12 +48,15 @@ def user_site_dir(request):
     # bpo-30132: On Windows, a .pdb file may be created in the current
     # working directory. Create a temporary working directory to cleanup
     # everything at the end of the test.
-    with path.Path(self.tmp_dir):
+    with self.tmp_path:
         yield
 
     site.USER_BASE = orig_user_base
     build_ext.USER_BASE = orig_user_base
 
+    if sys.platform == 'cygwin':
+        time.sleep(1)
+
 
 @contextlib.contextmanager
 def safe_extension_import(name, path):
@@ -88,11 +92,35 @@ class TestBuildExt(TempdirManager):
     def build_ext(self, *args, **kwargs):
         return build_ext(*args, **kwargs)
 
-    def test_build_ext(self):
-        cmd = support.missing_compiler_executable()
+    @pytest.mark.parametrize("copy_so", [False])
+    def test_build_ext(self, copy_so):
+        missing_compiler_executable()
         copy_xxmodule_c(self.tmp_dir)
         xx_c = os.path.join(self.tmp_dir, 'xxmodule.c')
         xx_ext = Extension('xx', [xx_c])
+        if sys.platform != "win32":
+            if not copy_so:
+                xx_ext = Extension(
+                    'xx',
+                    [xx_c],
+                    library_dirs=['/usr/lib'],
+                    libraries=['z'],
+                    runtime_library_dirs=['/usr/lib'],
+                )
+            elif sys.platform == 'linux':
+                libz_so = {
+                    os.path.realpath(name) for name in glob.iglob('/usr/lib*/libz.so*')
+                }
+                libz_so = sorted(libz_so, key=lambda lib_path: len(lib_path))
+                shutil.copyfile(libz_so[-1], '/tmp/libxx_z.so')
+
+                xx_ext = Extension(
+                    'xx',
+                    [xx_c],
+                    library_dirs=['/tmp'],
+                    libraries=['xx_z'],
+                    runtime_library_dirs=['/tmp'],
+                )
         dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]})
         dist.package_dir = self.tmp_dir
         cmd = self.build_ext(dist)
@@ -111,11 +139,14 @@ def test_build_ext(self):
             sys.stdout = old_stdout
 
         with safe_extension_import('xx', self.tmp_dir):
-            self._test_xx()
+            self._test_xx(copy_so)
+
+        if sys.platform == 'linux' and copy_so:
+            os.unlink('/tmp/libxx_z.so')
 
     @staticmethod
-    def _test_xx():
-        import xx
+    def _test_xx(copy_so):
+        import xx  # type: ignore[import-not-found] # Module generated for tests
 
         for attr in ('error', 'foo', 'new', 'roj'):
             assert hasattr(xx, attr)
@@ -129,6 +160,28 @@ def _test_xx():
         assert isinstance(xx.Null(), xx.Null)
         assert isinstance(xx.Str(), xx.Str)
 
+        if sys.platform == 'linux':
+            so_headers = subprocess.check_output(
+                ["readelf", "-d", xx.__file__], universal_newlines=True
+            )
+            import pprint
+
+            pprint.pprint(so_headers)
+            rpaths = [
+                rpath
+                for line in so_headers.split("\n")
+                if "RPATH" in line or "RUNPATH" in line
+                for rpath in line.split()[2][1:-1].split(":")
+            ]
+            if not copy_so:
+                pprint.pprint(rpaths)
+                # Linked against a library in /usr/lib{,64}
+                assert "/usr/lib" not in rpaths and "/usr/lib64" not in rpaths
+            else:
+                # Linked against a library in /tmp
+                assert "/tmp" in rpaths
+                # The import is the real test here
+
     def test_solaris_enable_shared(self):
         dist = Distribution({'name': 'xx'})
         cmd = self.build_ext(dist)
@@ -138,7 +191,7 @@ def test_solaris_enable_shared(self):
         from distutils.sysconfig import _config_vars
 
         old_var = _config_vars.get('Py_ENABLE_SHARED')
-        _config_vars['Py_ENABLE_SHARED'] = 1
+        _config_vars['Py_ENABLE_SHARED'] = True
         try:
             cmd.ensure_finalized()
         finally:
@@ -162,7 +215,7 @@ def test_user_site(self):
         assert 'user' in options
 
         # setting a value
-        cmd.user = 1
+        cmd.user = True
 
         # setting user based lib and include
         lib = os.path.join(site.USER_BASE, 'lib')
@@ -207,7 +260,7 @@ def test_finalize_options(self):
         for p in py_include.split(os.path.pathsep):
             assert p in cmd.include_dirs
 
-        plat_py_include = sysconfig.get_python_inc(plat_specific=1)
+        plat_py_include = sysconfig.get_python_inc(plat_specific=True)
         for p in plat_py_include.split(os.path.pathsep):
             assert p in cmd.include_dirs
 
@@ -221,7 +274,7 @@ def test_finalize_options(self):
         # make sure cmd.library_dirs is turned into a list
         # if it's a string
         cmd = self.build_ext(dist)
-        cmd.library_dirs = 'my_lib_dir%sother_lib_dir' % os.pathsep
+        cmd.library_dirs = f'my_lib_dir{os.pathsep}other_lib_dir'
         cmd.finalize_options()
         assert 'my_lib_dir' in cmd.library_dirs
         assert 'other_lib_dir' in cmd.library_dirs
@@ -229,7 +282,7 @@ def test_finalize_options(self):
         # make sure rpath is turned into a list
         # if it's a string
         cmd = self.build_ext(dist)
-        cmd.rpath = 'one%stwo' % os.pathsep
+        cmd.rpath = f'one{os.pathsep}two'
         cmd.finalize_options()
         assert cmd.rpath == ['one', 'two']
 
@@ -347,6 +400,19 @@ def test_unicode_module_names(self):
         assert cmd.get_export_symbols(modules[0]) == ['PyInit_foo']
         assert cmd.get_export_symbols(modules[1]) == ['PyInitU_f_1gaa']
 
+    def test_export_symbols__init__(self):
+        # https://github.com/python/cpython/issues/80074
+        # https://github.com/pypa/setuptools/issues/4826
+        modules = [
+            Extension('foo.__init__', ['aaa']),
+            Extension('föö.__init__', ['uuu']),
+        ]
+        dist = Distribution({'name': 'xx', 'ext_modules': modules})
+        cmd = self.build_ext(dist)
+        cmd.ensure_finalized()
+        assert cmd.get_export_symbols(modules[0]) == ['PyInit_foo']
+        assert cmd.get_export_symbols(modules[1]) == ['PyInitU_f_1gaa']
+
     def test_compiler_option(self):
         # cmd.compiler is an option and
         # should not be overridden by a compiler instance
@@ -359,7 +425,7 @@ def test_compiler_option(self):
         assert cmd.compiler == 'unix'
 
     def test_get_outputs(self):
-        cmd = support.missing_compiler_executable()
+        missing_compiler_executable()
         tmp_dir = self.mkdtemp()
         c_file = os.path.join(tmp_dir, 'foo.c')
         self.write_file(c_file, 'void PyInit_foo(void) {}\n')
@@ -379,7 +445,7 @@ def test_get_outputs(self):
         old_wd = os.getcwd()
         os.chdir(other_tmp_dir)
         try:
-            cmd.inplace = 1
+            cmd.inplace = True
             cmd.run()
             so_file = cmd.get_outputs()[0]
         finally:
@@ -390,7 +456,7 @@ def test_get_outputs(self):
         so_dir = os.path.dirname(so_file)
         assert so_dir == other_tmp_dir
 
-        cmd.inplace = 0
+        cmd.inplace = False
         cmd.compiler = None
         cmd.run()
         so_file = cmd.get_outputs()[0]
@@ -399,7 +465,7 @@ def test_get_outputs(self):
         so_dir = os.path.dirname(so_file)
         assert so_dir == cmd.build_lib
 
-        # inplace = 0, cmd.package = 'bar'
+        # inplace = False, cmd.package = 'bar'
         build_py = cmd.get_finalized_command('build_py')
         build_py.package_dir = {'': 'bar'}
         path = cmd.get_ext_fullpath('foo')
@@ -407,8 +473,8 @@ def test_get_outputs(self):
         path = os.path.split(path)[0]
         assert path == cmd.build_lib
 
-        # inplace = 1, cmd.package = 'bar'
-        cmd.inplace = 1
+        # inplace = True, cmd.package = 'bar'
+        cmd.inplace = True
         other_tmp_dir = os.path.realpath(self.mkdtemp())
         old_wd = os.getcwd()
         os.chdir(other_tmp_dir)
@@ -429,7 +495,7 @@ def test_ext_fullpath(self):
         # dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
         dist = Distribution()
         cmd = self.build_ext(dist)
-        cmd.inplace = 1
+        cmd.inplace = True
         cmd.distribution.package_dir = {'': 'src'}
         cmd.distribution.packages = ['lxml', 'lxml.html']
         curdir = os.getcwd()
@@ -438,7 +504,7 @@ def test_ext_fullpath(self):
         assert wanted == path
 
         # building lxml.etree not inplace
-        cmd.inplace = 0
+        cmd.inplace = False
         cmd.build_lib = os.path.join(curdir, 'tmpdir')
         wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree' + ext)
         path = cmd.get_ext_fullpath('lxml.etree')
@@ -453,7 +519,7 @@ def test_ext_fullpath(self):
         assert wanted == path
 
         # building twisted.runner.portmap inplace
-        cmd.inplace = 1
+        cmd.inplace = True
         path = cmd.get_ext_fullpath('twisted.runner.portmap')
         wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext)
         assert wanted == path
@@ -476,7 +542,7 @@ def test_deployment_target_too_low(self):
 
     @pytest.mark.skipif('platform.system() != "Darwin"')
     @pytest.mark.usefixtures('save_env')
-    def test_deployment_target_higher_ok(self):
+    def test_deployment_target_higher_ok(self):  # pragma: no cover
         # Issue 9516: Test that an extension module can be compiled with a
         # deployment target higher than that of the interpreter: the ext
         # module may depend on some newer OS feature.
@@ -488,32 +554,29 @@ def test_deployment_target_higher_ok(self):
             deptarget = '.'.join(str(i) for i in deptarget)
             self._try_compile_deployment_target('<', deptarget)
 
-    def _try_compile_deployment_target(self, operator, target):
+    def _try_compile_deployment_target(self, operator, target):  # pragma: no cover
         if target is None:
             if os.environ.get('MACOSX_DEPLOYMENT_TARGET'):
                 del os.environ['MACOSX_DEPLOYMENT_TARGET']
         else:
             os.environ['MACOSX_DEPLOYMENT_TARGET'] = target
 
-        deptarget_c = os.path.join(self.tmp_dir, 'deptargetmodule.c')
-
-        with open(deptarget_c, 'w') as fp:
-            fp.write(
-                textwrap.dedent(
-                    '''\
-                #include 
+        jaraco.path.build(
+            {
+                'deptargetmodule.c': textwrap.dedent(f"""\
+                    #include 
 
-                int dummy;
+                    int dummy;
 
-                #if TARGET %s MAC_OS_X_VERSION_MIN_REQUIRED
-                #else
-                #error "Unexpected target"
-                #endif
+                    #if TARGET {operator} MAC_OS_X_VERSION_MIN_REQUIRED
+                    #else
+                    #error "Unexpected target"
+                    #endif
 
-            '''
-                    % operator
-                )
-            )
+                    """),
+            },
+            self.tmp_path,
+        )
 
         # get the deployment target that the interpreter was built with
         target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
@@ -523,18 +586,19 @@ def _try_compile_deployment_target(self, operator, target):
         # at least one value we test with will not exist yet.
         if target[:2] < (10, 10):
             # for 10.1 through 10.9.x -> "10n0"
-            target = '%02d%01d0' % target
+            tmpl = '{:02}{:01}0'
         else:
             # for 10.10 and beyond -> "10nn00"
             if len(target) >= 2:
-                target = '%02d%02d00' % target
+                tmpl = '{:02}{:02}00'
             else:
                 # 11 and later can have no minor version (11 instead of 11.0)
-                target = '%02d0000' % target
+                tmpl = '{:02}0000'
+        target = tmpl.format(*target)
         deptarget_ext = Extension(
             'deptarget',
-            [deptarget_c],
-            extra_compile_args=['-DTARGET={}'.format(target)],
+            [self.tmp_path / 'deptargetmodule.c'],
+            extra_compile_args=[f'-DTARGET={target}'],
         )
         dist = Distribution({'name': 'deptarget', 'ext_modules': [deptarget_ext]})
         dist.package_dir = self.tmp_dir
diff --git a/setuptools/_distutils/tests/test_build_py.py b/setuptools/_distutils/tests/test_build_py.py
index 3bef9d79ec..b316ed43a1 100644
--- a/setuptools/_distutils/tests/test_build_py.py
+++ b/setuptools/_distutils/tests/test_build_py.py
@@ -2,43 +2,41 @@
 
 import os
 import sys
-
-import pytest
-
 from distutils.command.build_py import build_py
 from distutils.core import Distribution
 from distutils.errors import DistutilsFileError
-
 from distutils.tests import support
 
+import jaraco.path
+import pytest
+
 
 @support.combine_markers
 class TestBuildPy(support.TempdirManager):
     def test_package_data(self):
         sources = self.mkdtemp()
-        f = open(os.path.join(sources, "__init__.py"), "w")
-        try:
-            f.write("# Pretend this is a package.")
-        finally:
-            f.close()
-        f = open(os.path.join(sources, "README.txt"), "w")
-        try:
-            f.write("Info about this package")
-        finally:
-            f.close()
+        jaraco.path.build(
+            {
+                '__init__.py': "# Pretend this is a package.",
+                'README.txt': 'Info about this package',
+            },
+            sources,
+        )
 
         destination = self.mkdtemp()
 
         dist = Distribution({"packages": ["pkg"], "package_dir": {"pkg": sources}})
         # script_name need not exist, it just need to be initialized
         dist.script_name = os.path.join(sources, "setup.py")
-        dist.command_obj["build"] = support.DummyCommand(force=0, build_lib=destination)
+        dist.command_obj["build"] = support.DummyCommand(
+            force=False, build_lib=destination
+        )
         dist.packages = ["pkg"]
         dist.package_data = {"pkg": ["README.txt"]}
         dist.package_dir = {"pkg": sources}
 
         cmd = build_py(dist)
-        cmd.compile = 1
+        cmd.compile = True
         cmd.ensure_finalized()
         assert cmd.package_data == dist.package_data
 
@@ -57,25 +55,19 @@ def test_package_data(self):
             assert not os.path.exists(pycache_dir)
         else:
             pyc_files = os.listdir(pycache_dir)
-            assert "__init__.%s.pyc" % sys.implementation.cache_tag in pyc_files
+            assert f"__init__.{sys.implementation.cache_tag}.pyc" in pyc_files
 
     def test_empty_package_dir(self):
         # See bugs #1668596/#1720897
         sources = self.mkdtemp()
-        open(os.path.join(sources, "__init__.py"), "w").close()
-
-        testdir = os.path.join(sources, "doc")
-        os.mkdir(testdir)
-        open(os.path.join(testdir, "testfile"), "w").close()
+        jaraco.path.build({'__init__.py': '', 'doc': {'testfile': ''}}, sources)
 
         os.chdir(sources)
-        dist = Distribution(
-            {
-                "packages": ["pkg"],
-                "package_dir": {"pkg": ""},
-                "package_data": {"pkg": ["doc/*"]},
-            }
-        )
+        dist = Distribution({
+            "packages": ["pkg"],
+            "package_dir": {"pkg": ""},
+            "package_data": {"pkg": ["doc/*"]},
+        })
         # script_name need not exist, it just need to be initialized
         dist.script_name = os.path.join(sources, "setup.py")
         dist.script_args = ["build"]
@@ -92,7 +84,7 @@ def test_byte_compile(self):
         os.chdir(project_dir)
         self.write_file('boiledeggs.py', 'import antigravity')
         cmd = build_py(dist)
-        cmd.compile = 1
+        cmd.compile = True
         cmd.build_lib = 'here'
         cmd.finalize_options()
         cmd.run()
@@ -100,7 +92,7 @@ def test_byte_compile(self):
         found = os.listdir(cmd.build_lib)
         assert sorted(found) == ['__pycache__', 'boiledeggs.py']
         found = os.listdir(os.path.join(cmd.build_lib, '__pycache__'))
-        assert found == ['boiledeggs.%s.pyc' % sys.implementation.cache_tag]
+        assert found == [f'boiledeggs.{sys.implementation.cache_tag}.pyc']
 
     @pytest.mark.skipif('sys.dont_write_bytecode')
     def test_byte_compile_optimized(self):
@@ -108,7 +100,7 @@ def test_byte_compile_optimized(self):
         os.chdir(project_dir)
         self.write_file('boiledeggs.py', 'import antigravity')
         cmd = build_py(dist)
-        cmd.compile = 0
+        cmd.compile = False
         cmd.optimize = 1
         cmd.build_lib = 'here'
         cmd.finalize_options()
@@ -126,17 +118,19 @@ def test_dir_in_package_data(self):
         """
         # See bug 19286
         sources = self.mkdtemp()
-        pkg_dir = os.path.join(sources, "pkg")
-
-        os.mkdir(pkg_dir)
-        open(os.path.join(pkg_dir, "__init__.py"), "w").close()
-
-        docdir = os.path.join(pkg_dir, "doc")
-        os.mkdir(docdir)
-        open(os.path.join(docdir, "testfile"), "w").close()
-
-        # create the directory that could be incorrectly detected as a file
-        os.mkdir(os.path.join(docdir, 'otherdir'))
+        jaraco.path.build(
+            {
+                'pkg': {
+                    '__init__.py': '',
+                    'doc': {
+                        'testfile': '',
+                        # create a directory that could be incorrectly detected as a file
+                        'otherdir': {},
+                    },
+                }
+            },
+            sources,
+        )
 
         os.chdir(sources)
         dist = Distribution({"packages": ["pkg"], "package_data": {"pkg": ["doc/*"]}})
@@ -154,7 +148,7 @@ def test_dont_write_bytecode(self, caplog):
         # makes sure byte_compile is not used
         dist = self.create_dist()[1]
         cmd = build_py(dist)
-        cmd.compile = 1
+        cmd.compile = True
         cmd.optimize = 1
 
         old_dont_write_bytecode = sys.dont_write_bytecode
@@ -176,9 +170,8 @@ def test_namespace_package_does_not_warn(self, caplog):
         """
         # Create a fake project structure with a package namespace:
         tmp = self.mkdtemp()
+        jaraco.path.build({'ns': {'pkg': {'module.py': ''}}}, tmp)
         os.chdir(tmp)
-        os.makedirs("ns/pkg")
-        open("ns/pkg/module.py", "w").close()
 
         # Configure the package:
         attrs = {
diff --git a/setuptools/_distutils/tests/test_build_scripts.py b/setuptools/_distutils/tests/test_build_scripts.py
index 1a5753c772..3582f691ef 100644
--- a/setuptools/_distutils/tests/test_build_scripts.py
+++ b/setuptools/_distutils/tests/test_build_scripts.py
@@ -1,13 +1,14 @@
 """Tests for distutils.command.build_scripts."""
 
 import os
-
+import textwrap
+from distutils import sysconfig
 from distutils.command.build_scripts import build_scripts
 from distutils.core import Distribution
-from distutils import sysconfig
-
 from distutils.tests import support
 
+import jaraco.path
+
 
 class TestBuildScripts(support.TempdirManager):
     def test_default_settings(self):
@@ -41,42 +42,31 @@ def get_build_scripts_cmd(self, target, scripts):
         dist = Distribution()
         dist.scripts = scripts
         dist.command_obj["build"] = support.DummyCommand(
-            build_scripts=target, force=1, executable=sys.executable
+            build_scripts=target, force=True, executable=sys.executable
         )
         return build_scripts(dist)
 
-    def write_sample_scripts(self, dir):
-        expected = []
-        expected.append("script1.py")
-        self.write_script(
-            dir,
-            "script1.py",
-            (
-                "#! /usr/bin/env python2.3\n"
-                "# bogus script w/ Python sh-bang\n"
-                "pass\n"
-            ),
-        )
-        expected.append("script2.py")
-        self.write_script(
-            dir,
-            "script2.py",
-            ("#!/usr/bin/python\n" "# bogus script w/ Python sh-bang\n" "pass\n"),
-        )
-        expected.append("shell.sh")
-        self.write_script(
-            dir,
-            "shell.sh",
-            ("#!/bin/sh\n" "# bogus shell script w/ sh-bang\n" "exit 0\n"),
-        )
-        return expected
-
-    def write_script(self, dir, name, text):
-        f = open(os.path.join(dir, name), "w")
-        try:
-            f.write(text)
-        finally:
-            f.close()
+    @staticmethod
+    def write_sample_scripts(dir):
+        spec = {
+            'script1.py': textwrap.dedent("""
+                #! /usr/bin/env python2.3
+                # bogus script w/ Python sh-bang
+                pass
+                """).lstrip(),
+            'script2.py': textwrap.dedent("""
+                #!/usr/bin/python
+                # bogus script w/ Python sh-bang
+                pass
+                """).lstrip(),
+            'shell.sh': textwrap.dedent("""
+                #!/bin/sh
+                # bogus shell script w/ sh-bang
+                exit 0
+                """).lstrip(),
+        }
+        jaraco.path.build(spec, dir)
+        return list(spec)
 
     def test_version_int(self):
         source = self.mkdtemp()
@@ -88,7 +78,7 @@ def test_version_int(self):
         )
         cmd.finalize_options()
 
-        # http://bugs.python.org/issue4524
+        # https://bugs.python.org/issue4524
         #
         # On linux-g++-32 with command line `./configure --enable-ipv6
         # --with-suffix=3`, python is compiled okay but the build scripts
diff --git a/setuptools/_distutils/tests/test_check.py b/setuptools/_distutils/tests/test_check.py
index 6d240b8b2b..b672b1f972 100644
--- a/setuptools/_distutils/tests/test_check.py
+++ b/setuptools/_distutils/tests/test_check.py
@@ -1,12 +1,12 @@
 """Tests for distutils.command.check."""
+
 import os
 import textwrap
-
-import pytest
-
 from distutils.command.check import check
-from distutils.tests import support
 from distutils.errors import DistutilsSetupError
+from distutils.tests import support
+
+import pytest
 
 try:
     import pygments
@@ -62,7 +62,7 @@ def test_check_metadata(self):
             self._run({}, **{'strict': 1})
 
         # and of course, no error when all metadata are present
-        cmd = self._run(metadata, strict=1)
+        cmd = self._run(metadata, strict=True)
         assert cmd._warnings == 0
 
         # now a test with non-ASCII characters
@@ -126,7 +126,7 @@ def test_check_restructuredtext(self):
         cmd.check_restructuredtext()
         assert cmd._warnings == 1
 
-        # let's see if we have an error with strict=1
+        # let's see if we have an error with strict=True
         metadata = {
             'url': 'xxx',
             'author': 'xxx',
@@ -140,12 +140,12 @@ def test_check_restructuredtext(self):
 
         # and non-broken rest, including a non-ASCII character to test #12114
         metadata['long_description'] = 'title\n=====\n\ntest \u00df'
-        cmd = self._run(metadata, strict=1, restructuredtext=1)
+        cmd = self._run(metadata, strict=True, restructuredtext=True)
         assert cmd._warnings == 0
 
         # check that includes work to test #31292
         metadata['long_description'] = 'title\n=====\n\n.. include:: includetest.rst'
-        cmd = self._run(metadata, cwd=HERE, strict=1, restructuredtext=1)
+        cmd = self._run(metadata, cwd=HERE, strict=True, restructuredtext=True)
         assert cmd._warnings == 0
 
     def test_check_restructuredtext_with_syntax_highlight(self):
diff --git a/setuptools/_distutils/tests/test_clean.py b/setuptools/_distutils/tests/test_clean.py
index 157b60a1e9..cc78f30f34 100644
--- a/setuptools/_distutils/tests/test_clean.py
+++ b/setuptools/_distutils/tests/test_clean.py
@@ -1,6 +1,6 @@
 """Tests for distutils.command.clean."""
-import os
 
+import os
 from distutils.command.clean import clean
 from distutils.tests import support
 
@@ -36,8 +36,8 @@ def test_simple_run(self):
         cmd.run()
 
         # make sure the files where removed
-        for name, path in dirs:
-            assert not os.path.exists(path), '%s was not removed' % path
+        for _name, path in dirs:
+            assert not os.path.exists(path), f'{path} was not removed'
 
         # let's run the command again (should spit warnings but succeed)
         cmd.all = 1
diff --git a/setuptools/_distutils/tests/test_cmd.py b/setuptools/_distutils/tests/test_cmd.py
index cc740d1a8b..76e8f5989b 100644
--- a/setuptools/_distutils/tests/test_cmd.py
+++ b/setuptools/_distutils/tests/test_cmd.py
@@ -1,10 +1,11 @@
 """Tests for distutils.cmd."""
-import os
 
+import os
+from distutils import debug
 from distutils.cmd import Command
 from distutils.dist import Distribution
 from distutils.errors import DistutilsOptionError
-from distutils import debug
+
 import pytest
 
 
@@ -47,7 +48,7 @@ def test_ensure_string_list(self, cmd):
     def test_make_file(self, cmd):
         # making sure it raises when infiles is not a string or a list/tuple
         with pytest.raises(TypeError):
-            cmd.make_file(infiles=1, outfile='', func='func', args=())
+            cmd.make_file(infiles=True, outfile='', func='func', args=())
 
         # making sure execute gets called properly
         def _execute(func, args, exec_msg, level):
diff --git a/setuptools/_distutils/tests/test_config.py b/setuptools/_distutils/tests/test_config.py
deleted file mode 100644
index 1ae615db95..0000000000
--- a/setuptools/_distutils/tests/test_config.py
+++ /dev/null
@@ -1,116 +0,0 @@
-"""Tests for distutils.pypirc.pypirc."""
-import os
-
-import pytest
-
-from distutils.tests import support
-
-PYPIRC = """\
-[distutils]
-
-index-servers =
-    server1
-    server2
-    server3
-
-[server1]
-username:me
-password:secret
-
-[server2]
-username:meagain
-password: secret
-realm:acme
-repository:http://another.pypi/
-
-[server3]
-username:cbiggles
-password:yh^%#rest-of-my-password
-"""
-
-PYPIRC_OLD = """\
-[server-login]
-username:tarek
-password:secret
-"""
-
-WANTED = """\
-[distutils]
-index-servers =
-    pypi
-
-[pypi]
-username:tarek
-password:xxx
-"""
-
-
-@support.combine_markers
-@pytest.mark.usefixtures('pypirc')
-class BasePyPIRCCommandTestCase(support.TempdirManager):
-    pass
-
-
-class PyPIRCCommandTestCase(BasePyPIRCCommandTestCase):
-    def test_server_registration(self):
-        # This test makes sure PyPIRCCommand knows how to:
-        # 1. handle several sections in .pypirc
-        # 2. handle the old format
-
-        # new format
-        self.write_file(self.rc, PYPIRC)
-        cmd = self._cmd(self.dist)
-        config = cmd._read_pypirc()
-
-        config = list(sorted(config.items()))
-        waited = [
-            ('password', 'secret'),
-            ('realm', 'pypi'),
-            ('repository', 'https://upload.pypi.org/legacy/'),
-            ('server', 'server1'),
-            ('username', 'me'),
-        ]
-        assert config == waited
-
-        # old format
-        self.write_file(self.rc, PYPIRC_OLD)
-        config = cmd._read_pypirc()
-        config = list(sorted(config.items()))
-        waited = [
-            ('password', 'secret'),
-            ('realm', 'pypi'),
-            ('repository', 'https://upload.pypi.org/legacy/'),
-            ('server', 'server-login'),
-            ('username', 'tarek'),
-        ]
-        assert config == waited
-
-    def test_server_empty_registration(self):
-        cmd = self._cmd(self.dist)
-        rc = cmd._get_rc_file()
-        assert not os.path.exists(rc)
-        cmd._store_pypirc('tarek', 'xxx')
-        assert os.path.exists(rc)
-        f = open(rc)
-        try:
-            content = f.read()
-            assert content == WANTED
-        finally:
-            f.close()
-
-    def test_config_interpolation(self):
-        # using the % character in .pypirc should not raise an error (#20120)
-        self.write_file(self.rc, PYPIRC)
-        cmd = self._cmd(self.dist)
-        cmd.repository = 'server3'
-        config = cmd._read_pypirc()
-
-        config = list(sorted(config.items()))
-        waited = [
-            ('password', 'yh^%#rest-of-my-password'),
-            ('realm', 'pypi'),
-            ('repository', 'https://upload.pypi.org/legacy/'),
-            ('server', 'server3'),
-            ('username', 'cbiggles'),
-        ]
-        assert config == waited
diff --git a/setuptools/_distutils/tests/test_config_cmd.py b/setuptools/_distutils/tests/test_config_cmd.py
index e72a7c5ff8..ebee2ef93f 100644
--- a/setuptools/_distutils/tests/test_config_cmd.py
+++ b/setuptools/_distutils/tests/test_config_cmd.py
@@ -1,14 +1,15 @@
 """Tests for distutils.command.config."""
+
 import os
 import sys
-from test.support import missing_compiler_executable
+from distutils._log import log
+from distutils.command.config import config, dump_file
+from distutils.tests import missing_compiler_executable, support
 
+import more_itertools
+import path
 import pytest
 
-from distutils.command.config import dump_file, config
-from distutils.tests import support
-from distutils._log import log
-
 
 @pytest.fixture(autouse=True)
 def info_log(request, monkeypatch):
@@ -24,12 +25,9 @@ def _info(self, msg, *args):
             self._logs.append(line)
 
     def test_dump_file(self):
-        this_file = os.path.splitext(__file__)[0] + '.py'
-        f = open(this_file)
-        try:
-            numlines = len(f.readlines())
-        finally:
-            f.close()
+        this_file = path.Path(__file__).with_suffix('.py')
+        with this_file.open(encoding='utf-8') as f:
+            numlines = more_itertools.ilen(f)
 
         dump_file(this_file, 'I am the header')
         assert len(self._logs) == numlines + 1
@@ -38,7 +36,7 @@ def test_dump_file(self):
     def test_search_cpp(self):
         cmd = missing_compiler_executable(['preprocessor'])
         if cmd is not None:
-            self.skipTest('The %r command is not found' % cmd)
+            self.skipTest(f'The {cmd!r} command is not found')
         pkg_dir, dist = self.create_dist()
         cmd = config(dist)
         cmd._check_compiler()
@@ -60,9 +58,9 @@ def test_finalize_options(self):
         # on options
         pkg_dir, dist = self.create_dist()
         cmd = config(dist)
-        cmd.include_dirs = 'one%stwo' % os.pathsep
+        cmd.include_dirs = f'one{os.pathsep}two'
         cmd.libraries = 'one'
-        cmd.library_dirs = 'three%sfour' % os.pathsep
+        cmd.library_dirs = f'three{os.pathsep}four'
         cmd.ensure_finalized()
 
         assert cmd.include_dirs == ['one', 'two']
diff --git a/setuptools/_distutils/tests/test_core.py b/setuptools/_distutils/tests/test_core.py
index 2c11ff769e..bad3fb7e83 100644
--- a/setuptools/_distutils/tests/test_core.py
+++ b/setuptools/_distutils/tests/test_core.py
@@ -1,14 +1,13 @@
 """Tests for distutils.core."""
 
-import io
 import distutils.core
+import io
 import os
 import sys
+from distutils.dist import Distribution
 
 import pytest
 
-from distutils.dist import Distribution
-
 # setup script that uses __file__
 setup_using___file__ = """\
 
@@ -70,20 +69,20 @@ class TestCore:
     def test_run_setup_provides_file(self, temp_file):
         # Make sure the script can use __file__; if that's missing, the test
         # setup.py script will raise NameError.
-        temp_file.write_text(setup_using___file__)
+        temp_file.write_text(setup_using___file__, encoding='utf-8')
         distutils.core.run_setup(temp_file)
 
     def test_run_setup_preserves_sys_argv(self, temp_file):
         # Make sure run_setup does not clobber sys.argv
         argv_copy = sys.argv.copy()
-        temp_file.write_text(setup_does_nothing)
+        temp_file.write_text(setup_does_nothing, encoding='utf-8')
         distutils.core.run_setup(temp_file)
         assert sys.argv == argv_copy
 
     def test_run_setup_defines_subclass(self, temp_file):
         # Make sure the script can use __file__; if that's missing, the test
         # setup.py script will raise NameError.
-        temp_file.write_text(setup_defines_subclass)
+        temp_file.write_text(setup_defines_subclass, encoding='utf-8')
         dist = distutils.core.run_setup(temp_file)
         install = dist.get_command_obj('install')
         assert 'cmd' in install.sub_commands
@@ -98,7 +97,7 @@ def test_run_setup_uses_current_dir(self, tmp_path):
 
         # Create a directory and write the setup.py file there:
         setup_py = tmp_path / 'setup.py'
-        setup_py.write_text(setup_prints_cwd)
+        setup_py.write_text(setup_prints_cwd, encoding='utf-8')
         distutils.core.run_setup(setup_py)
 
         output = sys.stdout.getvalue()
@@ -107,14 +106,14 @@ def test_run_setup_uses_current_dir(self, tmp_path):
         assert cwd == output
 
     def test_run_setup_within_if_main(self, temp_file):
-        temp_file.write_text(setup_within_if_main)
+        temp_file.write_text(setup_within_if_main, encoding='utf-8')
         dist = distutils.core.run_setup(temp_file, stop_after="config")
         assert isinstance(dist, Distribution)
         assert dist.get_name() == "setup_within_if_main"
 
     def test_run_commands(self, temp_file):
         sys.argv = ['setup.py', 'build']
-        temp_file.write_text(setup_within_if_main)
+        temp_file.write_text(setup_within_if_main, encoding='utf-8')
         dist = distutils.core.run_setup(temp_file, stop_after="commandline")
         assert 'build' not in dist.have_run
         distutils.core.run_commands(dist)
@@ -124,7 +123,7 @@ def test_debug_mode(self, capsys, monkeypatch):
         # this covers the code called when DEBUG is set
         sys.argv = ['setup.py', '--name']
         distutils.core.setup(name='bar')
-        capsys.readouterr().out == 'bar\n'
+        assert capsys.readouterr().out == 'bar\n'
         monkeypatch.setattr(distutils.core, 'DEBUG', True)
         distutils.core.setup(name='bar')
         wanted = "options (after parsing config files):\n"
diff --git a/setuptools/_distutils/tests/test_dir_util.py b/setuptools/_distutils/tests/test_dir_util.py
index 72aca4ee55..326cb34614 100644
--- a/setuptools/_distutils/tests/test_dir_util.py
+++ b/setuptools/_distutils/tests/test_dir_util.py
@@ -1,18 +1,22 @@
 """Tests for distutils.dir_util."""
+
 import os
+import pathlib
 import stat
+import sys
 import unittest.mock as mock
-
 from distutils import dir_util, errors
 from distutils.dir_util import (
-    mkpath,
-    remove_tree,
-    create_tree,
     copy_tree,
+    create_tree,
     ensure_relative,
+    mkpath,
+    remove_tree,
 )
-
 from distutils.tests import support
+
+import jaraco.path
+import path
 import pytest
 
 
@@ -27,17 +31,17 @@ def stuff(request, monkeypatch, distutils_managed_tempdir):
 
 class TestDirUtil(support.TempdirManager):
     def test_mkpath_remove_tree_verbosity(self, caplog):
-        mkpath(self.target, verbose=0)
+        mkpath(self.target, verbose=False)
         assert not caplog.records
-        remove_tree(self.root_target, verbose=0)
+        remove_tree(self.root_target, verbose=False)
 
-        mkpath(self.target, verbose=1)
-        wanted = ['creating %s' % self.root_target, 'creating %s' % self.target]
+        mkpath(self.target, verbose=True)
+        wanted = [f'creating {self.target}']
         assert caplog.messages == wanted
         caplog.clear()
 
-        remove_tree(self.root_target, verbose=1)
-        wanted = ["removing '%s' (and everything under it)" % self.root_target]
+        remove_tree(self.root_target, verbose=True)
+        wanted = [f"removing '{self.root_target}' (and everything under it)"]
         assert caplog.messages == wanted
 
     @pytest.mark.skipif("platform.system() == 'Windows'")
@@ -51,50 +55,45 @@ def test_mkpath_with_custom_mode(self):
         assert stat.S_IMODE(os.stat(self.target2).st_mode) == 0o555 & ~umask
 
     def test_create_tree_verbosity(self, caplog):
-        create_tree(self.root_target, ['one', 'two', 'three'], verbose=0)
+        create_tree(self.root_target, ['one', 'two', 'three'], verbose=False)
         assert caplog.messages == []
-        remove_tree(self.root_target, verbose=0)
+        remove_tree(self.root_target, verbose=False)
 
-        wanted = ['creating %s' % self.root_target]
-        create_tree(self.root_target, ['one', 'two', 'three'], verbose=1)
+        wanted = [f'creating {self.root_target}']
+        create_tree(self.root_target, ['one', 'two', 'three'], verbose=True)
         assert caplog.messages == wanted
 
-        remove_tree(self.root_target, verbose=0)
+        remove_tree(self.root_target, verbose=False)
 
     def test_copy_tree_verbosity(self, caplog):
-        mkpath(self.target, verbose=0)
+        mkpath(self.target, verbose=False)
 
-        copy_tree(self.target, self.target2, verbose=0)
+        copy_tree(self.target, self.target2, verbose=False)
         assert caplog.messages == []
 
-        remove_tree(self.root_target, verbose=0)
+        remove_tree(self.root_target, verbose=False)
 
-        mkpath(self.target, verbose=0)
-        a_file = os.path.join(self.target, 'ok.txt')
-        with open(a_file, 'w') as f:
-            f.write('some content')
+        mkpath(self.target, verbose=False)
+        a_file = path.Path(self.target) / 'ok.txt'
+        jaraco.path.build({'ok.txt': 'some content'}, self.target)
 
-        wanted = ['copying {} -> {}'.format(a_file, self.target2)]
-        copy_tree(self.target, self.target2, verbose=1)
+        wanted = [f'copying {a_file} -> {self.target2}']
+        copy_tree(self.target, self.target2, verbose=True)
         assert caplog.messages == wanted
 
-        remove_tree(self.root_target, verbose=0)
-        remove_tree(self.target2, verbose=0)
+        remove_tree(self.root_target, verbose=False)
+        remove_tree(self.target2, verbose=False)
 
     def test_copy_tree_skips_nfs_temp_files(self):
-        mkpath(self.target, verbose=0)
+        mkpath(self.target, verbose=False)
 
-        a_file = os.path.join(self.target, 'ok.txt')
-        nfs_file = os.path.join(self.target, '.nfs123abc')
-        for f in a_file, nfs_file:
-            with open(f, 'w') as fh:
-                fh.write('some content')
+        jaraco.path.build({'ok.txt': 'some content', '.nfs123abc': ''}, self.target)
 
         copy_tree(self.target, self.target2)
         assert os.listdir(self.target2) == ['ok.txt']
 
-        remove_tree(self.root_target, verbose=0)
-        remove_tree(self.target2, verbose=0)
+        remove_tree(self.root_target, verbose=False)
+        remove_tree(self.target2, verbose=False)
 
     def test_ensure_relative(self):
         if os.sep == '/':
@@ -108,8 +107,33 @@ def test_copy_tree_exception_in_listdir(self):
         """
         An exception in listdir should raise a DistutilsFileError
         """
-        with mock.patch("os.listdir", side_effect=OSError()), pytest.raises(
-            errors.DistutilsFileError
+        with (
+            mock.patch("os.listdir", side_effect=OSError()),
+            pytest.raises(errors.DistutilsFileError),
         ):
             src = self.tempdirs[-1]
             dir_util.copy_tree(src, None)
+
+    def test_mkpath_exception_uncached(self, monkeypatch, tmp_path):
+        """
+        Caching should not remember failed attempts.
+
+        pypa/distutils#304
+        """
+
+        class FailPath(pathlib.Path):
+            def mkdir(self, *args, **kwargs):
+                raise OSError("Failed to create directory")
+
+            if sys.version_info < (3, 12):
+                _flavour = pathlib.Path()._flavour
+
+        target = tmp_path / 'foodir'
+
+        with pytest.raises(errors.DistutilsFileError):
+            mkpath(FailPath(target))
+
+        assert not target.exists()
+
+        mkpath(target)
+        assert target.exists()
diff --git a/setuptools/_distutils/tests/test_dist.py b/setuptools/_distutils/tests/test_dist.py
index 30a6f9ff2e..2c5beebe64 100644
--- a/setuptools/_distutils/tests/test_dist.py
+++ b/setuptools/_distutils/tests/test_dist.py
@@ -1,20 +1,22 @@
 """Tests for distutils.dist."""
-import os
+
+import email
+import email.generator
+import email.policy
+import functools
 import io
+import os
 import sys
-import warnings
 import textwrap
-import functools
 import unittest.mock as mock
-
-import pytest
-import jaraco.path
-
-from distutils.dist import Distribution, fix_help_options
+import warnings
 from distutils.cmd import Command
-
+from distutils.dist import Distribution, fix_help_options
 from distutils.tests import support
+from typing import ClassVar
 
+import jaraco.path
+import pytest
 
 pydistutils_cfg = '.' * (os.name == 'posix') + 'pydistutils.cfg'
 
@@ -22,7 +24,7 @@
 class test_dist(Command):
     """Sample distutils extension command."""
 
-    user_options = [
+    user_options: ClassVar[list[tuple[str, str, str]]] = [
         ("sample-option=", "S", "help text"),
     ]
 
@@ -66,14 +68,12 @@ def test_command_packages_unspecified(self, clear_argv):
     def test_command_packages_cmdline(self, clear_argv):
         from distutils.tests.test_dist import test_dist
 
-        sys.argv.extend(
-            [
-                "--command-packages",
-                "foo.bar,distutils.tests",
-                "test_dist",
-                "-Ssometext",
-            ]
-        )
+        sys.argv.extend([
+            "--command-packages",
+            "foo.bar,distutils.tests",
+            "test_dist",
+            "-Ssometext",
+        ])
         d = self.create_distribution()
         # let's actually try to load our test command:
         assert d.get_command_packages() == [
@@ -89,15 +89,14 @@ def test_command_packages_cmdline(self, clear_argv):
         'distutils' not in Distribution.parse_config_files.__module__,
         reason='Cannot test when virtualenv has monkey-patched Distribution',
     )
-    def test_venv_install_options(self, tmp_path):
+    def test_venv_install_options(self, tmp_path, clear_argv):
         sys.argv.append("install")
         file = str(tmp_path / 'file')
 
         fakepath = '/somedir'
 
-        jaraco.path.build(
-            {
-                file: f"""
+        jaraco.path.build({
+            file: f"""
                     [install]
                     install-base = {fakepath}
                     install-platbase = {fakepath}
@@ -113,8 +112,7 @@ def test_venv_install_options(self, tmp_path):
                     user = {fakepath}
                     root = {fakepath}
                     """,
-            }
-        )
+        })
 
         # Base case: Not in a Virtual Environment
         with mock.patch.multiple(sys, prefix='/a', base_prefix='/a'):
@@ -155,14 +153,12 @@ def test_venv_install_options(self, tmp_path):
     def test_command_packages_configfile(self, tmp_path, clear_argv):
         sys.argv.append("build")
         file = str(tmp_path / "file")
-        jaraco.path.build(
-            {
-                file: """
+        jaraco.path.build({
+            file: """
                     [global]
                     command_packages = foo.bar, splat
                     """,
-            }
-        )
+        })
 
         d = self.create_distribution([file])
         assert d.get_command_packages() == ["distutils.command", "foo.bar", "splat"]
@@ -251,6 +247,12 @@ def test_find_config_files_disable(self, temp_home):
         # make sure --no-user-cfg disables the user cfg file
         assert len(all_files) - 1 == len(files)
 
+    def test_script_args_list_coercion(self):
+        d = Distribution(attrs={'script_args': ('build', '--no-user-cfg')})
+
+        # make sure script_args is a list even if it started as a different iterable
+        assert d.script_args == ['build', '--no-user-cfg']
+
     @pytest.mark.skipif(
         'platform.system() == "Windows"',
         reason='Windows does not honor chmod 000',
@@ -259,7 +261,7 @@ def test_find_config_files_permission_error(self, fake_home):
         """
         Finding config files should not fail when directory is inaccessible.
         """
-        fake_home.joinpath(pydistutils_cfg).write_text('')
+        fake_home.joinpath(pydistutils_cfg).write_text('', encoding='utf-8')
         fake_home.chmod(0o000)
         Distribution().find_config_files()
 
@@ -473,7 +475,7 @@ def test_show_help(self, request, capsys):
         # smoke test, just makes sure some help is displayed
         dist = Distribution()
         sys.argv = []
-        dist.help = 1
+        dist.help = True
         dist.script_name = 'setup.py'
         dist.parse_command_line()
 
@@ -510,3 +512,41 @@ def test_read_metadata(self):
         assert metadata.platforms is None
         assert metadata.obsoletes is None
         assert metadata.requires == ['foo']
+
+    def test_round_trip_through_email_generator(self):
+        """
+        In pypa/setuptools#4033, it was shown that once PKG-INFO is
+        re-generated using ``email.generator.Generator``, some control
+        characters might cause problems.
+        """
+        # Given a PKG-INFO file ...
+        attrs = {
+            "name": "package",
+            "version": "1.0",
+            "long_description": "hello\x0b\nworld\n",
+        }
+        dist = Distribution(attrs)
+        metadata = dist.metadata
+
+        with io.StringIO() as buffer:
+            metadata.write_pkg_file(buffer)
+            msg = buffer.getvalue()
+
+        # ... when it is read and re-written using stdlib's email library,
+        orig = email.message_from_string(msg)
+        policy = email.policy.EmailPolicy(
+            utf8=True,
+            mangle_from_=False,
+            max_line_length=0,
+        )
+        with io.StringIO() as buffer:
+            email.generator.Generator(buffer, policy=policy).flatten(orig)
+
+            buffer.seek(0)
+            regen = email.message_from_file(buffer)
+
+        # ... then it should be the same as the original
+        # (except for the specific line break characters)
+        orig_desc = set(orig["Description"].splitlines())
+        regen_desc = set(regen["Description"].splitlines())
+        assert regen_desc == orig_desc
diff --git a/setuptools/_distutils/tests/test_extension.py b/setuptools/_distutils/tests/test_extension.py
index f86af07376..5e8e768223 100644
--- a/setuptools/_distutils/tests/test_extension.py
+++ b/setuptools/_distutils/tests/test_extension.py
@@ -1,11 +1,12 @@
 """Tests for distutils.extension."""
+
 import os
+import pathlib
 import warnings
+from distutils.extension import Extension, read_setup_file
 
-from distutils.extension import read_setup_file, Extension
-
-from .py38compat import check_warnings
 import pytest
+from test.support.warnings_helper import check_warnings
 
 
 class TestExtension:
@@ -61,19 +62,31 @@ def test_read_setup_file(self):
 
     def test_extension_init(self):
         # the first argument, which is the name, must be a string
-        with pytest.raises(AssertionError):
+        with pytest.raises(TypeError):
             Extension(1, [])
         ext = Extension('name', [])
         assert ext.name == 'name'
 
         # the second argument, which is the list of files, must
-        # be a list of strings
-        with pytest.raises(AssertionError):
+        # be an iterable of strings or PathLike objects, and not a string
+        with pytest.raises(TypeError):
             Extension('name', 'file')
-        with pytest.raises(AssertionError):
+        with pytest.raises(TypeError):
             Extension('name', ['file', 1])
         ext = Extension('name', ['file1', 'file2'])
         assert ext.sources == ['file1', 'file2']
+        ext = Extension('name', [pathlib.Path('file1'), pathlib.Path('file2')])
+        assert ext.sources == ['file1', 'file2']
+
+        # any non-string iterable of strings or PathLike objects should work
+        ext = Extension('name', ('file1', 'file2'))  # tuple
+        assert ext.sources == ['file1', 'file2']
+        ext = Extension('name', {'file1', 'file2'})  # set
+        assert sorted(ext.sources) == ['file1', 'file2']
+        ext = Extension('name', iter(['file1', 'file2']))  # iterator
+        assert ext.sources == ['file1', 'file2']
+        ext = Extension('name', [pathlib.Path('file1'), 'file2'])  # mixed types
+        assert ext.sources == ['file1', 'file2']
 
         # others arguments have defaults
         for attr in (
diff --git a/setuptools/_distutils/tests/test_file_util.py b/setuptools/_distutils/tests/test_file_util.py
index 9f44f91dfa..a75d4a0317 100644
--- a/setuptools/_distutils/tests/test_file_util.py
+++ b/setuptools/_distutils/tests/test_file_util.py
@@ -1,98 +1,89 @@
 """Tests for distutils.file_util."""
-import os
+
 import errno
+import os
 import unittest.mock as mock
-
-from distutils.file_util import move_file, copy_file
-from distutils.tests import support
 from distutils.errors import DistutilsFileError
-from .py38compat import unlink
+from distutils.file_util import copy_file, move_file
+
+import jaraco.path
 import pytest
 
 
 @pytest.fixture(autouse=True)
-def stuff(request, monkeypatch, distutils_managed_tempdir):
+def stuff(request, tmp_path):
     self = request.instance
-    tmp_dir = self.mkdtemp()
-    self.source = os.path.join(tmp_dir, 'f1')
-    self.target = os.path.join(tmp_dir, 'f2')
-    self.target_dir = os.path.join(tmp_dir, 'd1')
+    self.source = tmp_path / 'f1'
+    self.target = tmp_path / 'f2'
+    self.target_dir = tmp_path / 'd1'
 
 
-class TestFileUtil(support.TempdirManager):
+class TestFileUtil:
     def test_move_file_verbosity(self, caplog):
-        f = open(self.source, 'w')
-        try:
-            f.write('some content')
-        finally:
-            f.close()
+        jaraco.path.build({self.source: 'some content'})
 
-        move_file(self.source, self.target, verbose=0)
+        move_file(self.source, self.target, verbose=False)
         assert not caplog.messages
 
         # back to original state
-        move_file(self.target, self.source, verbose=0)
+        move_file(self.target, self.source, verbose=False)
 
-        move_file(self.source, self.target, verbose=1)
-        wanted = ['moving {} -> {}'.format(self.source, self.target)]
+        move_file(self.source, self.target, verbose=True)
+        wanted = [f'moving {self.source} -> {self.target}']
         assert caplog.messages == wanted
 
         # back to original state
-        move_file(self.target, self.source, verbose=0)
+        move_file(self.target, self.source, verbose=False)
 
         caplog.clear()
         # now the target is a dir
         os.mkdir(self.target_dir)
-        move_file(self.source, self.target_dir, verbose=1)
-        wanted = ['moving {} -> {}'.format(self.source, self.target_dir)]
+        move_file(self.source, self.target_dir, verbose=True)
+        wanted = [f'moving {self.source} -> {self.target_dir}']
         assert caplog.messages == wanted
 
     def test_move_file_exception_unpacking_rename(self):
         # see issue 22182
-        with mock.patch("os.rename", side_effect=OSError("wrong", 1)), pytest.raises(
-            DistutilsFileError
+        with (
+            mock.patch("os.rename", side_effect=OSError("wrong", 1)),
+            pytest.raises(DistutilsFileError),
         ):
-            with open(self.source, 'w') as fobj:
-                fobj.write('spam eggs')
-            move_file(self.source, self.target, verbose=0)
+            jaraco.path.build({self.source: 'spam eggs'})
+            move_file(self.source, self.target, verbose=False)
 
     def test_move_file_exception_unpacking_unlink(self):
         # see issue 22182
-        with mock.patch(
-            "os.rename", side_effect=OSError(errno.EXDEV, "wrong")
-        ), mock.patch("os.unlink", side_effect=OSError("wrong", 1)), pytest.raises(
-            DistutilsFileError
+        with (
+            mock.patch("os.rename", side_effect=OSError(errno.EXDEV, "wrong")),
+            mock.patch("os.unlink", side_effect=OSError("wrong", 1)),
+            pytest.raises(DistutilsFileError),
         ):
-            with open(self.source, 'w') as fobj:
-                fobj.write('spam eggs')
-            move_file(self.source, self.target, verbose=0)
+            jaraco.path.build({self.source: 'spam eggs'})
+            move_file(self.source, self.target, verbose=False)
 
     def test_copy_file_hard_link(self):
-        with open(self.source, 'w') as f:
-            f.write('some content')
+        jaraco.path.build({self.source: 'some content'})
         # Check first that copy_file() will not fall back on copying the file
         # instead of creating the hard link.
         try:
             os.link(self.source, self.target)
         except OSError as e:
-            self.skipTest('os.link: %s' % e)
+            self.skipTest(f'os.link: {e}')
         else:
-            unlink(self.target)
+            self.target.unlink()
         st = os.stat(self.source)
         copy_file(self.source, self.target, link='hard')
         st2 = os.stat(self.source)
         st3 = os.stat(self.target)
         assert os.path.samestat(st, st2), (st, st2)
         assert os.path.samestat(st2, st3), (st2, st3)
-        with open(self.source) as f:
-            assert f.read() == 'some content'
+        assert self.source.read_text(encoding='utf-8') == 'some content'
 
     def test_copy_file_hard_link_failure(self):
         # If hard linking fails, copy_file() falls back on copying file
         # (some special filesystems don't support hard linking even under
         #  Unix, see issue #8876).
-        with open(self.source, 'w') as f:
-            f.write('some content')
+        jaraco.path.build({self.source: 'some content'})
         st = os.stat(self.source)
         with mock.patch("os.link", side_effect=OSError(0, "linking unsupported")):
             copy_file(self.source, self.target, link='hard')
@@ -101,5 +92,4 @@ def test_copy_file_hard_link_failure(self):
         assert os.path.samestat(st, st2), (st, st2)
         assert not os.path.samestat(st2, st3), (st2, st3)
         for fn in (self.source, self.target):
-            with open(fn) as f:
-                assert f.read() == 'some content'
+            assert fn.read_text(encoding='utf-8') == 'some content'
diff --git a/setuptools/_distutils/tests/test_filelist.py b/setuptools/_distutils/tests/test_filelist.py
index 2cee42cddd..130e6fb53b 100644
--- a/setuptools/_distutils/tests/test_filelist.py
+++ b/setuptools/_distutils/tests/test_filelist.py
@@ -1,18 +1,16 @@
 """Tests for distutils.filelist."""
+
+import logging
 import os
 import re
-import logging
-
-from distutils import debug
+from distutils import debug, filelist
 from distutils.errors import DistutilsTemplateError
-from distutils.filelist import glob_to_re, translate_pattern, FileList
-from distutils import filelist
+from distutils.filelist import FileList, glob_to_re, translate_pattern
 
-import pytest
 import jaraco.path
+import pytest
 
-from . import py38compat as os_helper
-
+from .compat import py39 as os_helper
 
 MANIFEST_IN = """\
 include ok
@@ -321,14 +319,18 @@ def test_non_local_discovery(self, tmp_path):
         When findall is called with another path, the full
         path name should be returned.
         """
-        filename = tmp_path / 'file1.txt'
-        filename.write_text('')
-        expected = [str(filename)]
+        jaraco.path.build({'file1.txt': ''}, tmp_path)
+        expected = [str(tmp_path / 'file1.txt')]
         assert filelist.findall(tmp_path) == expected
 
     @os_helper.skip_unless_symlink
     def test_symlink_loop(self, tmp_path):
-        tmp_path.joinpath('link-to-parent').symlink_to('.')
-        tmp_path.joinpath('somefile').write_text('')
+        jaraco.path.build(
+            {
+                'link-to-parent': jaraco.path.Symlink('.'),
+                'somefile': '',
+            },
+            tmp_path,
+        )
         files = filelist.findall(tmp_path)
         assert len(files) == 1
diff --git a/setuptools/_distutils/tests/test_install.py b/setuptools/_distutils/tests/test_install.py
index 3f525db42a..b3ffb2e668 100644
--- a/setuptools/_distutils/tests/test_install.py
+++ b/setuptools/_distutils/tests/test_install.py
@@ -1,24 +1,21 @@
 """Tests for distutils.command.install."""
 
+import logging
 import os
-import sys
-import site
 import pathlib
-import logging
-
-import pytest
-
+import site
+import sys
 from distutils import sysconfig
-from distutils.command.install import install
 from distutils.command import install as install_module
 from distutils.command.build_ext import build_ext
-from distutils.command.install import INSTALL_SCHEMES
+from distutils.command.install import INSTALL_SCHEMES, install
 from distutils.core import Distribution
 from distutils.errors import DistutilsOptionError
 from distutils.extension import Extension
+from distutils.tests import missing_compiler_executable, support
+from distutils.util import is_mingw
 
-from distutils.tests import support
-from test import support as test_support
+import pytest
 
 
 def _make_ext_name(modname):
@@ -104,7 +101,7 @@ def _expanduser(path):
         assert 'user' in options
 
         # setting a value
-        cmd.user = 1
+        cmd.user = True
 
         # user base and site shouldn't be created yet
         assert not os.path.exists(site.USER_BASE)
@@ -121,7 +118,7 @@ def _expanduser(path):
         assert 'usersite' in cmd.config_vars
 
         actual_headers = os.path.relpath(cmd.install_headers, site.USER_BASE)
-        if os.name == 'nt':
+        if os.name == 'nt' and not is_mingw():
             site_path = os.path.relpath(os.path.dirname(orig_site), orig_base)
             include = os.path.join(site_path, 'Include')
         else:
@@ -197,25 +194,21 @@ def test_record(self):
         cmd.ensure_finalized()
         cmd.run()
 
-        f = open(cmd.record)
-        try:
-            content = f.read()
-        finally:
-            f.close()
+        content = pathlib.Path(cmd.record).read_text(encoding='utf-8')
 
-        found = [os.path.basename(line) for line in content.splitlines()]
+        found = [pathlib.Path(line).name for line in content.splitlines()]
         expected = [
             'hello.py',
-            'hello.%s.pyc' % sys.implementation.cache_tag,
+            f'hello.{sys.implementation.cache_tag}.pyc',
             'sayhi',
-            'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2],
+            'UNKNOWN-0.0.0-py{}.{}.egg-info'.format(*sys.version_info[:2]),
         ]
         assert found == expected
 
     def test_record_extensions(self):
-        cmd = test_support.missing_compiler_executable()
+        cmd = missing_compiler_executable()
         if cmd is not None:
-            pytest.skip('The %r command is not found' % cmd)
+            pytest.skip(f'The {cmd!r} command is not found')
         install_dir = self.mkdtemp()
         project_dir, dist = self.create_dist(
             ext_modules=[Extension('xx', ['xxmodule.c'])]
@@ -235,12 +228,12 @@ def test_record_extensions(self):
         cmd.ensure_finalized()
         cmd.run()
 
-        content = pathlib.Path(cmd.record).read_text()
+        content = pathlib.Path(cmd.record).read_text(encoding='utf-8')
 
-        found = [os.path.basename(line) for line in content.splitlines()]
+        found = [pathlib.Path(line).name for line in content.splitlines()]
         expected = [
             _make_ext_name('xx'),
-            'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2],
+            'UNKNOWN-0.0.0-py{}.{}.egg-info'.format(*sys.version_info[:2]),
         ]
         assert found == expected
 
diff --git a/setuptools/_distutils/tests/test_install_data.py b/setuptools/_distutils/tests/test_install_data.py
index 9badbc264f..c800f86c64 100644
--- a/setuptools/_distutils/tests/test_install_data.py
+++ b/setuptools/_distutils/tests/test_install_data.py
@@ -1,11 +1,12 @@
 """Tests for distutils.command.install_data."""
-import os
-
-import pytest
 
+import os
+import pathlib
 from distutils.command.install_data import install_data
 from distutils.tests import support
 
+import pytest
+
 
 @pytest.mark.usefixtures('save_env')
 class TestInstallData(
@@ -18,22 +19,27 @@ def test_simple_run(self):
 
         # data_files can contain
         #  - simple files
+        #  - a Path object
         #  - a tuple with a path, and a list of file
         one = os.path.join(pkg_dir, 'one')
         self.write_file(one, 'xxx')
         inst2 = os.path.join(pkg_dir, 'inst2')
         two = os.path.join(pkg_dir, 'two')
         self.write_file(two, 'xxx')
+        three = pathlib.Path(pkg_dir) / 'three'
+        self.write_file(three, 'xxx')
 
-        cmd.data_files = [one, (inst2, [two])]
-        assert cmd.get_inputs() == [one, (inst2, [two])]
+        cmd.data_files = [one, (inst2, [two]), three]
+        assert cmd.get_inputs() == [one, (inst2, [two]), three]
 
         # let's run the command
         cmd.ensure_finalized()
         cmd.run()
 
         # let's check the result
-        assert len(cmd.get_outputs()) == 2
+        assert len(cmd.get_outputs()) == 3
+        rthree = os.path.split(one)[-1]
+        assert os.path.exists(os.path.join(inst, rthree))
         rtwo = os.path.split(two)[-1]
         assert os.path.exists(os.path.join(inst2, rtwo))
         rone = os.path.split(one)[-1]
@@ -41,26 +47,28 @@ def test_simple_run(self):
         cmd.outfiles = []
 
         # let's try with warn_dir one
-        cmd.warn_dir = 1
+        cmd.warn_dir = True
         cmd.ensure_finalized()
         cmd.run()
 
         # let's check the result
-        assert len(cmd.get_outputs()) == 2
+        assert len(cmd.get_outputs()) == 3
+        assert os.path.exists(os.path.join(inst, rthree))
         assert os.path.exists(os.path.join(inst2, rtwo))
         assert os.path.exists(os.path.join(inst, rone))
         cmd.outfiles = []
 
         # now using root and empty dir
         cmd.root = os.path.join(pkg_dir, 'root')
-        inst4 = os.path.join(pkg_dir, 'inst4')
-        three = os.path.join(cmd.install_dir, 'three')
-        self.write_file(three, 'xx')
-        cmd.data_files = [one, (inst2, [two]), ('inst3', [three]), (inst4, [])]
+        inst5 = os.path.join(pkg_dir, 'inst5')
+        four = os.path.join(cmd.install_dir, 'four')
+        self.write_file(four, 'xx')
+        cmd.data_files = [one, (inst2, [two]), three, ('inst5', [four]), (inst5, [])]
         cmd.ensure_finalized()
         cmd.run()
 
         # let's check the result
-        assert len(cmd.get_outputs()) == 4
+        assert len(cmd.get_outputs()) == 5
+        assert os.path.exists(os.path.join(inst, rthree))
         assert os.path.exists(os.path.join(inst2, rtwo))
         assert os.path.exists(os.path.join(inst, rone))
diff --git a/setuptools/_distutils/tests/test_install_headers.py b/setuptools/_distutils/tests/test_install_headers.py
index 1e8ccf7991..2c74f06b97 100644
--- a/setuptools/_distutils/tests/test_install_headers.py
+++ b/setuptools/_distutils/tests/test_install_headers.py
@@ -1,11 +1,11 @@
 """Tests for distutils.command.install_headers."""
-import os
-
-import pytest
 
+import os
 from distutils.command.install_headers import install_headers
 from distutils.tests import support
 
+import pytest
+
 
 @pytest.mark.usefixtures('save_env')
 class TestInstallHeaders(
diff --git a/setuptools/_distutils/tests/test_install_lib.py b/setuptools/_distutils/tests/test_install_lib.py
index 0bd67cd04d..f685a57956 100644
--- a/setuptools/_distutils/tests/test_install_lib.py
+++ b/setuptools/_distutils/tests/test_install_lib.py
@@ -1,14 +1,14 @@
 """Tests for distutils.command.install_data."""
-import sys
-import os
-import importlib.util
-
-import pytest
 
+import importlib.util
+import os
+import sys
 from distutils.command.install_lib import install_lib
+from distutils.errors import DistutilsOptionError
 from distutils.extension import Extension
 from distutils.tests import support
-from distutils.errors import DistutilsOptionError
+
+import pytest
 
 
 @support.combine_markers
@@ -97,7 +97,7 @@ def test_dont_write_bytecode(self, caplog):
         # makes sure byte_compile is not used
         dist = self.create_dist()[1]
         cmd = install_lib(dist)
-        cmd.compile = 1
+        cmd.compile = True
         cmd.optimize = 1
 
         old_dont_write_bytecode = sys.dont_write_bytecode
diff --git a/setuptools/_distutils/tests/test_install_scripts.py b/setuptools/_distutils/tests/test_install_scripts.py
index 58313f2864..868b1c2252 100644
--- a/setuptools/_distutils/tests/test_install_scripts.py
+++ b/setuptools/_distutils/tests/test_install_scripts.py
@@ -1,12 +1,12 @@
 """Tests for distutils.command.install_scripts."""
 
 import os
-
 from distutils.command.install_scripts import install_scripts
 from distutils.core import Distribution
-
 from distutils.tests import support
 
+from . import test_build_scripts
+
 
 class TestInstallScripts(support.TempdirManager):
     def test_default_settings(self):
@@ -14,8 +14,8 @@ def test_default_settings(self):
         dist.command_obj["build"] = support.DummyCommand(build_scripts="/foo/bar")
         dist.command_obj["install"] = support.DummyCommand(
             install_scripts="/splat/funk",
-            force=1,
-            skip_build=1,
+            force=True,
+            skip_build=True,
         )
         cmd = install_scripts(dist)
         assert not cmd.force
@@ -32,39 +32,16 @@ def test_default_settings(self):
 
     def test_installation(self):
         source = self.mkdtemp()
-        expected = []
-
-        def write_script(name, text):
-            expected.append(name)
-            f = open(os.path.join(source, name), "w")
-            try:
-                f.write(text)
-            finally:
-                f.close()
 
-        write_script(
-            "script1.py",
-            (
-                "#! /usr/bin/env python2.3\n"
-                "# bogus script w/ Python sh-bang\n"
-                "pass\n"
-            ),
-        )
-        write_script(
-            "script2.py",
-            ("#!/usr/bin/python\n" "# bogus script w/ Python sh-bang\n" "pass\n"),
-        )
-        write_script(
-            "shell.sh", ("#!/bin/sh\n" "# bogus shell script w/ sh-bang\n" "exit 0\n")
-        )
+        expected = test_build_scripts.TestBuildScripts.write_sample_scripts(source)
 
         target = self.mkdtemp()
         dist = Distribution()
         dist.command_obj["build"] = support.DummyCommand(build_scripts=source)
         dist.command_obj["install"] = support.DummyCommand(
             install_scripts=target,
-            force=1,
-            skip_build=1,
+            force=True,
+            skip_build=True,
         )
         cmd = install_scripts(dist)
         cmd.finalize_options()
diff --git a/setuptools/_distutils/tests/test_log.py b/setuptools/_distutils/tests/test_log.py
index ec6a0c8051..d67779fc9f 100644
--- a/setuptools/_distutils/tests/test_log.py
+++ b/setuptools/_distutils/tests/test_log.py
@@ -1,7 +1,6 @@
 """Tests for distutils.log"""
 
 import logging
-
 from distutils._log import log
 
 
diff --git a/setuptools/_distutils/tests/test_dep_util.py b/setuptools/_distutils/tests/test_modified.py
similarity index 56%
rename from setuptools/_distutils/tests/test_dep_util.py
rename to setuptools/_distutils/tests/test_modified.py
index e5dcad9464..e35cec2d6f 100644
--- a/setuptools/_distutils/tests/test_dep_util.py
+++ b/setuptools/_distutils/tests/test_modified.py
@@ -1,9 +1,11 @@
-"""Tests for distutils.dep_util."""
-import os
+"""Tests for distutils._modified."""
 
-from distutils.dep_util import newer, newer_pairwise, newer_group
+import os
+import types
+from distutils._modified import newer, newer_group, newer_pairwise, newer_pairwise_group
 from distutils.errors import DistutilsFileError
 from distutils.tests import support
+
 import pytest
 
 
@@ -27,7 +29,7 @@ def test_newer(self):
         # than 'new_file'.
         assert not newer(old_file, new_file)
 
-    def test_newer_pairwise(self):
+    def _setup_1234(self):
         tmpdir = self.mkdtemp()
         sources = os.path.join(tmpdir, 'sources')
         targets = os.path.join(tmpdir, 'targets')
@@ -40,9 +42,30 @@ def test_newer_pairwise(self):
         self.write_file(one)
         self.write_file(two)
         self.write_file(four)
+        return one, two, three, four
+
+    def test_newer_pairwise(self):
+        one, two, three, four = self._setup_1234()
 
         assert newer_pairwise([one, two], [three, four]) == ([one], [three])
 
+    def test_newer_pairwise_mismatch(self):
+        one, two, three, four = self._setup_1234()
+
+        with pytest.raises(ValueError):
+            newer_pairwise([one], [three, four])
+
+        with pytest.raises(ValueError):
+            newer_pairwise([one, two], [three])
+
+    def test_newer_pairwise_empty(self):
+        assert newer_pairwise([], []) == ([], [])
+
+    def test_newer_pairwise_fresh(self):
+        one, two, three, four = self._setup_1234()
+
+        assert newer_pairwise([one, three], [two, four]) == ([], [])
+
     def test_newer_group(self):
         tmpdir = self.mkdtemp()
         sources = os.path.join(tmpdir, 'sources')
@@ -68,3 +91,36 @@ def test_newer_group(self):
         assert not newer_group([one, two, old_file], three, missing='ignore')
 
         assert newer_group([one, two, old_file], three, missing='newer')
+
+
+@pytest.fixture
+def groups_target(tmp_path):
+    """
+    Set up some older sources, a target, and newer sources.
+
+    Returns a simple namespace with these values.
+    """
+    filenames = ['older.c', 'older.h', 'target.o', 'newer.c', 'newer.h']
+    paths = [tmp_path / name for name in filenames]
+
+    for mtime, path in enumerate(paths):
+        path.write_text('', encoding='utf-8')
+
+        # make sure modification times are sequential
+        os.utime(path, (mtime, mtime))
+
+    return types.SimpleNamespace(older=paths[:2], target=paths[2], newer=paths[3:])
+
+
+def test_newer_pairwise_group(groups_target):
+    older = newer_pairwise_group([groups_target.older], [groups_target.target])
+    newer = newer_pairwise_group([groups_target.newer], [groups_target.target])
+    assert older == ([], [])
+    assert newer == ([groups_target.newer], [groups_target.target])
+
+
+def test_newer_group_no_sources_no_target(tmp_path):
+    """
+    Consider no sources and no target "newer".
+    """
+    assert newer_group([], str(tmp_path / 'does-not-exist'))
diff --git a/setuptools/_distutils/tests/test_msvc9compiler.py b/setuptools/_distutils/tests/test_msvc9compiler.py
deleted file mode 100644
index fe5693e1d8..0000000000
--- a/setuptools/_distutils/tests/test_msvc9compiler.py
+++ /dev/null
@@ -1,183 +0,0 @@
-"""Tests for distutils.msvc9compiler."""
-import sys
-import os
-
-from distutils.errors import DistutilsPlatformError
-from distutils.tests import support
-import pytest
-
-# A manifest with the only assembly reference being the msvcrt assembly, so
-# should have the assembly completely stripped.  Note that although the
-# assembly has a  reference the assembly is removed - that is
-# currently a "feature", not a bug :)
-_MANIFEST_WITH_ONLY_MSVC_REFERENCE = """\
-
-
-  
-    
-      
-        
-        
-      
-    
-  
-  
-    
-      
-      
-    
-  
-
-"""
-
-# A manifest with references to assemblies other than msvcrt.  When processed,
-# this assembly should be returned with just the msvcrt part removed.
-_MANIFEST_WITH_MULTIPLE_REFERENCES = """\
-
-
-  
-    
-      
-        
-        
-      
-    
-  
-  
-    
-      
-      
-    
-  
-  
-    
-      
-    
-  
-
-"""
-
-_CLEANED_MANIFEST = """\
-
-
-  
-    
-      
-        
-        
-      
-    
-  
-  
-
-  
-  
-    
-      
-    
-  
-"""
-
-if sys.platform == "win32":
-    from distutils.msvccompiler import get_build_version
-
-    if get_build_version() >= 8.0:
-        SKIP_MESSAGE = None
-    else:
-        SKIP_MESSAGE = "These tests are only for MSVC8.0 or above"
-else:
-    SKIP_MESSAGE = "These tests are only for win32"
-
-
-@pytest.mark.skipif('SKIP_MESSAGE', reason=SKIP_MESSAGE)
-class Testmsvc9compiler(support.TempdirManager):
-    def test_no_compiler(self):
-        # makes sure query_vcvarsall raises
-        # a DistutilsPlatformError if the compiler
-        # is not found
-        from distutils.msvc9compiler import query_vcvarsall
-
-        def _find_vcvarsall(version):
-            return None
-
-        from distutils import msvc9compiler
-
-        old_find_vcvarsall = msvc9compiler.find_vcvarsall
-        msvc9compiler.find_vcvarsall = _find_vcvarsall
-        try:
-            with pytest.raises(DistutilsPlatformError):
-                query_vcvarsall('wont find this version')
-        finally:
-            msvc9compiler.find_vcvarsall = old_find_vcvarsall
-
-    def test_reg_class(self):
-        from distutils.msvc9compiler import Reg
-
-        with pytest.raises(KeyError):
-            Reg.get_value('xxx', 'xxx')
-
-        # looking for values that should exist on all
-        # windows registry versions.
-        path = r'Control Panel\Desktop'
-        v = Reg.get_value(path, 'dragfullwindows')
-        assert v in ('0', '1', '2')
-
-        import winreg
-
-        HKCU = winreg.HKEY_CURRENT_USER
-        keys = Reg.read_keys(HKCU, 'xxxx')
-        assert keys is None
-
-        keys = Reg.read_keys(HKCU, r'Control Panel')
-        assert 'Desktop' in keys
-
-    def test_remove_visual_c_ref(self):
-        from distutils.msvc9compiler import MSVCCompiler
-
-        tempdir = self.mkdtemp()
-        manifest = os.path.join(tempdir, 'manifest')
-        f = open(manifest, 'w')
-        try:
-            f.write(_MANIFEST_WITH_MULTIPLE_REFERENCES)
-        finally:
-            f.close()
-
-        compiler = MSVCCompiler()
-        compiler._remove_visual_c_ref(manifest)
-
-        # see what we got
-        f = open(manifest)
-        try:
-            # removing trailing spaces
-            content = '\n'.join([line.rstrip() for line in f.readlines()])
-        finally:
-            f.close()
-
-        # makes sure the manifest was properly cleaned
-        assert content == _CLEANED_MANIFEST
-
-    def test_remove_entire_manifest(self):
-        from distutils.msvc9compiler import MSVCCompiler
-
-        tempdir = self.mkdtemp()
-        manifest = os.path.join(tempdir, 'manifest')
-        f = open(manifest, 'w')
-        try:
-            f.write(_MANIFEST_WITH_ONLY_MSVC_REFERENCE)
-        finally:
-            f.close()
-
-        compiler = MSVCCompiler()
-        got = compiler._remove_visual_c_ref(manifest)
-        assert got is None
diff --git a/setuptools/_distutils/tests/test_register.py b/setuptools/_distutils/tests/test_register.py
deleted file mode 100644
index 34e593244e..0000000000
--- a/setuptools/_distutils/tests/test_register.py
+++ /dev/null
@@ -1,321 +0,0 @@
-"""Tests for distutils.command.register."""
-import os
-import getpass
-import urllib
-
-from distutils.command import register as register_module
-from distutils.command.register import register
-from distutils.errors import DistutilsSetupError
-
-from distutils.tests.test_config import BasePyPIRCCommandTestCase
-import pytest
-
-try:
-    import docutils
-except ImportError:
-    docutils = None
-
-PYPIRC_NOPASSWORD = """\
-[distutils]
-
-index-servers =
-    server1
-
-[server1]
-username:me
-"""
-
-WANTED_PYPIRC = """\
-[distutils]
-index-servers =
-    pypi
-
-[pypi]
-username:tarek
-password:password
-"""
-
-
-class Inputs:
-    """Fakes user inputs."""
-
-    def __init__(self, *answers):
-        self.answers = answers
-        self.index = 0
-
-    def __call__(self, prompt=''):
-        try:
-            return self.answers[self.index]
-        finally:
-            self.index += 1
-
-
-class FakeOpener:
-    """Fakes a PyPI server"""
-
-    def __init__(self):
-        self.reqs = []
-
-    def __call__(self, *args):
-        return self
-
-    def open(self, req, data=None, timeout=None):
-        self.reqs.append(req)
-        return self
-
-    def read(self):
-        return b'xxx'
-
-    def getheader(self, name, default=None):
-        return {
-            'content-type': 'text/plain; charset=utf-8',
-        }.get(name.lower(), default)
-
-
-@pytest.fixture(autouse=True)
-def autopass(monkeypatch):
-    monkeypatch.setattr(getpass, 'getpass', lambda prompt: 'password')
-
-
-@pytest.fixture(autouse=True)
-def fake_opener(monkeypatch, request):
-    opener = FakeOpener()
-    monkeypatch.setattr(urllib.request, 'build_opener', opener)
-    monkeypatch.setattr(urllib.request, '_opener', None)
-    request.instance.conn = opener
-
-
-class TestRegister(BasePyPIRCCommandTestCase):
-    def _get_cmd(self, metadata=None):
-        if metadata is None:
-            metadata = {
-                'url': 'xxx',
-                'author': 'xxx',
-                'author_email': 'xxx',
-                'name': 'xxx',
-                'version': 'xxx',
-                'long_description': 'xxx',
-            }
-        pkg_info, dist = self.create_dist(**metadata)
-        return register(dist)
-
-    def test_create_pypirc(self):
-        # this test makes sure a .pypirc file
-        # is created when requested.
-
-        # let's create a register instance
-        cmd = self._get_cmd()
-
-        # we shouldn't have a .pypirc file yet
-        assert not os.path.exists(self.rc)
-
-        # patching input and getpass.getpass
-        # so register gets happy
-        #
-        # Here's what we are faking :
-        # use your existing login (choice 1.)
-        # Username : 'tarek'
-        # Password : 'password'
-        # Save your login (y/N)? : 'y'
-        inputs = Inputs('1', 'tarek', 'y')
-        register_module.input = inputs.__call__
-        # let's run the command
-        try:
-            cmd.run()
-        finally:
-            del register_module.input
-
-        # we should have a brand new .pypirc file
-        assert os.path.exists(self.rc)
-
-        # with the content similar to WANTED_PYPIRC
-        f = open(self.rc)
-        try:
-            content = f.read()
-            assert content == WANTED_PYPIRC
-        finally:
-            f.close()
-
-        # now let's make sure the .pypirc file generated
-        # really works : we shouldn't be asked anything
-        # if we run the command again
-        def _no_way(prompt=''):
-            raise AssertionError(prompt)
-
-        register_module.input = _no_way
-
-        cmd.show_response = 1
-        cmd.run()
-
-        # let's see what the server received : we should
-        # have 2 similar requests
-        assert len(self.conn.reqs) == 2
-        req1 = dict(self.conn.reqs[0].headers)
-        req2 = dict(self.conn.reqs[1].headers)
-
-        assert req1['Content-length'] == '1358'
-        assert req2['Content-length'] == '1358'
-        assert b'xxx' in self.conn.reqs[1].data
-
-    def test_password_not_in_file(self):
-        self.write_file(self.rc, PYPIRC_NOPASSWORD)
-        cmd = self._get_cmd()
-        cmd._set_config()
-        cmd.finalize_options()
-        cmd.send_metadata()
-
-        # dist.password should be set
-        # therefore used afterwards by other commands
-        assert cmd.distribution.password == 'password'
-
-    def test_registering(self):
-        # this test runs choice 2
-        cmd = self._get_cmd()
-        inputs = Inputs('2', 'tarek', 'tarek@ziade.org')
-        register_module.input = inputs.__call__
-        try:
-            # let's run the command
-            cmd.run()
-        finally:
-            del register_module.input
-
-        # we should have send a request
-        assert len(self.conn.reqs) == 1
-        req = self.conn.reqs[0]
-        headers = dict(req.headers)
-        assert headers['Content-length'] == '608'
-        assert b'tarek' in req.data
-
-    def test_password_reset(self):
-        # this test runs choice 3
-        cmd = self._get_cmd()
-        inputs = Inputs('3', 'tarek@ziade.org')
-        register_module.input = inputs.__call__
-        try:
-            # let's run the command
-            cmd.run()
-        finally:
-            del register_module.input
-
-        # we should have send a request
-        assert len(self.conn.reqs) == 1
-        req = self.conn.reqs[0]
-        headers = dict(req.headers)
-        assert headers['Content-length'] == '290'
-        assert b'tarek' in req.data
-
-    def test_strict(self):
-        # testing the strict option
-        # when on, the register command stops if
-        # the metadata is incomplete or if
-        # long_description is not reSt compliant
-
-        pytest.importorskip('docutils')
-
-        # empty metadata
-        cmd = self._get_cmd({})
-        cmd.ensure_finalized()
-        cmd.strict = 1
-        with pytest.raises(DistutilsSetupError):
-            cmd.run()
-
-        # metadata are OK but long_description is broken
-        metadata = {
-            'url': 'xxx',
-            'author': 'xxx',
-            'author_email': 'éxéxé',
-            'name': 'xxx',
-            'version': 'xxx',
-            'long_description': 'title\n==\n\ntext',
-        }
-
-        cmd = self._get_cmd(metadata)
-        cmd.ensure_finalized()
-        cmd.strict = 1
-        with pytest.raises(DistutilsSetupError):
-            cmd.run()
-
-        # now something that works
-        metadata['long_description'] = 'title\n=====\n\ntext'
-        cmd = self._get_cmd(metadata)
-        cmd.ensure_finalized()
-        cmd.strict = 1
-        inputs = Inputs('1', 'tarek', 'y')
-        register_module.input = inputs.__call__
-        # let's run the command
-        try:
-            cmd.run()
-        finally:
-            del register_module.input
-
-        # strict is not by default
-        cmd = self._get_cmd()
-        cmd.ensure_finalized()
-        inputs = Inputs('1', 'tarek', 'y')
-        register_module.input = inputs.__call__
-        # let's run the command
-        try:
-            cmd.run()
-        finally:
-            del register_module.input
-
-        # and finally a Unicode test (bug #12114)
-        metadata = {
-            'url': 'xxx',
-            'author': '\u00c9ric',
-            'author_email': 'xxx',
-            'name': 'xxx',
-            'version': 'xxx',
-            'description': 'Something about esszet \u00df',
-            'long_description': 'More things about esszet \u00df',
-        }
-
-        cmd = self._get_cmd(metadata)
-        cmd.ensure_finalized()
-        cmd.strict = 1
-        inputs = Inputs('1', 'tarek', 'y')
-        register_module.input = inputs.__call__
-        # let's run the command
-        try:
-            cmd.run()
-        finally:
-            del register_module.input
-
-    def test_register_invalid_long_description(self, monkeypatch):
-        pytest.importorskip('docutils')
-        description = ':funkie:`str`'  # mimic Sphinx-specific markup
-        metadata = {
-            'url': 'xxx',
-            'author': 'xxx',
-            'author_email': 'xxx',
-            'name': 'xxx',
-            'version': 'xxx',
-            'long_description': description,
-        }
-        cmd = self._get_cmd(metadata)
-        cmd.ensure_finalized()
-        cmd.strict = True
-        inputs = Inputs('2', 'tarek', 'tarek@ziade.org')
-        monkeypatch.setattr(register_module, 'input', inputs, raising=False)
-
-        with pytest.raises(DistutilsSetupError):
-            cmd.run()
-
-    def test_list_classifiers(self, caplog):
-        cmd = self._get_cmd()
-        cmd.list_classifiers = 1
-        cmd.run()
-        assert caplog.messages == ['running check', 'xxx']
-
-    def test_show_response(self, caplog):
-        # test that the --show-response option return a well formatted response
-        cmd = self._get_cmd()
-        inputs = Inputs('1', 'tarek', 'y')
-        register_module.input = inputs.__call__
-        cmd.show_response = 1
-        try:
-            cmd.run()
-        finally:
-            del register_module.input
-
-        assert caplog.messages[3] == 75 * '-' + '\nxxx\n' + 75 * '-'
diff --git a/setuptools/_distutils/tests/test_sdist.py b/setuptools/_distutils/tests/test_sdist.py
index fdb768e73f..6b1a376b26 100644
--- a/setuptools/_distutils/tests/test_sdist.py
+++ b/setuptools/_distutils/tests/test_sdist.py
@@ -1,25 +1,25 @@
 """Tests for distutils.command.sdist."""
+
 import os
+import pathlib
+import shutil  # noqa: F401
 import tarfile
-import warnings
 import zipfile
+from distutils.archive_util import ARCHIVE_FORMATS
+from distutils.command.sdist import sdist, show_formats
+from distutils.core import Distribution
+from distutils.errors import DistutilsOptionError
+from distutils.filelist import FileList
 from os.path import join
 from textwrap import dedent
-from .unix_compat import require_unix_id, require_uid_0, pwd, grp
 
-import pytest
-import path
 import jaraco.path
+import path
+import pytest
+from more_itertools import ilen
 
-from .py38compat import check_warnings
-
-from distutils.command.sdist import sdist, show_formats
-from distutils.core import Distribution
-from distutils.tests.test_config import BasePyPIRCCommandTestCase
-from distutils.errors import DistutilsOptionError
-from distutils.spawn import find_executable  # noqa: F401
-from distutils.filelist import FileList
-from distutils.archive_util import ARCHIVE_FORMATS
+from . import support
+from .unix_compat import grp, pwd, require_uid_0, require_unix_id
 
 SETUP_PY = """
 from distutils.core import setup
@@ -45,8 +45,9 @@
 
 
 @pytest.fixture(autouse=True)
-def project_dir(request, pypirc):
+def project_dir(request, distutils_managed_tempdir):
     self = request.instance
+    self.tmp_dir = self.mkdtemp()
     jaraco.path.build(
         {
             'somecode': {
@@ -61,12 +62,17 @@ def project_dir(request, pypirc):
         yield
 
 
-class TestSDist(BasePyPIRCCommandTestCase):
+def clean_lines(filepath):
+    with pathlib.Path(filepath).open(encoding='utf-8') as f:
+        yield from filter(None, map(str.strip, f))
+
+
+class TestSDist(support.TempdirManager):
     def get_cmd(self, metadata=None):
         """Returns a cmd"""
         if metadata is None:
             metadata = {
-                'name': 'fake',
+                'name': 'ns.fake--pkg',
                 'version': '1.0',
                 'url': 'xxx',
                 'author': 'xxx',
@@ -110,9 +116,9 @@ def test_prune_file_list(self):
         # now let's check what we have
         dist_folder = join(self.tmp_dir, 'dist')
         files = os.listdir(dist_folder)
-        assert files == ['fake-1.0.zip']
+        assert files == ['ns_fake_pkg-1.0.zip']
 
-        zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip'))
+        zip_file = zipfile.ZipFile(join(dist_folder, 'ns_fake_pkg-1.0.zip'))
         try:
             content = zip_file.namelist()
         finally:
@@ -127,11 +133,11 @@ def test_prune_file_list(self):
             'somecode/',
             'somecode/__init__.py',
         ]
-        assert sorted(content) == ['fake-1.0/' + x for x in expected]
+        assert sorted(content) == ['ns_fake_pkg-1.0/' + x for x in expected]
 
     @pytest.mark.usefixtures('needs_zlib')
-    @pytest.mark.skipif("not find_executable('tar')")
-    @pytest.mark.skipif("not find_executable('gzip')")
+    @pytest.mark.skipif("not shutil.which('tar')")
+    @pytest.mark.skipif("not shutil.which('gzip')")
     def test_make_distribution(self):
         # now building a sdist
         dist, cmd = self.get_cmd()
@@ -145,10 +151,10 @@ def test_make_distribution(self):
         dist_folder = join(self.tmp_dir, 'dist')
         result = os.listdir(dist_folder)
         result.sort()
-        assert result == ['fake-1.0.tar', 'fake-1.0.tar.gz']
+        assert result == ['ns_fake_pkg-1.0.tar', 'ns_fake_pkg-1.0.tar.gz']
 
-        os.remove(join(dist_folder, 'fake-1.0.tar'))
-        os.remove(join(dist_folder, 'fake-1.0.tar.gz'))
+        os.remove(join(dist_folder, 'ns_fake_pkg-1.0.tar'))
+        os.remove(join(dist_folder, 'ns_fake_pkg-1.0.tar.gz'))
 
         # now trying a tar then a gztar
         cmd.formats = ['tar', 'gztar']
@@ -158,11 +164,11 @@ def test_make_distribution(self):
 
         result = os.listdir(dist_folder)
         result.sort()
-        assert result == ['fake-1.0.tar', 'fake-1.0.tar.gz']
+        assert result == ['ns_fake_pkg-1.0.tar', 'ns_fake_pkg-1.0.tar.gz']
 
     @pytest.mark.usefixtures('needs_zlib')
     def test_add_defaults(self):
-        # http://bugs.python.org/issue2279
+        # https://bugs.python.org/issue2279
 
         # add_default should also include
         # data_files and package_data
@@ -211,9 +217,9 @@ def test_add_defaults(self):
         # now let's check what we have
         dist_folder = join(self.tmp_dir, 'dist')
         files = os.listdir(dist_folder)
-        assert files == ['fake-1.0.zip']
+        assert files == ['ns_fake_pkg-1.0.zip']
 
-        zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip'))
+        zip_file = zipfile.ZipFile(join(dist_folder, 'ns_fake_pkg-1.0.zip'))
         try:
             content = zip_file.namelist()
         finally:
@@ -239,14 +245,10 @@ def test_add_defaults(self):
             'somecode/doc.dat',
             'somecode/doc.txt',
         ]
-        assert sorted(content) == ['fake-1.0/' + x for x in expected]
+        assert sorted(content) == ['ns_fake_pkg-1.0/' + x for x in expected]
 
         # checking the MANIFEST
-        f = open(join(self.tmp_dir, 'MANIFEST'))
-        try:
-            manifest = f.read()
-        finally:
-            f.close()
+        manifest = pathlib.Path(self.tmp_dir, 'MANIFEST').read_text(encoding='utf-8')
         assert manifest == MANIFEST % {'sep': os.sep}
 
     @staticmethod
@@ -268,18 +270,10 @@ def test_metadata_check_option(self, caplog):
         caplog.clear()
         dist, cmd = self.get_cmd()
         cmd.ensure_finalized()
-        cmd.metadata_check = 0
+        cmd.metadata_check = False
         cmd.run()
         assert len(self.warnings(caplog.messages, 'warning: check: ')) == 0
 
-    def test_check_metadata_deprecated(self):
-        # makes sure make_metadata is deprecated
-        dist, cmd = self.get_cmd()
-        with check_warnings() as w:
-            warnings.simplefilter("always")
-            cmd.check_metadata()
-            assert len(w.warnings) == 1
-
     def test_show_formats(self, capsys):
         show_formats()
 
@@ -351,15 +345,7 @@ def test_get_file_list(self):
         cmd.ensure_finalized()
         cmd.run()
 
-        f = open(cmd.manifest)
-        try:
-            manifest = [
-                line.strip() for line in f.read().split('\n') if line.strip() != ''
-            ]
-        finally:
-            f.close()
-
-        assert len(manifest) == 5
+        assert ilen(clean_lines(cmd.manifest)) == 5
 
         # adding a file
         self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#')
@@ -371,13 +357,7 @@ def test_get_file_list(self):
 
         cmd.run()
 
-        f = open(cmd.manifest)
-        try:
-            manifest2 = [
-                line.strip() for line in f.read().split('\n') if line.strip() != ''
-            ]
-        finally:
-            f.close()
+        manifest2 = list(clean_lines(cmd.manifest))
 
         # do we have the new file in MANIFEST ?
         assert len(manifest2) == 6
@@ -390,15 +370,10 @@ def test_manifest_marker(self):
         cmd.ensure_finalized()
         cmd.run()
 
-        f = open(cmd.manifest)
-        try:
-            manifest = [
-                line.strip() for line in f.read().split('\n') if line.strip() != ''
-            ]
-        finally:
-            f.close()
-
-        assert manifest[0] == '# file GENERATED by distutils, do NOT edit'
+        assert (
+            next(clean_lines(cmd.manifest))
+            == '# file GENERATED by distutils, do NOT edit'
+        )
 
     @pytest.mark.usefixtures('needs_zlib')
     def test_manifest_comments(self):
@@ -433,33 +408,25 @@ def test_manual_manifest(self):
         cmd.run()
         assert cmd.filelist.files == ['README.manual']
 
-        f = open(cmd.manifest)
-        try:
-            manifest = [
-                line.strip() for line in f.read().split('\n') if line.strip() != ''
-            ]
-        finally:
-            f.close()
-
-        assert manifest == ['README.manual']
+        assert list(clean_lines(cmd.manifest)) == ['README.manual']
 
-        archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz')
+        archive_name = join(self.tmp_dir, 'dist', 'ns_fake_pkg-1.0.tar.gz')
         archive = tarfile.open(archive_name)
         try:
             filenames = [tarinfo.name for tarinfo in archive]
         finally:
             archive.close()
         assert sorted(filenames) == [
-            'fake-1.0',
-            'fake-1.0/PKG-INFO',
-            'fake-1.0/README.manual',
+            'ns_fake_pkg-1.0',
+            'ns_fake_pkg-1.0/PKG-INFO',
+            'ns_fake_pkg-1.0/README.manual',
         ]
 
     @pytest.mark.usefixtures('needs_zlib')
     @require_unix_id
     @require_uid_0
-    @pytest.mark.skipif("not find_executable('tar')")
-    @pytest.mark.skipif("not find_executable('gzip')")
+    @pytest.mark.skipif("not shutil.which('tar')")
+    @pytest.mark.skipif("not shutil.which('gzip')")
     def test_make_distribution_owner_group(self):
         # now building a sdist
         dist, cmd = self.get_cmd()
@@ -472,7 +439,7 @@ def test_make_distribution_owner_group(self):
         cmd.run()
 
         # making sure we have the good rights
-        archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz')
+        archive_name = join(self.tmp_dir, 'dist', 'ns_fake_pkg-1.0.tar.gz')
         archive = tarfile.open(archive_name)
         try:
             for member in archive.getmembers():
@@ -490,7 +457,7 @@ def test_make_distribution_owner_group(self):
         cmd.run()
 
         # making sure we have the good rights
-        archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz')
+        archive_name = join(self.tmp_dir, 'dist', 'ns_fake_pkg-1.0.tar.gz')
         archive = tarfile.open(archive_name)
 
         # note that we are not testing the group ownership here
diff --git a/setuptools/_distutils/tests/test_spawn.py b/setuptools/_distutils/tests/test_spawn.py
index 08a34ee2b8..3b9fc926f6 100644
--- a/setuptools/_distutils/tests/test_spawn.py
+++ b/setuptools/_distutils/tests/test_spawn.py
@@ -1,20 +1,18 @@
 """Tests for distutils.spawn."""
+
 import os
 import stat
 import sys
 import unittest.mock as mock
-
-from test.support import unix_shell
-
-import path
-
-from . import py38compat as os_helper
-
-from distutils.spawn import find_executable
-from distutils.spawn import spawn
 from distutils.errors import DistutilsExecError
+from distutils.spawn import find_executable, spawn
 from distutils.tests import support
+
+import path
 import pytest
+from test.support import unix_shell
+
+from .compat import py39 as os_helper
 
 
 class TestSpawn(support.TempdirManager):
@@ -26,7 +24,7 @@ def test_spawn(self):
         # through the shell that returns 1
         if sys.platform != 'win32':
             exe = os.path.join(tmpdir, 'foo.sh')
-            self.write_file(exe, '#!%s\nexit 1' % unix_shell)
+            self.write_file(exe, f'#!{unix_shell}\nexit 1')
         else:
             exe = os.path.join(tmpdir, 'foo.bat')
             self.write_file(exe, 'exit 1')
@@ -38,7 +36,7 @@ def test_spawn(self):
         # now something that works
         if sys.platform != 'win32':
             exe = os.path.join(tmpdir, 'foo.sh')
-            self.write_file(exe, '#!%s\nexit 0' % unix_shell)
+            self.write_file(exe, f'#!{unix_shell}\nexit 0')
         else:
             exe = os.path.join(tmpdir, 'foo.bat')
             self.write_file(exe, 'exit 0')
@@ -47,14 +45,9 @@ def test_spawn(self):
         spawn([exe])  # should work without any error
 
     def test_find_executable(self, tmp_path):
-        program_noeext = 'program'
-        # Give the temporary program an ".exe" suffix for all.
-        # It's needed on Windows and not harmful on other platforms.
-        program = program_noeext + ".exe"
-
-        program_path = tmp_path / program
-        program_path.write_text("")
-        program_path.chmod(stat.S_IXUSR)
+        program_path = self._make_executable(tmp_path, '.exe')
+        program = program_path.name
+        program_noeext = program_path.with_suffix('').name
         filename = str(program_path)
         tmp_dir = path.Path(tmp_path)
 
@@ -80,9 +73,12 @@ def test_find_executable(self, tmp_path):
         # PATH='': no match, except in the current directory
         with os_helper.EnvironmentVarGuard() as env:
             env['PATH'] = ''
-            with mock.patch(
-                'distutils.spawn.os.confstr', return_value=tmp_dir, create=True
-            ), mock.patch('distutils.spawn.os.defpath', tmp_dir):
+            with (
+                mock.patch(
+                    'distutils.spawn.os.confstr', return_value=tmp_dir, create=True
+                ),
+                mock.patch('distutils.spawn.os.defpath', tmp_dir),
+            ):
                 rv = find_executable(program)
                 assert rv is None
 
@@ -94,9 +90,10 @@ def test_find_executable(self, tmp_path):
         # PATH=':': explicitly looks in the current directory
         with os_helper.EnvironmentVarGuard() as env:
             env['PATH'] = os.pathsep
-            with mock.patch(
-                'distutils.spawn.os.confstr', return_value='', create=True
-            ), mock.patch('distutils.spawn.os.defpath', ''):
+            with (
+                mock.patch('distutils.spawn.os.confstr', return_value='', create=True),
+                mock.patch('distutils.spawn.os.defpath', ''),
+            ):
                 rv = find_executable(program)
                 assert rv is None
 
@@ -110,19 +107,34 @@ def test_find_executable(self, tmp_path):
             env.pop('PATH', None)
 
             # without confstr
-            with mock.patch(
-                'distutils.spawn.os.confstr', side_effect=ValueError, create=True
-            ), mock.patch('distutils.spawn.os.defpath', tmp_dir):
+            with (
+                mock.patch(
+                    'distutils.spawn.os.confstr', side_effect=ValueError, create=True
+                ),
+                mock.patch('distutils.spawn.os.defpath', tmp_dir),
+            ):
                 rv = find_executable(program)
                 assert rv == filename
 
             # with confstr
-            with mock.patch(
-                'distutils.spawn.os.confstr', return_value=tmp_dir, create=True
-            ), mock.patch('distutils.spawn.os.defpath', ''):
+            with (
+                mock.patch(
+                    'distutils.spawn.os.confstr', return_value=tmp_dir, create=True
+                ),
+                mock.patch('distutils.spawn.os.defpath', ''),
+            ):
                 rv = find_executable(program)
                 assert rv == filename
 
+    @staticmethod
+    def _make_executable(tmp_path, ext):
+        # Give the temporary program a suffix regardless of platform.
+        # It's needed on Windows and not harmful on others.
+        program = tmp_path.joinpath('program').with_suffix(ext)
+        program.write_text("", encoding='utf-8')
+        program.chmod(stat.S_IXUSR)
+        return program
+
     def test_spawn_missing_exe(self):
         with pytest.raises(DistutilsExecError) as ctx:
             spawn(['does-not-exist'])
diff --git a/setuptools/_distutils/tests/test_sysconfig.py b/setuptools/_distutils/tests/test_sysconfig.py
index bfeaf9a6b9..43d77c23fa 100644
--- a/setuptools/_distutils/tests/test_sysconfig.py
+++ b/setuptools/_distutils/tests/test_sysconfig.py
@@ -1,22 +1,25 @@
 """Tests for distutils.sysconfig."""
+
 import contextlib
+import distutils
 import os
+import pathlib
 import subprocess
 import sys
-import pathlib
+from distutils import sysconfig
+from distutils.ccompiler import new_compiler  # noqa: F401
+from distutils.unixccompiler import UnixCCompiler
 
-import pytest
 import jaraco.envs
 import path
+import pytest
 from jaraco.text import trim
-
-import distutils
-from distutils import sysconfig
-from distutils.ccompiler import get_default_compiler  # noqa: F401
-from distutils.unixccompiler import UnixCCompiler
 from test.support import swap_item
 
-from . import py37compat
+
+def _gen_makefile(root, contents):
+    jaraco.path.build({'Makefile': trim(contents)}, root)
+    return root / 'Makefile'
 
 
 @pytest.mark.usefixtures('save_env')
@@ -97,8 +100,6 @@ def set_executables(self, **kw):
             'CCSHARED': '--sc-ccshared',
             'LDSHARED': 'sc_ldshared',
             'SHLIB_SUFFIX': 'sc_shutil_suffix',
-            # On macOS, disable _osx_support.customize_compiler()
-            'CUSTOMIZED_OSX_COMPILER': 'True',
         }
 
         comp = compiler()
@@ -109,7 +110,8 @@ def set_executables(self, **kw):
 
         return comp
 
-    @pytest.mark.skipif("get_default_compiler() != 'unix'")
+    @pytest.mark.skipif("not isinstance(new_compiler(), UnixCCompiler)")
+    @pytest.mark.usefixtures('disable_macos_customization')
     def test_customize_compiler(self):
         # Make sure that sysconfig._config_vars is initialized
         sysconfig.get_config_vars()
@@ -128,14 +130,17 @@ def test_customize_compiler(self):
         comp = self.customize_compiler()
         assert comp.exes['archiver'] == 'env_ar --env-arflags'
         assert comp.exes['preprocessor'] == 'env_cpp --env-cppflags'
-        assert comp.exes['compiler'] == 'env_cc --sc-cflags --env-cflags --env-cppflags'
+        assert comp.exes['compiler'] == 'env_cc --env-cflags --env-cppflags'
         assert comp.exes['compiler_so'] == (
-            'env_cc --sc-cflags ' '--env-cflags ' '--env-cppflags --sc-ccshared'
+            'env_cc --env-cflags --env-cppflags --sc-ccshared'
+        )
+        assert (
+            comp.exes['compiler_cxx']
+            == 'env_cxx --env-cxx-flags --sc-cflags --env-cppflags'
         )
-        assert comp.exes['compiler_cxx'] == 'env_cxx --env-cxx-flags'
         assert comp.exes['linker_exe'] == 'env_cc'
         assert comp.exes['linker_so'] == (
-            'env_ldshared --env-ldflags --env-cflags' ' --env-cppflags'
+            'env_ldshared --env-ldflags --env-cflags --env-cppflags'
         )
         assert comp.shared_lib_extension == 'sc_shutil_suffix'
 
@@ -160,36 +165,32 @@ def test_customize_compiler(self):
         assert comp.exes['preprocessor'] == 'sc_cc -E'
         assert comp.exes['compiler'] == 'sc_cc --sc-cflags'
         assert comp.exes['compiler_so'] == 'sc_cc --sc-cflags --sc-ccshared'
-        assert comp.exes['compiler_cxx'] == 'sc_cxx'
+        assert comp.exes['compiler_cxx'] == 'sc_cxx --sc-cflags'
         assert comp.exes['linker_exe'] == 'sc_cc'
         assert comp.exes['linker_so'] == 'sc_ldshared'
         assert comp.shared_lib_extension == 'sc_shutil_suffix'
         assert 'ranlib' not in comp.exes
 
     def test_parse_makefile_base(self, tmp_path):
-        makefile = tmp_path / 'Makefile'
-        makefile.write_text(
-            trim(
-                """
-                CONFIG_ARGS=  '--arg1=optarg1' 'ENV=LIB'
-                VAR=$OTHER
-                OTHER=foo
-                """
-            )
+        makefile = _gen_makefile(
+            tmp_path,
+            """
+            CONFIG_ARGS=  '--arg1=optarg1' 'ENV=LIB'
+            VAR=$OTHER
+            OTHER=foo
+            """,
         )
         d = sysconfig.parse_makefile(makefile)
         assert d == {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'", 'OTHER': 'foo'}
 
     def test_parse_makefile_literal_dollar(self, tmp_path):
-        makefile = tmp_path / 'Makefile'
-        makefile.write_text(
-            trim(
-                """
-                CONFIG_ARGS=  '--arg1=optarg1' 'ENV=\\$$LIB'
-                VAR=$OTHER
-                OTHER=foo
-                """
-            )
+        makefile = _gen_makefile(
+            tmp_path,
+            """
+            CONFIG_ARGS=  '--arg1=optarg1' 'ENV=\\$$LIB'
+            VAR=$OTHER
+            OTHER=foo
+            """,
         )
         d = sysconfig.parse_makefile(makefile)
         assert d == {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'", 'OTHER': 'foo'}
@@ -204,22 +205,21 @@ def test_sysconfig_module(self):
             'LDFLAGS'
         )
 
+    # On macOS, binary installers support extension module building on
+    # various levels of the operating system with differing Xcode
+    # configurations, requiring customization of some of the
+    # compiler configuration directives to suit the environment on
+    # the installed machine. Some of these customizations may require
+    # running external programs and are thus deferred until needed by
+    # the first extension module build. Only
+    # the Distutils version of sysconfig is used for extension module
+    # builds, which happens earlier in the Distutils tests. This may
+    # cause the following tests to fail since no tests have caused
+    # the global version of sysconfig to call the customization yet.
+    # The solution for now is to simply skip this test in this case.
+    # The longer-term solution is to only have one version of sysconfig.
     @pytest.mark.skipif("sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER')")
     def test_sysconfig_compiler_vars(self):
-        # On OS X, binary installers support extension module building on
-        # various levels of the operating system with differing Xcode
-        # configurations.  This requires customization of some of the
-        # compiler configuration directives to suit the environment on
-        # the installed machine.  Some of these customizations may require
-        # running external programs and, so, are deferred until needed by
-        # the first extension module build.  With Python 3.3, only
-        # the Distutils version of sysconfig is used for extension module
-        # builds, which happens earlier in the Distutils tests.  This may
-        # cause the following tests to fail since no tests have caused
-        # the global version of sysconfig to call the customization yet.
-        # The solution for now is to simply skip this test in this case.
-        # The longer-term solution is to only have one version of sysconfig.
-
         import sysconfig as global_sysconfig
 
         if sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'):
@@ -238,23 +238,24 @@ def test_customize_compiler_before_get_config_vars(self, tmp_path):
         # Issue #21923: test that a Distribution compiler
         # instance can be called without an explicit call to
         # get_config_vars().
-        file = tmp_path / 'file'
-        file.write_text(
-            trim(
-                """
-                from distutils.core import Distribution
-                config = Distribution().get_command_obj('config')
-                # try_compile may pass or it may fail if no compiler
-                # is found but it should not raise an exception.
-                rc = config.try_compile('int x;')
-                """
-            )
+        jaraco.path.build(
+            {
+                'file': trim("""
+                    from distutils.core import Distribution
+                    config = Distribution().get_command_obj('config')
+                    # try_compile may pass or it may fail if no compiler
+                    # is found but it should not raise an exception.
+                    rc = config.try_compile('int x;')
+                    """)
+            },
+            tmp_path,
         )
         p = subprocess.Popen(
-            py37compat.subprocess_args(sys.executable, file),
+            [sys.executable, tmp_path / 'file'],
             stdout=subprocess.PIPE,
             stderr=subprocess.STDOUT,
             universal_newlines=True,
+            encoding='utf-8',
         )
         outs, errs = p.communicate()
         assert 0 == p.returncode, "Subprocess failed: " + outs
diff --git a/setuptools/_distutils/tests/test_text_file.py b/setuptools/_distutils/tests/test_text_file.py
index 7c8dc5be54..f511156561 100644
--- a/setuptools/_distutils/tests/test_text_file.py
+++ b/setuptools/_distutils/tests/test_text_file.py
@@ -1,7 +1,10 @@
 """Tests for distutils.text_file."""
-import os
-from distutils.text_file import TextFile
+
 from distutils.tests import support
+from distutils.text_file import TextFile
+
+import jaraco.path
+import path
 
 TEST_DATA = """# test file
 
@@ -52,16 +55,16 @@ def test_input(count, description, file, expected_result):
             result = file.readlines()
             assert result == expected_result
 
-        tmpdir = self.mkdtemp()
-        filename = os.path.join(tmpdir, "test.txt")
-        out_file = open(filename, "w")
-        try:
-            out_file.write(TEST_DATA)
-        finally:
-            out_file.close()
+        tmp_path = path.Path(self.mkdtemp())
+        filename = tmp_path / 'test.txt'
+        jaraco.path.build({filename.name: TEST_DATA}, tmp_path)
 
         in_file = TextFile(
-            filename, strip_comments=0, skip_blanks=0, lstrip_ws=0, rstrip_ws=0
+            filename,
+            strip_comments=False,
+            skip_blanks=False,
+            lstrip_ws=False,
+            rstrip_ws=False,
         )
         try:
             test_input(1, "no processing", in_file, result1)
@@ -69,7 +72,11 @@ def test_input(count, description, file, expected_result):
             in_file.close()
 
         in_file = TextFile(
-            filename, strip_comments=1, skip_blanks=0, lstrip_ws=0, rstrip_ws=0
+            filename,
+            strip_comments=True,
+            skip_blanks=False,
+            lstrip_ws=False,
+            rstrip_ws=False,
         )
         try:
             test_input(2, "strip comments", in_file, result2)
@@ -77,7 +84,11 @@ def test_input(count, description, file, expected_result):
             in_file.close()
 
         in_file = TextFile(
-            filename, strip_comments=0, skip_blanks=1, lstrip_ws=0, rstrip_ws=0
+            filename,
+            strip_comments=False,
+            skip_blanks=True,
+            lstrip_ws=False,
+            rstrip_ws=False,
         )
         try:
             test_input(3, "strip blanks", in_file, result3)
@@ -91,7 +102,11 @@ def test_input(count, description, file, expected_result):
             in_file.close()
 
         in_file = TextFile(
-            filename, strip_comments=1, skip_blanks=1, join_lines=1, rstrip_ws=1
+            filename,
+            strip_comments=True,
+            skip_blanks=True,
+            join_lines=True,
+            rstrip_ws=True,
         )
         try:
             test_input(5, "join lines without collapsing", in_file, result5)
@@ -100,11 +115,11 @@ def test_input(count, description, file, expected_result):
 
         in_file = TextFile(
             filename,
-            strip_comments=1,
-            skip_blanks=1,
-            join_lines=1,
-            rstrip_ws=1,
-            collapse_join=1,
+            strip_comments=True,
+            skip_blanks=True,
+            join_lines=True,
+            rstrip_ws=True,
+            collapse_join=True,
         )
         try:
             test_input(6, "join lines with collapsing", in_file, result6)
diff --git a/setuptools/_distutils/tests/test_upload.py b/setuptools/_distutils/tests/test_upload.py
deleted file mode 100644
index af113b8b6e..0000000000
--- a/setuptools/_distutils/tests/test_upload.py
+++ /dev/null
@@ -1,216 +0,0 @@
-"""Tests for distutils.command.upload."""
-import os
-import unittest.mock as mock
-from urllib.request import HTTPError
-
-
-from distutils.command import upload as upload_mod
-from distutils.command.upload import upload
-from distutils.core import Distribution
-from distutils.errors import DistutilsError
-
-from distutils.tests.test_config import PYPIRC, BasePyPIRCCommandTestCase
-import pytest
-
-PYPIRC_LONG_PASSWORD = """\
-[distutils]
-
-index-servers =
-    server1
-    server2
-
-[server1]
-username:me
-password:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
-
-[server2]
-username:meagain
-password: secret
-realm:acme
-repository:http://another.pypi/
-"""
-
-
-PYPIRC_NOPASSWORD = """\
-[distutils]
-
-index-servers =
-    server1
-
-[server1]
-username:me
-"""
-
-
-class FakeOpen:
-    def __init__(self, url, msg=None, code=None):
-        self.url = url
-        if not isinstance(url, str):
-            self.req = url
-        else:
-            self.req = None
-        self.msg = msg or 'OK'
-        self.code = code or 200
-
-    def getheader(self, name, default=None):
-        return {
-            'content-type': 'text/plain; charset=utf-8',
-        }.get(name.lower(), default)
-
-    def read(self):
-        return b'xyzzy'
-
-    def getcode(self):
-        return self.code
-
-
-@pytest.fixture(autouse=True)
-def urlopen(request, monkeypatch):
-    self = request.instance
-    monkeypatch.setattr(upload_mod, 'urlopen', self._urlopen)
-    self.next_msg = self.next_code = None
-
-
-class TestUpload(BasePyPIRCCommandTestCase):
-    def _urlopen(self, url):
-        self.last_open = FakeOpen(url, msg=self.next_msg, code=self.next_code)
-        return self.last_open
-
-    def test_finalize_options(self):
-        # new format
-        self.write_file(self.rc, PYPIRC)
-        dist = Distribution()
-        cmd = upload(dist)
-        cmd.finalize_options()
-        for attr, waited in (
-            ('username', 'me'),
-            ('password', 'secret'),
-            ('realm', 'pypi'),
-            ('repository', 'https://upload.pypi.org/legacy/'),
-        ):
-            assert getattr(cmd, attr) == waited
-
-    def test_saved_password(self):
-        # file with no password
-        self.write_file(self.rc, PYPIRC_NOPASSWORD)
-
-        # make sure it passes
-        dist = Distribution()
-        cmd = upload(dist)
-        cmd.finalize_options()
-        assert cmd.password is None
-
-        # make sure we get it as well, if another command
-        # initialized it at the dist level
-        dist.password = 'xxx'
-        cmd = upload(dist)
-        cmd.finalize_options()
-        assert cmd.password == 'xxx'
-
-    def test_upload(self, caplog):
-        tmp = self.mkdtemp()
-        path = os.path.join(tmp, 'xxx')
-        self.write_file(path)
-        command, pyversion, filename = 'xxx', '2.6', path
-        dist_files = [(command, pyversion, filename)]
-        self.write_file(self.rc, PYPIRC_LONG_PASSWORD)
-
-        # lets run it
-        pkg_dir, dist = self.create_dist(dist_files=dist_files)
-        cmd = upload(dist)
-        cmd.show_response = 1
-        cmd.ensure_finalized()
-        cmd.run()
-
-        # what did we send ?
-        headers = dict(self.last_open.req.headers)
-        assert int(headers['Content-length']) >= 2162
-        content_type = headers['Content-type']
-        assert content_type.startswith('multipart/form-data')
-        assert self.last_open.req.get_method() == 'POST'
-        expected_url = 'https://upload.pypi.org/legacy/'
-        assert self.last_open.req.get_full_url() == expected_url
-        data = self.last_open.req.data
-        assert b'xxx' in data
-        assert b'protocol_version' in data
-        assert b'sha256_digest' in data
-        assert (
-            b'cd2eb0837c9b4c962c22d2ff8b5441b7b45805887f051d39bf133b583baf'
-            b'6860' in data
-        )
-        if b'md5_digest' in data:
-            assert b'f561aaf6ef0bf14d4208bb46a4ccb3ad' in data
-        if b'blake2_256_digest' in data:
-            assert (
-                b'b6f289a27d4fe90da63c503bfe0a9b761a8f76bb86148565065f040be'
-                b'6d1c3044cf7ded78ef800509bccb4b648e507d88dc6383d67642aadcc'
-                b'ce443f1534330a' in data
-            )
-
-        # The PyPI response body was echoed
-        results = caplog.messages
-        assert results[-1] == 75 * '-' + '\nxyzzy\n' + 75 * '-'
-
-    # bpo-32304: archives whose last byte was b'\r' were corrupted due to
-    # normalization intended for Mac OS 9.
-    def test_upload_correct_cr(self):
-        # content that ends with \r should not be modified.
-        tmp = self.mkdtemp()
-        path = os.path.join(tmp, 'xxx')
-        self.write_file(path, content='yy\r')
-        command, pyversion, filename = 'xxx', '2.6', path
-        dist_files = [(command, pyversion, filename)]
-        self.write_file(self.rc, PYPIRC_LONG_PASSWORD)
-
-        # other fields that ended with \r used to be modified, now are
-        # preserved.
-        pkg_dir, dist = self.create_dist(
-            dist_files=dist_files, description='long description\r'
-        )
-        cmd = upload(dist)
-        cmd.show_response = 1
-        cmd.ensure_finalized()
-        cmd.run()
-
-        headers = dict(self.last_open.req.headers)
-        assert int(headers['Content-length']) >= 2172
-        assert b'long description\r' in self.last_open.req.data
-
-    def test_upload_fails(self, caplog):
-        self.next_msg = "Not Found"
-        self.next_code = 404
-        with pytest.raises(DistutilsError):
-            self.test_upload(caplog)
-
-    @pytest.mark.parametrize(
-        'exception,expected,raised_exception',
-        [
-            (OSError('oserror'), 'oserror', OSError),
-            pytest.param(
-                HTTPError('url', 400, 'httperror', {}, None),
-                'Upload failed (400): httperror',
-                DistutilsError,
-                id="HTTP 400",
-            ),
-        ],
-    )
-    def test_wrong_exception_order(self, exception, expected, raised_exception, caplog):
-        tmp = self.mkdtemp()
-        path = os.path.join(tmp, 'xxx')
-        self.write_file(path)
-        dist_files = [('xxx', '2.6', path)]  # command, pyversion, filename
-        self.write_file(self.rc, PYPIRC_LONG_PASSWORD)
-
-        pkg_dir, dist = self.create_dist(dist_files=dist_files)
-
-        with mock.patch(
-            'distutils.command.upload.urlopen',
-            new=mock.Mock(side_effect=exception),
-        ):
-            with pytest.raises(raised_exception):
-                cmd = upload(dist)
-                cmd.ensure_finalized()
-                cmd.run()
-            results = caplog.messages
-            assert expected in results[-1]
-            caplog.clear()
diff --git a/setuptools/_distutils/tests/test_util.py b/setuptools/_distutils/tests/test_util.py
index 070a277069..00c9743ed0 100644
--- a/setuptools/_distutils/tests/test_util.py
+++ b/setuptools/_distutils/tests/test_util.py
@@ -1,27 +1,31 @@
 """Tests for distutils.util."""
+
+import email
+import email.generator
+import email.policy
+import io
 import os
+import pathlib
 import sys
 import sysconfig as stdlib_sysconfig
 import unittest.mock as mock
 from copy import copy
-
-import pytest
-
+from distutils import sysconfig, util
+from distutils.errors import DistutilsByteCompileError, DistutilsPlatformError
 from distutils.util import (
-    get_platform,
-    convert_path,
+    byte_compile,
     change_root,
     check_environ,
+    convert_path,
+    get_host_platform,
+    get_platform,
+    grok_environment_error,
+    rfc822_escape,
     split_quoted,
     strtobool,
-    rfc822_escape,
-    byte_compile,
-    grok_environment_error,
-    get_host_platform,
 )
-from distutils import util
-from distutils import sysconfig
-from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError
+
+import pytest
 
 
 @pytest.fixture(autouse=True)
@@ -60,30 +64,9 @@ def test_get_platform(self):
                 assert get_platform() == 'win-arm64'
 
     def test_convert_path(self):
-        # linux/mac
-        os.sep = '/'
-
-        def _join(path):
-            return '/'.join(path)
-
-        os.path.join = _join
-
-        assert convert_path('/home/to/my/stuff') == '/home/to/my/stuff'
-
-        # win
-        os.sep = '\\'
-
-        def _join(*path):
-            return '\\'.join(path)
-
-        os.path.join = _join
-
-        with pytest.raises(ValueError):
-            convert_path('/home/to/my/stuff')
-        with pytest.raises(ValueError):
-            convert_path('home/to/my/stuff/')
-
-        assert convert_path('home/to/my/stuff') == 'home\\to\\my\\stuff'
+        expected = os.sep.join(('', 'home', 'to', 'my', 'stuff'))
+        assert convert_path('/home/to/my/stuff') == expected
+        assert convert_path(pathlib.Path('/home/to/my/stuff')) == expected
         assert convert_path('.') == os.curdir
 
     def test_change_root(self):
@@ -105,6 +88,7 @@ def _join(*path):
 
         # windows
         os.name = 'nt'
+        os.sep = '\\'
 
         def _isabs(path):
             return path.startswith('c:\\')
@@ -151,9 +135,15 @@ def test_check_environ_getpwuid(self):
         import pwd
 
         # only set pw_dir field, other fields are not used
-        result = pwd.struct_passwd(
-            (None, None, None, None, None, '/home/distutils', None)
-        )
+        result = pwd.struct_passwd((
+            None,
+            None,
+            None,
+            None,
+            None,
+            '/home/distutils',
+            None,
+        ))
         with mock.patch.object(pwd, 'getpwuid', return_value=result):
             check_environ()
             assert os.environ['HOME'] == '/home/distutils'
@@ -184,12 +174,55 @@ def test_strtobool(self):
         for n in no:
             assert not strtobool(n)
 
-    def test_rfc822_escape(self):
-        header = 'I am a\npoor\nlonesome\nheader\n'
-        res = rfc822_escape(header)
-        wanted = ('I am a%(8s)spoor%(8s)slonesome%(8s)s' 'header%(8s)s') % {
-            '8s': '\n' + 8 * ' '
-        }
+    indent = 8 * ' '
+
+    @pytest.mark.parametrize(
+        "given,wanted",
+        [
+            # 0x0b, 0x0c, ..., etc are also considered a line break by Python
+            ("hello\x0b\nworld\n", f"hello\x0b{indent}\n{indent}world\n{indent}"),
+            ("hello\x1eworld", f"hello\x1e{indent}world"),
+            ("", ""),
+            (
+                "I am a\npoor\nlonesome\nheader\n",
+                f"I am a\n{indent}poor\n{indent}lonesome\n{indent}header\n{indent}",
+            ),
+        ],
+    )
+    def test_rfc822_escape(self, given, wanted):
+        """
+        We want to ensure a multi-line header parses correctly.
+
+        For interoperability, the escaped value should also "round-trip" over
+        `email.generator.Generator.flatten` and `email.message_from_*`
+        (see pypa/setuptools#4033).
+
+        The main issue is that internally `email.policy.EmailPolicy` uses
+        `splitlines` which will split on some control chars. If all the new lines
+        are not prefixed with spaces, the parser will interrupt reading
+        the current header and produce an incomplete value, while
+        incorrectly interpreting the rest of the headers as part of the payload.
+        """
+        res = rfc822_escape(given)
+
+        policy = email.policy.EmailPolicy(
+            utf8=True,
+            mangle_from_=False,
+            max_line_length=0,
+        )
+        with io.StringIO() as buffer:
+            raw = f"header: {res}\nother-header: 42\n\npayload\n"
+            orig = email.message_from_string(raw)
+            email.generator.Generator(buffer, policy=policy).flatten(orig)
+            buffer.seek(0)
+            regen = email.message_from_file(buffer)
+
+        for msg in (orig, regen):
+            assert msg.get_payload() == "payload\n"
+            assert msg["other-header"] == "42"
+            # Generator may replace control chars with `\n`
+            assert set(msg["header"].splitlines()) == set(res.splitlines())
+
         assert res == wanted
 
     def test_dont_write_bytecode(self):
@@ -205,6 +238,6 @@ def test_dont_write_bytecode(self):
 
     def test_grok_environment_error(self):
         # test obsolete function to ensure backward compat (#4931)
-        exc = IOError("Unable to find batch file")
+        exc = OSError("Unable to find batch file")
         msg = grok_environment_error(exc)
         assert msg == "error: Unable to find batch file"
diff --git a/setuptools/_distutils/tests/test_version.py b/setuptools/_distutils/tests/test_version.py
index ff52ea4683..b68f097724 100644
--- a/setuptools/_distutils/tests/test_version.py
+++ b/setuptools/_distutils/tests/test_version.py
@@ -1,9 +1,9 @@
 """Tests for distutils.version."""
-import pytest
 
 import distutils
-from distutils.version import LooseVersion
-from distutils.version import StrictVersion
+from distutils.version import LooseVersion, StrictVersion
+
+import pytest
 
 
 @pytest.fixture(autouse=True)
@@ -48,20 +48,14 @@ def test_cmp_strict(self):
                 if wanted is ValueError:
                     continue
                 else:
-                    raise AssertionError(
-                        ("cmp(%s, %s) " "shouldn't raise ValueError") % (v1, v2)
-                    )
-            assert res == wanted, 'cmp({}, {}) should be {}, got {}'.format(
-                v1, v2, wanted, res
-            )
+                    raise AssertionError(f"cmp({v1}, {v2}) shouldn't raise ValueError")
+            assert res == wanted, f'cmp({v1}, {v2}) should be {wanted}, got {res}'
             res = StrictVersion(v1)._cmp(v2)
-            assert res == wanted, 'cmp({}, {}) should be {}, got {}'.format(
-                v1, v2, wanted, res
-            )
+            assert res == wanted, f'cmp({v1}, {v2}) should be {wanted}, got {res}'
             res = StrictVersion(v1)._cmp(object())
-            assert (
-                res is NotImplemented
-            ), 'cmp({}, {}) should be NotImplemented, got {}'.format(v1, v2, res)
+            assert res is NotImplemented, (
+                f'cmp({v1}, {v2}) should be NotImplemented, got {res}'
+            )
 
     def test_cmp(self):
         versions = (
@@ -77,14 +71,10 @@ def test_cmp(self):
 
         for v1, v2, wanted in versions:
             res = LooseVersion(v1)._cmp(LooseVersion(v2))
-            assert res == wanted, 'cmp({}, {}) should be {}, got {}'.format(
-                v1, v2, wanted, res
-            )
+            assert res == wanted, f'cmp({v1}, {v2}) should be {wanted}, got {res}'
             res = LooseVersion(v1)._cmp(v2)
-            assert res == wanted, 'cmp({}, {}) should be {}, got {}'.format(
-                v1, v2, wanted, res
-            )
+            assert res == wanted, f'cmp({v1}, {v2}) should be {wanted}, got {res}'
             res = LooseVersion(v1)._cmp(object())
-            assert (
-                res is NotImplemented
-            ), 'cmp({}, {}) should be NotImplemented, got {}'.format(v1, v2, res)
+            assert res is NotImplemented, (
+                f'cmp({v1}, {v2}) should be NotImplemented, got {res}'
+            )
diff --git a/setuptools/_distutils/tests/unix_compat.py b/setuptools/_distutils/tests/unix_compat.py
index 95fc8eebe2..a5d9ee45cc 100644
--- a/setuptools/_distutils/tests/unix_compat.py
+++ b/setuptools/_distutils/tests/unix_compat.py
@@ -8,7 +8,6 @@
 
 import pytest
 
-
 UNIX_ID_SUPPORT = grp and pwd
 UID_0_SUPPORT = UNIX_ID_SUPPORT and sys.platform != "cygwin"
 
diff --git a/setuptools/_distutils/text_file.py b/setuptools/_distutils/text_file.py
index 36f947e51c..89d9048d59 100644
--- a/setuptools/_distutils/text_file.py
+++ b/setuptools/_distutils/text_file.py
@@ -97,7 +97,7 @@ def __init__(self, filename=None, file=None, **options):
         # sanity check client option hash
         for opt in options.keys():
             if opt not in self.default_options:
-                raise KeyError("invalid TextFile option '%s'" % opt)
+                raise KeyError(f"invalid TextFile option '{opt}'")
 
         if file is None:
             self.open(filename)
@@ -115,7 +115,7 @@ def open(self, filename):
         """Open a new file named 'filename'.  This overrides both the
         'filename' and 'file' arguments to the constructor."""
         self.filename = filename
-        self.file = open(self.filename, errors=self.errors)
+        self.file = open(self.filename, errors=self.errors, encoding='utf-8')
         self.current_line = 0
 
     def close(self):
@@ -133,9 +133,9 @@ def gen_error(self, msg, line=None):
             line = self.current_line
         outmsg.append(self.filename + ", ")
         if isinstance(line, (list, tuple)):
-            outmsg.append("lines %d-%d: " % tuple(line))
+            outmsg.append("lines {}-{}: ".format(*line))
         else:
-            outmsg.append("line %d: " % line)
+            outmsg.append(f"line {int(line)}: ")
         outmsg.append(str(msg))
         return "".join(outmsg)
 
@@ -220,7 +220,7 @@ def readline(self):  # noqa: C901
             if self.join_lines and buildup_line:
                 # oops: end of file
                 if line is None:
-                    self.warn("continuation line immediately precedes " "end-of-file")
+                    self.warn("continuation line immediately precedes end-of-file")
                     return buildup_line
 
                 if self.collapse_join:
diff --git a/setuptools/_distutils/unixccompiler.py b/setuptools/_distutils/unixccompiler.py
index 6ca2332ae1..20b8ce6b9b 100644
--- a/setuptools/_distutils/unixccompiler.py
+++ b/setuptools/_distutils/unixccompiler.py
@@ -1,400 +1,9 @@
-"""distutils.unixccompiler
+import importlib
 
-Contains the UnixCCompiler class, a subclass of CCompiler that handles
-the "typical" Unix-style command-line C compiler:
-  * macros defined with -Dname[=value]
-  * macros undefined with -Uname
-  * include search directories specified with -Idir
-  * libraries specified with -lllib
-  * library search directories specified with -Ldir
-  * compile handled by 'cc' (or similar) executable with -c option:
-    compiles .c to .o
-  * link static library handled by 'ar' command (possibly with 'ranlib')
-  * link shared library handled by 'cc -shared'
-"""
+from .compilers.C import unix
 
-import os
-import sys
-import re
-import shlex
-import itertools
+UnixCCompiler = unix.Compiler
 
-from . import sysconfig
-from .dep_util import newer
-from .ccompiler import CCompiler, gen_preprocess_options, gen_lib_options
-from .errors import DistutilsExecError, CompileError, LibError, LinkError
-from ._log import log
-from ._macos_compat import compiler_fixup
-
-# XXX Things not currently handled:
-#   * optimization/debug/warning flags; we just use whatever's in Python's
-#     Makefile and live with it.  Is this adequate?  If not, we might
-#     have to have a bunch of subclasses GNUCCompiler, SGICCompiler,
-#     SunCCompiler, and I suspect down that road lies madness.
-#   * even if we don't know a warning flag from an optimization flag,
-#     we need some way for outsiders to feed preprocessor/compiler/linker
-#     flags in to us -- eg. a sysadmin might want to mandate certain flags
-#     via a site config file, or a user might want to set something for
-#     compiling this module distribution only via the setup.py command
-#     line, whatever.  As long as these options come from something on the
-#     current system, they can be as system-dependent as they like, and we
-#     should just happily stuff them into the preprocessor/compiler/linker
-#     options and carry on.
-
-
-def _split_env(cmd):
-    """
-    For macOS, split command into 'env' portion (if any)
-    and the rest of the linker command.
-
-    >>> _split_env(['a', 'b', 'c'])
-    ([], ['a', 'b', 'c'])
-    >>> _split_env(['/usr/bin/env', 'A=3', 'gcc'])
-    (['/usr/bin/env', 'A=3'], ['gcc'])
-    """
-    pivot = 0
-    if os.path.basename(cmd[0]) == "env":
-        pivot = 1
-        while '=' in cmd[pivot]:
-            pivot += 1
-    return cmd[:pivot], cmd[pivot:]
-
-
-def _split_aix(cmd):
-    """
-    AIX platforms prefix the compiler with the ld_so_aix
-    script, so split that from the linker command.
-
-    >>> _split_aix(['a', 'b', 'c'])
-    ([], ['a', 'b', 'c'])
-    >>> _split_aix(['/bin/foo/ld_so_aix', 'gcc'])
-    (['/bin/foo/ld_so_aix'], ['gcc'])
-    """
-    pivot = os.path.basename(cmd[0]) == 'ld_so_aix'
-    return cmd[:pivot], cmd[pivot:]
-
-
-def _linker_params(linker_cmd, compiler_cmd):
-    """
-    The linker command usually begins with the compiler
-    command (possibly multiple elements), followed by zero or more
-    params for shared library building.
-
-    If the LDSHARED env variable overrides the linker command,
-    however, the commands may not match.
-
-    Return the best guess of the linker parameters by stripping
-    the linker command. If the compiler command does not
-    match the linker command, assume the linker command is
-    just the first element.
-
-    >>> _linker_params('gcc foo bar'.split(), ['gcc'])
-    ['foo', 'bar']
-    >>> _linker_params('gcc foo bar'.split(), ['other'])
-    ['foo', 'bar']
-    >>> _linker_params('ccache gcc foo bar'.split(), 'ccache gcc'.split())
-    ['foo', 'bar']
-    >>> _linker_params(['gcc'], ['gcc'])
-    []
-    """
-    c_len = len(compiler_cmd)
-    pivot = c_len if linker_cmd[:c_len] == compiler_cmd else 1
-    return linker_cmd[pivot:]
-
-
-class UnixCCompiler(CCompiler):
-    compiler_type = 'unix'
-
-    # These are used by CCompiler in two places: the constructor sets
-    # instance attributes 'preprocessor', 'compiler', etc. from them, and
-    # 'set_executable()' allows any of these to be set.  The defaults here
-    # are pretty generic; they will probably have to be set by an outsider
-    # (eg. using information discovered by the sysconfig about building
-    # Python extensions).
-    executables = {
-        'preprocessor': None,
-        'compiler': ["cc"],
-        'compiler_so': ["cc"],
-        'compiler_cxx': ["cc"],
-        'linker_so': ["cc", "-shared"],
-        'linker_exe': ["cc"],
-        'archiver': ["ar", "-cr"],
-        'ranlib': None,
-    }
-
-    if sys.platform[:6] == "darwin":
-        executables['ranlib'] = ["ranlib"]
-
-    # Needed for the filename generation methods provided by the base
-    # class, CCompiler.  NB. whoever instantiates/uses a particular
-    # UnixCCompiler instance should set 'shared_lib_ext' -- we set a
-    # reasonable common default here, but it's not necessarily used on all
-    # Unices!
-
-    src_extensions = [".c", ".C", ".cc", ".cxx", ".cpp", ".m"]
-    obj_extension = ".o"
-    static_lib_extension = ".a"
-    shared_lib_extension = ".so"
-    dylib_lib_extension = ".dylib"
-    xcode_stub_lib_extension = ".tbd"
-    static_lib_format = shared_lib_format = dylib_lib_format = "lib%s%s"
-    xcode_stub_lib_format = dylib_lib_format
-    if sys.platform == "cygwin":
-        exe_extension = ".exe"
-
-    def preprocess(
-        self,
-        source,
-        output_file=None,
-        macros=None,
-        include_dirs=None,
-        extra_preargs=None,
-        extra_postargs=None,
-    ):
-        fixed_args = self._fix_compile_args(None, macros, include_dirs)
-        ignore, macros, include_dirs = fixed_args
-        pp_opts = gen_preprocess_options(macros, include_dirs)
-        pp_args = self.preprocessor + pp_opts
-        if output_file:
-            pp_args.extend(['-o', output_file])
-        if extra_preargs:
-            pp_args[:0] = extra_preargs
-        if extra_postargs:
-            pp_args.extend(extra_postargs)
-        pp_args.append(source)
-
-        # reasons to preprocess:
-        # - force is indicated
-        # - output is directed to stdout
-        # - source file is newer than the target
-        preprocess = self.force or output_file is None or newer(source, output_file)
-        if not preprocess:
-            return
-
-        if output_file:
-            self.mkpath(os.path.dirname(output_file))
-
-        try:
-            self.spawn(pp_args)
-        except DistutilsExecError as msg:
-            raise CompileError(msg)
-
-    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
-        compiler_so = compiler_fixup(self.compiler_so, cc_args + extra_postargs)
-        try:
-            self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs)
-        except DistutilsExecError as msg:
-            raise CompileError(msg)
-
-    def create_static_lib(
-        self, objects, output_libname, output_dir=None, debug=0, target_lang=None
-    ):
-        objects, output_dir = self._fix_object_args(objects, output_dir)
-
-        output_filename = self.library_filename(output_libname, output_dir=output_dir)
-
-        if self._need_link(objects, output_filename):
-            self.mkpath(os.path.dirname(output_filename))
-            self.spawn(self.archiver + [output_filename] + objects + self.objects)
-
-            # Not many Unices required ranlib anymore -- SunOS 4.x is, I
-            # think the only major Unix that does.  Maybe we need some
-            # platform intelligence here to skip ranlib if it's not
-            # needed -- or maybe Python's configure script took care of
-            # it for us, hence the check for leading colon.
-            if self.ranlib:
-                try:
-                    self.spawn(self.ranlib + [output_filename])
-                except DistutilsExecError as msg:
-                    raise LibError(msg)
-        else:
-            log.debug("skipping %s (up-to-date)", output_filename)
-
-    def link(
-        self,
-        target_desc,
-        objects,
-        output_filename,
-        output_dir=None,
-        libraries=None,
-        library_dirs=None,
-        runtime_library_dirs=None,
-        export_symbols=None,
-        debug=0,
-        extra_preargs=None,
-        extra_postargs=None,
-        build_temp=None,
-        target_lang=None,
-    ):
-        objects, output_dir = self._fix_object_args(objects, output_dir)
-        fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
-        libraries, library_dirs, runtime_library_dirs = fixed_args
-
-        lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
-        if not isinstance(output_dir, (str, type(None))):
-            raise TypeError("'output_dir' must be a string or None")
-        if output_dir is not None:
-            output_filename = os.path.join(output_dir, output_filename)
-
-        if self._need_link(objects, output_filename):
-            ld_args = objects + self.objects + lib_opts + ['-o', output_filename]
-            if debug:
-                ld_args[:0] = ['-g']
-            if extra_preargs:
-                ld_args[:0] = extra_preargs
-            if extra_postargs:
-                ld_args.extend(extra_postargs)
-            self.mkpath(os.path.dirname(output_filename))
-            try:
-                # Select a linker based on context: linker_exe when
-                # building an executable or linker_so (with shared options)
-                # when building a shared library.
-                building_exe = target_desc == CCompiler.EXECUTABLE
-                linker = (self.linker_exe if building_exe else self.linker_so)[:]
-
-                if target_lang == "c++" and self.compiler_cxx:
-                    env, linker_ne = _split_env(linker)
-                    aix, linker_na = _split_aix(linker_ne)
-                    _, compiler_cxx_ne = _split_env(self.compiler_cxx)
-                    _, linker_exe_ne = _split_env(self.linker_exe)
-
-                    params = _linker_params(linker_na, linker_exe_ne)
-                    linker = env + aix + compiler_cxx_ne + params
-
-                linker = compiler_fixup(linker, ld_args)
-
-                self.spawn(linker + ld_args)
-            except DistutilsExecError as msg:
-                raise LinkError(msg)
-        else:
-            log.debug("skipping %s (up-to-date)", output_filename)
-
-    # -- Miscellaneous methods -----------------------------------------
-    # These are all used by the 'gen_lib_options() function, in
-    # ccompiler.py.
-
-    def library_dir_option(self, dir):
-        return "-L" + dir
-
-    def _is_gcc(self):
-        cc_var = sysconfig.get_config_var("CC")
-        compiler = os.path.basename(shlex.split(cc_var)[0])
-        return "gcc" in compiler or "g++" in compiler
-
-    def runtime_library_dir_option(self, dir):
-        # XXX Hackish, at the very least.  See Python bug #445902:
-        # http://sourceforge.net/tracker/index.php
-        #   ?func=detail&aid=445902&group_id=5470&atid=105470
-        # Linkers on different platforms need different options to
-        # specify that directories need to be added to the list of
-        # directories searched for dependencies when a dynamic library
-        # is sought.  GCC on GNU systems (Linux, FreeBSD, ...) has to
-        # be told to pass the -R option through to the linker, whereas
-        # other compilers and gcc on other systems just know this.
-        # Other compilers may need something slightly different.  At
-        # this time, there's no way to determine this information from
-        # the configuration data stored in the Python installation, so
-        # we use this hack.
-        if sys.platform[:6] == "darwin":
-            from distutils.util import get_macosx_target_ver, split_version
-
-            macosx_target_ver = get_macosx_target_ver()
-            if macosx_target_ver and split_version(macosx_target_ver) >= [10, 5]:
-                return "-Wl,-rpath," + dir
-            else:  # no support for -rpath on earlier macOS versions
-                return "-L" + dir
-        elif sys.platform[:7] == "freebsd":
-            return "-Wl,-rpath=" + dir
-        elif sys.platform[:5] == "hp-ux":
-            return [
-                "-Wl,+s" if self._is_gcc() else "+s",
-                "-L" + dir,
-            ]
-
-        # For all compilers, `-Wl` is the presumed way to
-        # pass a compiler option to the linker and `-R` is
-        # the way to pass an RPATH.
-        if sysconfig.get_config_var("GNULD") == "yes":
-            # GNU ld needs an extra option to get a RUNPATH
-            # instead of just an RPATH.
-            return "-Wl,--enable-new-dtags,-R" + dir
-        else:
-            return "-Wl,-R" + dir
-
-    def library_option(self, lib):
-        return "-l" + lib
-
-    @staticmethod
-    def _library_root(dir):
-        """
-        macOS users can specify an alternate SDK using'-isysroot'.
-        Calculate the SDK root if it is specified.
-
-        Note that, as of Xcode 7, Apple SDKs may contain textual stub
-        libraries with .tbd extensions rather than the normal .dylib
-        shared libraries installed in /.  The Apple compiler tool
-        chain handles this transparently but it can cause problems
-        for programs that are being built with an SDK and searching
-        for specific libraries.  Callers of find_library_file need to
-        keep in mind that the base filename of the returned SDK library
-        file might have a different extension from that of the library
-        file installed on the running system, for example:
-          /Applications/Xcode.app/Contents/Developer/Platforms/
-              MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/
-              usr/lib/libedit.tbd
-        vs
-          /usr/lib/libedit.dylib
-        """
-        cflags = sysconfig.get_config_var('CFLAGS')
-        match = re.search(r'-isysroot\s*(\S+)', cflags)
-
-        apply_root = (
-            sys.platform == 'darwin'
-            and match
-            and (
-                dir.startswith('/System/')
-                or (dir.startswith('/usr/') and not dir.startswith('/usr/local/'))
-            )
-        )
-
-        return os.path.join(match.group(1), dir[1:]) if apply_root else dir
-
-    def find_library_file(self, dirs, lib, debug=0):
-        r"""
-        Second-guess the linker with not much hard
-        data to go on: GCC seems to prefer the shared library, so
-        assume that *all* Unix C compilers do,
-        ignoring even GCC's "-static" option.
-
-        >>> compiler = UnixCCompiler()
-        >>> compiler._library_root = lambda dir: dir
-        >>> monkeypatch = getfixture('monkeypatch')
-        >>> monkeypatch.setattr(os.path, 'exists', lambda d: 'existing' in d)
-        >>> dirs = ('/foo/bar/missing', '/foo/bar/existing')
-        >>> compiler.find_library_file(dirs, 'abc').replace('\\', '/')
-        '/foo/bar/existing/libabc.dylib'
-        >>> compiler.find_library_file(reversed(dirs), 'abc').replace('\\', '/')
-        '/foo/bar/existing/libabc.dylib'
-        >>> monkeypatch.setattr(os.path, 'exists',
-        ...     lambda d: 'existing' in d and '.a' in d)
-        >>> compiler.find_library_file(dirs, 'abc').replace('\\', '/')
-        '/foo/bar/existing/libabc.a'
-        >>> compiler.find_library_file(reversed(dirs), 'abc').replace('\\', '/')
-        '/foo/bar/existing/libabc.a'
-        """
-        lib_names = (
-            self.library_filename(lib, lib_type=type)
-            for type in 'dylib xcode_stub shared static'.split()
-        )
-
-        roots = map(self._library_root, dirs)
-
-        searched = (
-            os.path.join(root, lib_name)
-            for root, lib_name in itertools.product(roots, lib_names)
-        )
-
-        found = filter(os.path.exists, searched)
-
-        # Return None if it could not be found in any dir.
-        return next(found, None)
+# ensure import of unixccompiler implies ccompiler imported
+# (pypa/setuptools#4871)
+importlib.import_module('distutils.ccompiler')
diff --git a/setuptools/_distutils/util.py b/setuptools/_distutils/util.py
index 7ef47176e2..47bb5af5e4 100644
--- a/setuptools/_distutils/util.py
+++ b/setuptools/_distutils/util.py
@@ -4,22 +4,35 @@
 one of the other *util.py modules.
 """
 
+from __future__ import annotations
+
+import functools
 import importlib.util
 import os
+import pathlib
 import re
 import string
 import subprocess
 import sys
 import sysconfig
-import functools
+import tempfile
+from collections.abc import Callable, Iterable, Mapping
+from typing import TYPE_CHECKING, AnyStr
+
+from jaraco.functools import pass_none
 
-from .errors import DistutilsPlatformError, DistutilsByteCompileError
-from .dep_util import newer
-from .spawn import spawn
 from ._log import log
+from ._modified import newer
+from .errors import DistutilsByteCompileError, DistutilsPlatformError
+from .spawn import spawn
+
+if TYPE_CHECKING:
+    from typing_extensions import TypeVarTuple, Unpack
+
+    _Ts = TypeVarTuple("_Ts")
 
 
-def get_host_platform():
+def get_host_platform() -> str:
     """
     Return a string that identifies the current platform. Use this
     function to distinguish platform-specific build directories and
@@ -28,27 +41,12 @@ def get_host_platform():
 
     # This function initially exposed platforms as defined in Python 3.9
     # even with older Python versions when distutils was split out.
-    # Now it delegates to stdlib sysconfig, but maintains compatibility.
-
-    if sys.version_info < (3, 8):
-        if os.name == 'nt':
-            if '(arm)' in sys.version.lower():
-                return 'win-arm32'
-            if '(arm64)' in sys.version.lower():
-                return 'win-arm64'
-
-    if sys.version_info < (3, 9):
-        if os.name == "posix" and hasattr(os, 'uname'):
-            osname, host, release, version, machine = os.uname()
-            if osname[:3] == "aix":
-                from .py38compat import aix_platform
-
-                return aix_platform(osname, version, release)
+    # Now it delegates to stdlib sysconfig.
 
     return sysconfig.get_platform()
 
 
-def get_platform():
+def get_platform() -> str:
     if os.name == 'nt':
         TARGET_TO_PLAT = {
             'x86': 'win32',
@@ -109,49 +107,41 @@ def get_macosx_target_ver():
         ):
             my_msg = (
                 '$' + MACOSX_VERSION_VAR + ' mismatch: '
-                'now "%s" but "%s" during configure; '
-                'must use 10.3 or later' % (env_ver, syscfg_ver)
+                f'now "{env_ver}" but "{syscfg_ver}" during configure; '
+                'must use 10.3 or later'
             )
             raise DistutilsPlatformError(my_msg)
         return env_ver
     return syscfg_ver
 
 
-def split_version(s):
+def split_version(s: str) -> list[int]:
     """Convert a dot-separated string into a list of numbers for comparisons"""
     return [int(n) for n in s.split('.')]
 
 
-def convert_path(pathname):
-    """Return 'pathname' as a name that will work on the native filesystem,
-    i.e. split it on '/' and put it back together again using the current
-    directory separator.  Needed because filenames in the setup script are
-    always supplied in Unix style, and have to be converted to the local
-    convention before we can actually use them in the filesystem.  Raises
-    ValueError on non-Unix-ish systems if 'pathname' either starts or
-    ends with a slash.
-    """
-    if os.sep == '/':
-        return pathname
-    if not pathname:
-        return pathname
-    if pathname[0] == '/':
-        raise ValueError("path '%s' cannot be absolute" % pathname)
-    if pathname[-1] == '/':
-        raise ValueError("path '%s' cannot end with '/'" % pathname)
+@pass_none
+def convert_path(pathname: str | os.PathLike[str]) -> str:
+    r"""
+    Allow for pathlib.Path inputs, coax to a native path string.
 
-    paths = pathname.split('/')
-    while '.' in paths:
-        paths.remove('.')
-    if not paths:
-        return os.curdir
-    return os.path.join(*paths)
+    If None is passed, will just pass it through as
+    Setuptools relies on this behavior.
 
+    >>> convert_path(None) is None
+    True
 
-# convert_path ()
+    Removes empty paths.
+
+    >>> convert_path('foo/./bar').replace('\\', '/')
+    'foo/bar'
+    """
+    return os.fspath(pathlib.PurePath(pathname))
 
 
-def change_root(new_root, pathname):
+def change_root(
+    new_root: AnyStr | os.PathLike[AnyStr], pathname: AnyStr | os.PathLike[AnyStr]
+) -> AnyStr:
     """Return 'pathname' with 'new_root' prepended.  If 'pathname' is
     relative, this is equivalent to "os.path.join(new_root,pathname)".
     Otherwise, it requires making 'pathname' relative and then joining the
@@ -165,15 +155,15 @@ def change_root(new_root, pathname):
 
     elif os.name == 'nt':
         (drive, path) = os.path.splitdrive(pathname)
-        if path[0] == '\\':
+        if path[0] == os.sep:
             path = path[1:]
         return os.path.join(new_root, path)
 
     raise DistutilsPlatformError(f"nothing known about platform '{os.name}'")
 
 
-@functools.lru_cache()
-def check_environ():
+@functools.lru_cache
+def check_environ() -> None:
     """Ensure that 'os.environ' has all the environment variables we
     guarantee that users can use in config files, command-line options,
     etc.  Currently this includes:
@@ -195,7 +185,7 @@ def check_environ():
         os.environ['PLAT'] = get_platform()
 
 
-def subst_vars(s, local_vars):
+def subst_vars(s, local_vars: Mapping[str, object]) -> str:
     """
     Perform variable substitution on 'string'.
     Variables are indicated by format-style braces ("{var}").
@@ -234,7 +224,7 @@ def _subst(match):
     return repl
 
 
-def grok_environment_error(exc, prefix="error: "):
+def grok_environment_error(exc: object, prefix: str = "error: ") -> str:
     # Function kept for backward compatibility.
     # Used to try clever things with EnvironmentErrors,
     # but nowadays str(exception) produces good messages.
@@ -247,12 +237,12 @@ def grok_environment_error(exc, prefix="error: "):
 
 def _init_regex():
     global _wordchars_re, _squote_re, _dquote_re
-    _wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
+    _wordchars_re = re.compile(rf'[^\\\'\"{string.whitespace} ]*')
     _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
     _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
 
 
-def split_quoted(s):
+def split_quoted(s: str) -> list[str]:
     """Split a string up according to Unix shell-like rules for quotes and
     backslashes.  In short: words are delimited by spaces, as long as those
     spaces are not escaped by a backslash, or inside a quoted string.
@@ -299,10 +289,10 @@ def split_quoted(s):
             elif s[end] == '"':  # slurp doubly-quoted string
                 m = _dquote_re.match(s, end)
             else:
-                raise RuntimeError("this can't happen (bad char '%c')" % s[end])
+                raise RuntimeError(f"this can't happen (bad char '{s[end]}')")
 
             if m is None:
-                raise ValueError("bad string (mismatched %s quotes?)" % s[end])
+                raise ValueError(f"bad string (mismatched {s[end]} quotes?)")
 
             (beg, end) = m.span()
             s = s[:beg] + s[beg + 1 : end - 1] + s[end:]
@@ -318,26 +308,27 @@ def split_quoted(s):
 # split_quoted ()
 
 
-def execute(func, args, msg=None, verbose=0, dry_run=0):
-    """Perform some action that affects the outside world (eg.  by
-    writing to the filesystem).  Such actions are special because they
-    are disabled by the 'dry_run' flag.  This method takes care of all
-    that bureaucracy for you; all you have to do is supply the
-    function to call and an argument tuple for it (to embody the
-    "external action" being performed), and an optional message to
-    print.
+def execute(
+    func: Callable[[Unpack[_Ts]], object],
+    args: tuple[Unpack[_Ts]],
+    msg: object = None,
+    verbose: bool = False,
+) -> None:
+    """
+    Perform some action that affects the outside world (e.g. by
+    writing to the filesystem). Was previously used to deal with
+    "dry run" operations, but now runs unconditionally.
     """
     if msg is None:
-        msg = "{}{!r}".format(func.__name__, args)
+        msg = f"{func.__name__}{args!r}"
         if msg[-2:] == ',)':  # correct for singleton tuple
             msg = msg[0:-2] + ')'
 
     log.info(msg)
-    if not dry_run:
-        func(*args)
+    func(*args)
 
 
-def strtobool(val):
+def strtobool(val: str) -> bool:
     """Convert a string representation of truth to true (1) or false (0).
 
     True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
@@ -346,23 +337,22 @@ def strtobool(val):
     """
     val = val.lower()
     if val in ('y', 'yes', 't', 'true', 'on', '1'):
-        return 1
+        return True
     elif val in ('n', 'no', 'f', 'false', 'off', '0'):
-        return 0
+        return False
     else:
-        raise ValueError("invalid truth value {!r}".format(val))
+        raise ValueError(f"invalid truth value {val!r}")
 
 
 def byte_compile(  # noqa: C901
-    py_files,
-    optimize=0,
-    force=0,
-    prefix=None,
-    base_dir=None,
-    verbose=1,
-    dry_run=0,
-    direct=None,
-):
+    py_files: Iterable[str],
+    optimize: int = 0,
+    force: bool = False,
+    prefix: str | None = None,
+    base_dir: str | None = None,
+    verbose: bool = True,
+    direct: bool | None = None,
+) -> None:
     """Byte-compile a collection of Python source files to .pyc
     files in a __pycache__ subdirectory.  'py_files' is a list
     of files to compile; any files that don't end in ".py" are silently
@@ -380,9 +370,6 @@ def byte_compile(  # noqa: C901
     prepended (after 'prefix' is stripped).  You can supply either or both
     (or neither) of 'prefix' and 'base_dir', as you wish.
 
-    If 'dry_run' is true, doesn't actually do anything that would
-    affect the filesystem.
-
     Byte-compilation is either done directly in this interpreter process
     with the standard py_compile module, or indirectly by writing a
     temporary script and executing it.  Normally, you should let
@@ -412,55 +399,43 @@ def byte_compile(  # noqa: C901
     # "Indirect" byte-compilation: write a temporary script and then
     # run it with the appropriate flags.
     if not direct:
-        try:
-            from tempfile import mkstemp
-
-            (script_fd, script_name) = mkstemp(".py")
-        except ImportError:
-            from tempfile import mktemp
-
-            (script_fd, script_name) = None, mktemp(".py")
+        (script_fd, script_name) = tempfile.mkstemp(".py")
         log.info("writing byte-compilation script '%s'", script_name)
-        if not dry_run:
-            if script_fd is not None:
-                script = os.fdopen(script_fd, "w")
-            else:
-                script = open(script_name, "w")
+        script = os.fdopen(script_fd, "w", encoding='utf-8')
 
-            with script:
-                script.write(
-                    """\
+        with script:
+            script.write(
+                """\
 from distutils.util import byte_compile
 files = [
 """
-                )
-
-                # XXX would be nice to write absolute filenames, just for
-                # safety's sake (script should be more robust in the face of
-                # chdir'ing before running it).  But this requires abspath'ing
-                # 'prefix' as well, and that breaks the hack in build_lib's
-                # 'byte_compile()' method that carefully tacks on a trailing
-                # slash (os.sep really) to make sure the prefix here is "just
-                # right".  This whole prefix business is rather delicate -- the
-                # problem is that it's really a directory, but I'm treating it
-                # as a dumb string, so trailing slashes and so forth matter.
-
-                script.write(",\n".join(map(repr, py_files)) + "]\n")
-                script.write(
-                    """
-byte_compile(files, optimize=%r, force=%r,
-             prefix=%r, base_dir=%r,
-             verbose=%r, dry_run=0,
-             direct=1)
+            )
+
+            # XXX would be nice to write absolute filenames, just for
+            # safety's sake (script should be more robust in the face of
+            # chdir'ing before running it).  But this requires abspath'ing
+            # 'prefix' as well, and that breaks the hack in build_lib's
+            # 'byte_compile()' method that carefully tacks on a trailing
+            # slash (os.sep really) to make sure the prefix here is "just
+            # right".  This whole prefix business is rather delicate -- the
+            # problem is that it's really a directory, but I'm treating it
+            # as a dumb string, so trailing slashes and so forth matter.
+
+            script.write(",\n".join(map(repr, py_files)) + "]\n")
+            script.write(
+                f"""
+byte_compile(files, optimize={optimize!r}, force={force!r},
+         prefix={prefix!r}, base_dir={base_dir!r},
+         verbose={verbose!r},
+         direct=True)
 """
-                    % (optimize, force, prefix, base_dir, verbose)
-                )
+            )
 
         cmd = [sys.executable]
         cmd.extend(subprocess._optim_args_from_interpreter_flags())
         cmd.append(script_name)
-        spawn(cmd, dry_run=dry_run)
-        execute(os.remove, (script_name,), "removing %s" % script_name, dry_run=dry_run)
+        spawn(cmd)
+        execute(os.remove, (script_name,), f"removing {script_name}")
 
     # "Direct" byte-compilation: use the py_compile module to compile
     # right here, right now.  Note that the script generated in indirect
@@ -487,8 +462,7 @@ def byte_compile(  # noqa: C901
             if prefix:
                 if file[: len(prefix)] != prefix:
                     raise ValueError(
-                        "invalid prefix: filename %r doesn't start with %r"
-                        % (file, prefix)
+                        f"invalid prefix: filename {file!r} doesn't start with {prefix!r}"
                     )
                 dfile = dfile[len(prefix) :]
             if base_dir:
@@ -498,16 +472,35 @@ def byte_compile(  # noqa: C901
             if direct:
                 if force or newer(file, cfile):
                     log.info("byte-compiling %s to %s", file, cfile_base)
-                    if not dry_run:
-                        compile(file, cfile, dfile)
+                    compile(file, cfile, dfile)
                 else:
                     log.debug("skipping byte-compilation of %s to %s", file, cfile_base)
 
 
-def rfc822_escape(header):
+def rfc822_escape(header: str) -> str:
     """Return a version of the string escaped for inclusion in an
     RFC-822 header, by ensuring there are 8 spaces space after each newline.
     """
-    lines = header.split('\n')
-    sep = '\n' + 8 * ' '
-    return sep.join(lines)
+    indent = 8 * " "
+    lines = header.splitlines(keepends=True)
+
+    # Emulate the behaviour of `str.split`
+    # (the terminal line break in `splitlines` does not result in an extra line):
+    ends_in_newline = lines and lines[-1].splitlines()[0] != lines[-1]
+    suffix = indent if ends_in_newline else ""
+
+    return indent.join(lines) + suffix
+
+
+def is_mingw() -> bool:
+    """Returns True if the current platform is mingw.
+
+    Python compiled with Mingw-w64 has sys.platform == 'win32' and
+    get_platform() starts with 'mingw'.
+    """
+    return sys.platform == 'win32' and get_platform().startswith('mingw')
+
+
+def is_freethreaded():
+    """Return True if the Python interpreter is built with free threading support."""
+    return bool(sysconfig.get_config_var('Py_GIL_DISABLED'))
diff --git a/setuptools/_distutils/version.py b/setuptools/_distutils/version.py
index 74c40d7bfd..2223ee9c8c 100644
--- a/setuptools/_distutils/version.py
+++ b/setuptools/_distutils/version.py
@@ -26,9 +26,9 @@
     of the same class, thus must follow the same rules)
 """
 
+import contextlib
 import re
 import warnings
-import contextlib
 
 
 @contextlib.contextmanager
@@ -53,14 +53,13 @@ def __init__(self, vstring=None):
         if vstring:
             self.parse(vstring)
         warnings.warn(
-            "distutils Version classes are deprecated. "
-            "Use packaging.version instead.",
+            "distutils Version classes are deprecated. Use packaging.version instead.",
             DeprecationWarning,
             stacklevel=2,
         )
 
     def __repr__(self):
-        return "{} ('{}')".format(self.__class__.__name__, str(self))
+        return f"{self.__class__.__name__} ('{self}')"
 
     def __eq__(self, other):
         c = self._cmp(other)
@@ -111,7 +110,6 @@ def __ge__(self, other):
 
 
 class StrictVersion(Version):
-
     """Version numbering for anal retentives and software idealists.
     Implements the standard interface for version number classes as
     described above.  A version number consists of two or three
@@ -154,7 +152,7 @@ class StrictVersion(Version):
     def parse(self, vstring):
         match = self.version_re.match(vstring)
         if not match:
-            raise ValueError("invalid version number '%s'" % vstring)
+            raise ValueError(f"invalid version number '{vstring}'")
 
         (major, minor, patch, prerelease, prerelease_num) = match.group(1, 2, 4, 5, 6)
 
@@ -179,42 +177,36 @@ def __str__(self):
 
         return vstring
 
-    def _cmp(self, other):  # noqa: C901
+    def _cmp(self, other):
         if isinstance(other, str):
             with suppress_known_deprecation():
                 other = StrictVersion(other)
         elif not isinstance(other, StrictVersion):
             return NotImplemented
 
-        if self.version != other.version:
-            # numeric versions don't match
-            # prerelease stuff doesn't matter
-            if self.version < other.version:
-                return -1
-            else:
-                return 1
-
-        # have to compare prerelease
-        # case 1: neither has prerelease; they're equal
-        # case 2: self has prerelease, other doesn't; other is greater
-        # case 3: self doesn't have prerelease, other does: self is greater
-        # case 4: both have prerelease: must compare them!
-
-        if not self.prerelease and not other.prerelease:
-            return 0
-        elif self.prerelease and not other.prerelease:
+        if self.version == other.version:
+            # versions match; pre-release drives the comparison
+            return self._cmp_prerelease(other)
+
+        return -1 if self.version < other.version else 1
+
+    def _cmp_prerelease(self, other):
+        """
+        case 1: self has prerelease, other doesn't; other is greater
+        case 2: self doesn't have prerelease, other does: self is greater
+        case 3: both or neither have prerelease: compare them!
+        """
+        if self.prerelease and not other.prerelease:
             return -1
         elif not self.prerelease and other.prerelease:
             return 1
-        elif self.prerelease and other.prerelease:
-            if self.prerelease == other.prerelease:
-                return 0
-            elif self.prerelease < other.prerelease:
-                return -1
-            else:
-                return 1
+
+        if self.prerelease == other.prerelease:
+            return 0
+        elif self.prerelease < other.prerelease:
+            return -1
         else:
-            assert False, "never get here"
+            return 1
 
 
 # end class StrictVersion
@@ -286,7 +278,6 @@ def _cmp(self, other):  # noqa: C901
 
 
 class LooseVersion(Version):
-
     """Version numbering for anarchists and software realists.
     Implements the standard interface for version number classes as
     described above.  A version number consists of a series of numbers,
@@ -338,7 +329,7 @@ def __str__(self):
         return self.vstring
 
     def __repr__(self):
-        return "LooseVersion ('%s')" % str(self)
+        return f"LooseVersion ('{self}')"
 
     def _cmp(self, other):
         if isinstance(other, str):
diff --git a/setuptools/_distutils/versionpredicate.py b/setuptools/_distutils/versionpredicate.py
index d6c0c007aa..fe31b0ed8e 100644
--- a/setuptools/_distutils/versionpredicate.py
+++ b/setuptools/_distutils/versionpredicate.py
@@ -1,9 +1,9 @@
-"""Module for parsing and testing package version predicate strings.
-"""
-import re
-from . import version
+"""Module for parsing and testing package version predicate strings."""
+
 import operator
+import re
 
+from . import version
 
 re_validPackage = re.compile(r"(?i)^\s*([a-z_]\w*(?:\.[a-z_]\w*)*)(.*)", re.ASCII)
 # (package) (rest)
@@ -20,7 +20,7 @@ def splitUp(pred):
     """
     res = re_splitComparison.match(pred)
     if not res:
-        raise ValueError("bad package restriction syntax: %r" % pred)
+        raise ValueError(f"bad package restriction syntax: {pred!r}")
     comp, verStr = res.groups()
     with version.suppress_known_deprecation():
         other = version.StrictVersion(verStr)
@@ -113,17 +113,17 @@ def __init__(self, versionPredicateStr):
             raise ValueError("empty package restriction")
         match = re_validPackage.match(versionPredicateStr)
         if not match:
-            raise ValueError("bad package name in %r" % versionPredicateStr)
+            raise ValueError(f"bad package name in {versionPredicateStr!r}")
         self.name, paren = match.groups()
         paren = paren.strip()
         if paren:
             match = re_paren.match(paren)
             if not match:
-                raise ValueError("expected parenthesized list: %r" % paren)
+                raise ValueError(f"expected parenthesized list: {paren!r}")
             str = match.groups()[0]
             self.pred = [splitUp(aPred) for aPred in str.split(",")]
             if not self.pred:
-                raise ValueError("empty parenthesized list in %r" % versionPredicateStr)
+                raise ValueError(f"empty parenthesized list in {versionPredicateStr!r}")
         else:
             self.pred = []
 
@@ -167,7 +167,7 @@ def split_provision(value):
     value = value.strip()
     m = _provision_rx.match(value)
     if not m:
-        raise ValueError("illegal provides specification: %r" % value)
+        raise ValueError(f"illegal provides specification: {value!r}")
     ver = m.group(2) or None
     if ver:
         with version.suppress_known_deprecation():
diff --git a/setuptools/_distutils/zosccompiler.py b/setuptools/_distutils/zosccompiler.py
new file mode 100644
index 0000000000..e49630ac6e
--- /dev/null
+++ b/setuptools/_distutils/zosccompiler.py
@@ -0,0 +1,3 @@
+from .compilers.C import zos
+
+zOSCCompiler = zos.Compiler
diff --git a/setuptools/_entry_points.py b/setuptools/_entry_points.py
index 747a69067e..cd5dd2c8ac 100644
--- a/setuptools/_entry_points.py
+++ b/setuptools/_entry_points.py
@@ -1,23 +1,29 @@
 import functools
-import operator
 import itertools
+import operator
+
+from jaraco.functools import pass_none
+from jaraco.text import yield_lines
+from more_itertools import consume
 
-from .errors import OptionError
-from .extern.jaraco.text import yield_lines
-from .extern.jaraco.functools import pass_none
 from ._importlib import metadata
 from ._itertools import ensure_unique
-from .extern.more_itertools import consume
+from .errors import OptionError
 
 
 def ensure_valid(ep):
     """
     Exercise one of the dynamic properties to trigger
     the pattern match.
+
+    This function is deprecated in favor of importlib_metadata 8.7 and
+    Python 3.14 importlib.metadata, which validates entry points on
+    construction.
     """
     try:
         ep.extras
-    except AttributeError as ex:
+    except (AttributeError, AssertionError) as ex:
+        # Why both? See https://github.com/python/importlib_metadata/issues/488
         msg = (
             f"Problems to parse {ep}.\nPlease ensure entry-point follows the spec: "
             "https://packaging.python.org/en/latest/specifications/entry-points/"
diff --git a/setuptools/_imp.py b/setuptools/_imp.py
index 9d4ead0eb0..f1d9f29218 100644
--- a/setuptools/_imp.py
+++ b/setuptools/_imp.py
@@ -3,13 +3,12 @@
 from the deprecated imp module.
 """
 
-import os
-import importlib.util
 import importlib.machinery
-
+import importlib.util
+import os
+import tokenize
 from importlib.util import module_from_spec
 
-
 PY_SOURCE = 1
 PY_COMPILED = 2
 C_EXTENSION = 3
@@ -30,7 +29,7 @@ def find_module(module, paths=None):
     """Just like 'imp.find_module()', but with package support"""
     spec = find_spec(module, paths)
     if spec is None:
-        raise ImportError("Can't find %s" % module)
+        raise ImportError(f"Can't find {module}")
     if not spec.has_location and hasattr(spec, 'submodule_search_locations'):
         spec = importlib.util.spec_from_loader('__init__.py', spec.loader)
 
@@ -60,13 +59,13 @@ def find_module(module, paths=None):
 
         if suffix in importlib.machinery.SOURCE_SUFFIXES:
             kind = PY_SOURCE
+            file = tokenize.open(path)
         elif suffix in importlib.machinery.BYTECODE_SUFFIXES:
             kind = PY_COMPILED
+            file = open(path, 'rb')
         elif suffix in importlib.machinery.EXTENSION_SUFFIXES:
             kind = C_EXTENSION
 
-        if kind in {PY_SOURCE, PY_COMPILED}:
-            file = open(path, mode)
     else:
         path = None
         suffix = mode = ''
@@ -77,12 +76,12 @@ def find_module(module, paths=None):
 def get_frozen_object(module, paths=None):
     spec = find_spec(module, paths)
     if not spec:
-        raise ImportError("Can't find %s" % module)
+        raise ImportError(f"Can't find {module}")
     return spec.loader.get_code(module)
 
 
 def get_module(module, paths, info):
     spec = find_spec(module, paths)
     if not spec:
-        raise ImportError("Can't find %s" % module)
+        raise ImportError(f"Can't find {module}")
     return module_from_spec(spec)
diff --git a/setuptools/_importlib.py b/setuptools/_importlib.py
index bd2b01e2b5..2b27bc10cd 100644
--- a/setuptools/_importlib.py
+++ b/setuptools/_importlib.py
@@ -1,51 +1,2 @@
-import sys
-
-
-def disable_importlib_metadata_finder(metadata):
-    """
-    Ensure importlib_metadata doesn't provide older, incompatible
-    Distributions.
-
-    Workaround for #3102.
-    """
-    try:
-        import importlib_metadata
-    except ImportError:
-        return
-    except AttributeError:
-        from .warnings import SetuptoolsWarning
-
-        SetuptoolsWarning.emit(
-            "Incompatibility problem.",
-            """
-            `importlib-metadata` version is incompatible with `setuptools`.
-            This problem is likely to be solved by installing an updated version of
-            `importlib-metadata`.
-            """,
-            see_url="https://github.com/python/importlib_metadata/issues/396",
-        )  # Ensure a descriptive message is shown.
-        raise  # This exception can be suppressed by _distutils_hack
-
-    if importlib_metadata is metadata:
-        return
-    to_remove = [
-        ob
-        for ob in sys.meta_path
-        if isinstance(ob, importlib_metadata.MetadataPathFinder)
-    ]
-    for item in to_remove:
-        sys.meta_path.remove(item)
-
-
-if sys.version_info < (3, 10):
-    from setuptools.extern import importlib_metadata as metadata
-
-    disable_importlib_metadata_finder(metadata)
-else:
-    import importlib.metadata as metadata  # noqa: F401
-
-
-if sys.version_info < (3, 9):
-    from setuptools.extern import importlib_resources as resources
-else:
-    import importlib.resources as resources  # noqa: F401
+import importlib.metadata as metadata  # noqa: F401
+import importlib.resources as resources  # noqa: F401
diff --git a/setuptools/_itertools.py b/setuptools/_itertools.py
index b8bf6d210a..d6ca841353 100644
--- a/setuptools/_itertools.py
+++ b/setuptools/_itertools.py
@@ -1,4 +1,4 @@
-from setuptools.extern.more_itertools import consume  # noqa: F401
+from more_itertools import consume  # noqa: F401
 
 
 # copied from jaraco.itertools 6.1
diff --git a/setuptools/_normalization.py b/setuptools/_normalization.py
index 3e94e662ef..6b8d4ddbf9 100644
--- a/setuptools/_normalization.py
+++ b/setuptools/_normalization.py
@@ -2,19 +2,19 @@
 Helpers for normalization as expected in wheel/sdist/module file names
 and core metadata
 """
-import re
-from pathlib import Path
-from typing import Union
 
-from .extern import packaging
-from .warnings import SetuptoolsDeprecationWarning
+import re
+from typing import TYPE_CHECKING
 
-_Path = Union[str, Path]
+import packaging
 
 # https://packaging.python.org/en/latest/specifications/core-metadata/#name
-_VALID_NAME = re.compile(r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.I)
-_UNSAFE_NAME_CHARS = re.compile(r"[^A-Z0-9.]+", re.I)
-_NON_ALPHANUMERIC = re.compile(r"[^A-Z0-9]+", re.I)
+_VALID_NAME = re.compile(r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.IGNORECASE)
+_UNSAFE_NAME_CHARS = re.compile(r"[^A-Z0-9._-]+", re.IGNORECASE)
+_NON_ALPHANUMERIC = re.compile(r"[^A-Z0-9]+", re.IGNORECASE)
+_PEP440_FALLBACK = re.compile(
+    r"^v?(?P(?:[0-9]+!)?[0-9]+(?:\.[0-9]+)*)", re.IGNORECASE
+)
 
 
 def safe_identifier(name: str) -> str:
@@ -35,13 +35,16 @@ def safe_name(component: str) -> str:
     'hello-world'
     >>> safe_name("hello?world")
     'hello-world'
+    >>> safe_name("hello_world")
+    'hello_world'
     """
-    # See pkg_resources.safe_name
     return _UNSAFE_NAME_CHARS.sub("-", component)
 
 
 def safe_version(version: str) -> str:
     """Convert an arbitrary string into a valid version string.
+    Can still raise an ``InvalidVersion`` exception.
+    To avoid exceptions use ``best_effort_version``.
     >>> safe_version("1988 12 25")
     '1988.12.25'
     >>> safe_version("v0.2.1")
@@ -53,7 +56,7 @@ def safe_version(version: str) -> str:
     >>> safe_version("ubuntu lts")
     Traceback (most recent call last):
     ...
-    setuptools.extern.packaging.version.InvalidVersion: Invalid version: 'ubuntu.lts'
+    packaging.version.InvalidVersion: Invalid version: 'ubuntu.lts'
     """
     v = version.replace(' ', '.')
     try:
@@ -65,32 +68,34 @@ def safe_version(version: str) -> str:
 
 def best_effort_version(version: str) -> str:
     """Convert an arbitrary string into a version-like string.
+    Fallback when ``safe_version`` is not safe enough.
     >>> best_effort_version("v0.2 beta")
     '0.2b0'
-
-    >>> import warnings
-    >>> warnings.simplefilter("ignore", category=SetuptoolsDeprecationWarning)
     >>> best_effort_version("ubuntu lts")
-    'ubuntu.lts'
+    '0.dev0+sanitized.ubuntu.lts'
+    >>> best_effort_version("0.23ubuntu1")
+    '0.23.dev0+sanitized.ubuntu1'
+    >>> best_effort_version("0.23-")
+    '0.23.dev0+sanitized'
+    >>> best_effort_version("0.-_")
+    '0.dev0+sanitized'
+    >>> best_effort_version("42.+?1")
+    '42.dev0+sanitized.1'
     """
-    # See pkg_resources.safe_version
     try:
         return safe_version(version)
     except packaging.version.InvalidVersion:
-        SetuptoolsDeprecationWarning.emit(
-            f"Invalid version: {version!r}.",
-            f"""
-            Version {version!r} is not valid according to PEP 440.
-
-            Please make sure to specify a valid version for your package.
-            Also note that future releases of setuptools may halt the build process
-            if an invalid version is given.
-            """,
-            see_url="https://peps.python.org/pep-0440/",
-            due_date=(2023, 9, 26),  # See setuptools/dist _validate_version
-        )
         v = version.replace(' ', '.')
-        return safe_name(v)
+        match = _PEP440_FALLBACK.search(v)
+        if match:
+            safe = match["safe"]
+            rest = v[len(safe) :]
+        else:
+            safe = "0"
+            rest = version
+        safe_rest = _NON_ALPHANUMERIC.sub(".", rest).strip(".")
+        local = f"sanitized.{safe_rest}".strip(".")
+        return safe_version(f"{safe}.dev0+{local}")
 
 
 def safe_extra(extra: str) -> str:
@@ -112,10 +117,32 @@ def filename_component(value: str) -> str:
     return value.replace("-", "_").strip("_")
 
 
+def filename_component_broken(value: str) -> str:
+    """
+    Produce the incorrect filename component for compatibility.
+
+    See pypa/setuptools#4167 for detailed analysis.
+
+    TODO: replace this with filename_component after pip 24 is
+    nearly-ubiquitous.
+
+    >>> filename_component_broken('foo_bar-baz')
+    'foo-bar-baz'
+    """
+    return value.replace('_', '-')
+
+
 def safer_name(value: str) -> str:
     """Like ``safe_name`` but can be used as filename component for wheel"""
     # See bdist_wheel.safer_name
-    return filename_component(safe_name(value))
+    return (
+        # Per https://packaging.python.org/en/latest/specifications/name-normalization/#name-normalization
+        re
+        .sub(r"[-_.]+", "-", safe_name(value))
+        .lower()
+        # Per https://packaging.python.org/en/latest/specifications/binary-distribution-format/#escaping-and-unicode
+        .replace("-", "_")
+    )
 
 
 def safer_best_effort_version(value: str) -> str:
@@ -123,3 +150,31 @@ def safer_best_effort_version(value: str) -> str:
     # See bdist_wheel.safer_verion
     # TODO: Replace with only safe_version in the future (no need for best effort)
     return filename_component(best_effort_version(value))
+
+
+def _missing_canonicalize_license_expression(expression: str) -> str:
+    """
+    Defer import error to affect only users that actually use it
+    https://github.com/pypa/setuptools/issues/4894
+    >>> _missing_canonicalize_license_expression("a OR b")
+    Traceback (most recent call last):
+    ...
+    ImportError: ...Cannot import `packaging.licenses`...
+    """
+    raise ImportError(
+        "Cannot import `packaging.licenses`."
+        """
+        Setuptools>=77.0.0 requires "packaging>=24.2" to work properly.
+        Please make sure you have a suitable version installed.
+        """
+    )
+
+
+try:
+    from packaging.licenses import (
+        canonicalize_license_expression as _canonicalize_license_expression,
+    )
+except ImportError:  # pragma: nocover
+    if not TYPE_CHECKING:
+        # XXX: pyright is still upset even with # pyright: ignore[reportAssignmentType]
+        _canonicalize_license_expression = _missing_canonicalize_license_expression
diff --git a/setuptools/_path.py b/setuptools/_path.py
index b99d9dadcf..0a5b26ea4b 100644
--- a/setuptools/_path.py
+++ b/setuptools/_path.py
@@ -1,8 +1,17 @@
+from __future__ import annotations
+
+import contextlib
 import os
 import sys
-from typing import Union
+from typing import TYPE_CHECKING, TypeVar
+
+from more_itertools import unique_everseen
 
-_Path = Union[str, os.PathLike]
+if TYPE_CHECKING:
+    from typing import TypeAlias
+
+StrPath: TypeAlias = str | os.PathLike[str]  #  Same as _typeshed.StrPath
+StrPathT = TypeVar("StrPathT", bound=str | os.PathLike[str])
 
 
 def ensure_directory(path):
@@ -11,7 +20,7 @@ def ensure_directory(path):
     os.makedirs(dirname, exist_ok=True)
 
 
-def same_path(p1: _Path, p2: _Path) -> bool:
+def same_path(p1: StrPath, p2: StrPath) -> bool:
     """Differs from os.path.samefile because it does not require paths to exist.
     Purely string based (no comparison between i-nodes).
     >>> same_path("a/b", "./a/b")
@@ -30,8 +39,55 @@ def same_path(p1: _Path, p2: _Path) -> bool:
     return normpath(p1) == normpath(p2)
 
 
-def normpath(filename: _Path) -> str:
+def _cygwin_patch(filename: StrPath):  # pragma: nocover
+    """
+    Contrary to POSIX 2008, on Cygwin, getcwd (3) contains
+    symlink components. Using
+    os.path.abspath() works around this limitation. A fix in os.getcwd()
+    would probably better, in Cygwin even more so, except
+    that this seems to be by design...
+    """
+    return os.path.abspath(filename) if sys.platform == 'cygwin' else filename
+
+
+def normpath(filename: StrPath) -> str:
     """Normalize a file/dir name for comparison purposes."""
-    # See pkg_resources.normalize_path for notes about cygwin
-    file = os.path.abspath(filename) if sys.platform == 'cygwin' else filename
-    return os.path.normcase(os.path.realpath(os.path.normpath(file)))
+    return os.path.normcase(os.path.realpath(os.path.normpath(_cygwin_patch(filename))))
+
+
+@contextlib.contextmanager
+def paths_on_pythonpath(paths):
+    """
+    Add the indicated paths to the head of the PYTHONPATH environment
+    variable so that subprocesses will also see the packages at
+    these paths.
+
+    Do this in a context that restores the value on exit.
+
+    >>> getfixture('monkeypatch').setenv('PYTHONPATH', 'anything')
+    >>> with paths_on_pythonpath(['foo', 'bar']):
+    ...     assert 'foo' in os.environ['PYTHONPATH']
+    ...     assert 'anything' in os.environ['PYTHONPATH']
+    >>> os.environ['PYTHONPATH']
+    'anything'
+
+    >>> getfixture('monkeypatch').delenv('PYTHONPATH')
+    >>> with paths_on_pythonpath(['foo', 'bar']):
+    ...     assert 'foo' in os.environ['PYTHONPATH']
+    >>> os.environ.get('PYTHONPATH')
+    """
+    nothing = object()
+    orig_pythonpath = os.environ.get('PYTHONPATH', nothing)
+    current_pythonpath = os.environ.get('PYTHONPATH', '')
+    try:
+        prefix = os.pathsep.join(unique_everseen(paths))
+        to_join = filter(None, [prefix, current_pythonpath])
+        new_path = os.pathsep.join(to_join)
+        if new_path:
+            os.environ['PYTHONPATH'] = new_path
+        yield
+    finally:
+        if orig_pythonpath is nothing:
+            os.environ.pop('PYTHONPATH', None)
+        else:
+            os.environ['PYTHONPATH'] = orig_pythonpath
diff --git a/setuptools/_reqs.py b/setuptools/_reqs.py
index 5d5b927fd8..19ef375cf1 100644
--- a/setuptools/_reqs.py
+++ b/setuptools/_reqs.py
@@ -1,10 +1,23 @@
-from typing import Callable, Iterable, Iterator, TypeVar, Union, overload
+from __future__ import annotations
 
-import setuptools.extern.jaraco.text as text
-from setuptools.extern.packaging.requirements import Requirement
+from collections.abc import Callable, Iterable, Iterator
+from functools import lru_cache
+from typing import TYPE_CHECKING, TypeVar, overload
+
+import jaraco.text as text
+from packaging.requirements import Requirement
+
+if TYPE_CHECKING:
+    from typing import TypeAlias
 
 _T = TypeVar("_T")
-_StrOrIter = Union[str, Iterable[str]]
+_StrOrIter: TypeAlias = str | Iterable[str]
+
+
+parse_req: Callable[[str], Requirement] = lru_cache()(Requirement)
+# Setuptools parses the same requirement many times
+# (e.g. first for validation than for normalisation),
+# so it might be worth to cache.
 
 
 def parse_strings(strs: _StrOrIter) -> Iterator[str]:
@@ -16,18 +29,14 @@ def parse_strings(strs: _StrOrIter) -> Iterator[str]:
     return text.join_continuation(map(text.drop_comment, text.yield_lines(strs)))
 
 
+# These overloads are only needed because of a mypy false-positive, pyright gets it right
+# https://github.com/python/mypy/issues/3737
 @overload
-def parse(strs: _StrOrIter) -> Iterator[Requirement]:
-    ...
-
-
+def parse(strs: _StrOrIter) -> Iterator[Requirement]: ...
 @overload
-def parse(strs: _StrOrIter, parser: Callable[[str], _T]) -> Iterator[_T]:
-    ...
-
-
-def parse(strs, parser=Requirement):
+def parse(strs: _StrOrIter, parser: Callable[[str], _T]) -> Iterator[_T]: ...
+def parse(strs: _StrOrIter, parser: Callable[[str], _T] = parse_req) -> Iterator[_T]:  # type: ignore[assignment]
     """
-    Replacement for ``pkg_resources.parse_requirements`` that uses ``packaging``.
+    Parse requirements.
     """
     return map(parser, parse_strings(strs))
diff --git a/setuptools/_scripts.py b/setuptools/_scripts.py
new file mode 100644
index 0000000000..88bf02f927
--- /dev/null
+++ b/setuptools/_scripts.py
@@ -0,0 +1,361 @@
+from __future__ import annotations
+
+import os
+import re
+import shlex
+import shutil
+import struct
+import subprocess
+import sys
+import textwrap
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, TypedDict
+
+from ._importlib import metadata, resources
+
+if TYPE_CHECKING:
+    from typing_extensions import Self
+
+from .warnings import SetuptoolsWarning
+
+from distutils.command.build_scripts import first_line_re
+from distutils.util import get_platform
+
+
+class _SplitArgs(TypedDict, total=False):
+    comments: bool
+    posix: bool
+
+
+class CommandSpec(list):
+    """
+    A command spec for a #! header, specified as a list of arguments akin to
+    those passed to Popen.
+    """
+
+    options: list[str] = []
+    split_args = _SplitArgs()
+
+    @classmethod
+    def best(cls):
+        """
+        Choose the best CommandSpec class based on environmental conditions.
+        """
+        return cls
+
+    @classmethod
+    def _sys_executable(cls):
+        _default = os.path.normpath(sys.executable)
+        return os.environ.get('__PYVENV_LAUNCHER__', _default)
+
+    @classmethod
+    def from_param(cls, param: Self | str | Iterable[str] | None) -> Self:
+        """
+        Construct a CommandSpec from a parameter to build_scripts, which may
+        be None.
+        """
+        if isinstance(param, cls):
+            return param
+        if isinstance(param, str):
+            return cls.from_string(param)
+        if isinstance(param, Iterable):
+            return cls(param)
+        if param is None:
+            return cls.from_environment()
+        raise TypeError(f"Argument has an unsupported type {type(param)}")
+
+    @classmethod
+    def from_environment(cls):
+        return cls([cls._sys_executable()])
+
+    @classmethod
+    def from_string(cls, string: str) -> Self:
+        """
+        Construct a command spec from a simple string representing a command
+        line parseable by shlex.split.
+        """
+        items = shlex.split(string, **cls.split_args)
+        return cls(items)
+
+    def install_options(self, script_text: str):
+        self.options = shlex.split(self._extract_options(script_text))
+        cmdline = subprocess.list2cmdline(self)
+        if not isascii(cmdline):
+            self.options[:0] = ['-x']
+
+    @staticmethod
+    def _extract_options(orig_script):
+        """
+        Extract any options from the first line of the script.
+        """
+        first = (orig_script + '\n').splitlines()[0]
+        match = _first_line_re().match(first)
+        options = match.group(1) or '' if match else ''
+        return options.strip()
+
+    def as_header(self):
+        return self._render(self + list(self.options))
+
+    @staticmethod
+    def _strip_quotes(item):
+        _QUOTES = '"\''
+        for q in _QUOTES:
+            if item.startswith(q) and item.endswith(q):
+                return item[1:-1]
+        return item
+
+    @staticmethod
+    def _render(items):
+        cmdline = subprocess.list2cmdline(
+            CommandSpec._strip_quotes(item.strip()) for item in items
+        )
+        return '#!' + cmdline + '\n'
+
+
+class WindowsCommandSpec(CommandSpec):
+    split_args = _SplitArgs(posix=False)
+
+
+class ScriptWriter:
+    """
+    Encapsulates behavior around writing entry point scripts for console and
+    gui apps.
+    """
+
+    template = textwrap.dedent(
+        r"""
+        # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r
+        import re
+        import sys
+
+        # for compatibility with easy_install; see #2198
+        __requires__ = %(spec)r
+
+        try:
+            from importlib.metadata import distribution
+        except ImportError:
+            try:
+                from importlib_metadata import distribution
+            except ImportError:
+                from pkg_resources import load_entry_point
+
+
+        def importlib_load_entry_point(spec, group, name):
+            dist_name, _, _ = spec.partition('==')
+            matches = (
+                entry_point
+                for entry_point in distribution(dist_name).entry_points
+                if entry_point.group == group and entry_point.name == name
+            )
+            return next(matches).load()
+
+
+        globals().setdefault('load_entry_point', importlib_load_entry_point)
+
+
+        if __name__ == '__main__':
+            sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
+            sys.exit(load_entry_point(%(spec)r, %(group)r, %(name)r)())
+        """
+    ).lstrip()
+
+    command_spec_class = CommandSpec
+
+    @classmethod
+    def get_args(cls, dist, header=None):
+        """
+        Yield write_script() argument tuples for a distribution's
+        console_scripts and gui_scripts entry points.
+        """
+
+        # If distribution is not an importlib.metadata.Distribution, assume
+        # it's a pkg_resources.Distribution and transform it.
+        if not hasattr(dist, 'entry_points'):
+            SetuptoolsWarning.emit("Unsupported distribution encountered.")
+            dist = metadata.Distribution.at(dist.egg_info)
+
+        if header is None:
+            header = cls.get_header()
+        spec = f'{dist.name}=={dist.version}'
+        for type_ in 'console', 'gui':
+            group = f'{type_}_scripts'
+            for ep in dist.entry_points.select(group=group):
+                name = ep.name
+                cls._ensure_safe_name(ep.name)
+                script_text = cls.template % locals()
+                args = cls._get_script_args(type_, ep.name, header, script_text)
+                yield from args
+
+    @staticmethod
+    def _ensure_safe_name(name):
+        """
+        Prevent paths in *_scripts entry point names.
+        """
+        has_path_sep = re.search(r'[\\/]', name)
+        if has_path_sep:
+            raise ValueError("Path separators not allowed in script names")
+
+    @classmethod
+    def best(cls):
+        """
+        Select the best ScriptWriter for this environment.
+        """
+        if sys.platform == 'win32' or (os.name == 'java' and os._name == 'nt'):
+            return WindowsScriptWriter.best()
+        else:
+            return cls
+
+    @classmethod
+    def _get_script_args(cls, type_, name, header, script_text):
+        # Simply write the stub with no extension.
+        yield (name, header + script_text)
+
+    @classmethod
+    def get_header(
+        cls,
+        script_text: str = "",
+        executable: str | CommandSpec | Iterable[str] | None = None,
+    ) -> str:
+        """Create a #! line, getting options (if any) from script_text"""
+        cmd = cls.command_spec_class.best().from_param(executable)
+        cmd.install_options(script_text)
+        return cmd.as_header()
+
+
+class WindowsScriptWriter(ScriptWriter):
+    command_spec_class = WindowsCommandSpec
+
+    @classmethod
+    def best(cls):
+        """
+        Select the best ScriptWriter suitable for Windows
+        """
+        writer_lookup = dict(
+            executable=WindowsExecutableLauncherWriter,
+            natural=cls,
+        )
+        # for compatibility, use the executable launcher by default
+        launcher = os.environ.get('SETUPTOOLS_LAUNCHER', 'executable')
+        return writer_lookup[launcher]
+
+    @classmethod
+    def _get_script_args(cls, type_, name, header, script_text):
+        "For Windows, add a .py extension"
+        ext = dict(console='.pya', gui='.pyw')[type_]
+        if ext not in os.environ['PATHEXT'].lower().split(';'):
+            msg = (
+                "{ext} not listed in PATHEXT; scripts will not be "
+                "recognized as executables."
+            ).format(**locals())
+            SetuptoolsWarning.emit(msg)
+        old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe']
+        old.remove(ext)
+        header = cls._adjust_header(type_, header)
+        blockers = [name + x for x in old]
+        yield name + ext, header + script_text, 't', blockers
+
+    @classmethod
+    def _adjust_header(cls, type_, orig_header):
+        """
+        Make sure 'pythonw' is used for gui and 'python' is used for
+        console (regardless of what sys.executable is).
+        """
+        pattern = 'pythonw.exe'
+        repl = 'python.exe'
+        if type_ == 'gui':
+            pattern, repl = repl, pattern
+        pattern_ob = re.compile(re.escape(pattern), re.IGNORECASE)
+        new_header = pattern_ob.sub(string=orig_header, repl=repl)
+        return new_header if cls._use_header(new_header) else orig_header
+
+    @staticmethod
+    def _use_header(new_header):
+        """
+        Should _adjust_header use the replaced header?
+
+        On non-windows systems, always use. On
+        Windows systems, only use the replaced header if it resolves
+        to an executable on the system.
+        """
+        clean_header = new_header[2:-1].strip('"')
+        return sys.platform != 'win32' or shutil.which(clean_header)
+
+
+class WindowsExecutableLauncherWriter(WindowsScriptWriter):
+    @classmethod
+    def _get_script_args(cls, type_, name, header, script_text):
+        """
+        For Windows, add a .py extension and an .exe launcher
+        """
+        if type_ == 'gui':
+            launcher_type = 'gui'
+            ext = '-script.pyw'
+            old = ['.pyw']
+        else:
+            launcher_type = 'cli'
+            ext = '-script.py'
+            old = ['.py', '.pyc', '.pyo']
+        hdr = cls._adjust_header(type_, header)
+        blockers = [name + x for x in old]
+        yield (name + ext, hdr + script_text, 't', blockers)
+        yield (
+            name + '.exe',
+            get_win_launcher(launcher_type),
+            'b',  # write in binary mode
+        )
+        if not is_64bit():
+            # install a manifest for the launcher to prevent Windows
+            # from detecting it as an installer (which it will for
+            #  launchers like easy_install.exe). Consider only
+            #  adding a manifest for launchers detected as installers.
+            #  See Distribute #143 for details.
+            m_name = name + '.exe.manifest'
+            yield (m_name, load_launcher_manifest(name), 't')
+
+
+def get_win_launcher(type):
+    """
+    Load the Windows launcher (executable) suitable for launching a script.
+
+    `type` should be either 'cli' or 'gui'
+
+    Returns the executable as a byte string.
+    """
+    launcher_fn = f'{type}.exe'
+    if is_64bit():
+        if get_platform() == "win-arm64":
+            launcher_fn = launcher_fn.replace(".", "-arm64.")
+        else:
+            launcher_fn = launcher_fn.replace(".", "-64.")
+    else:
+        launcher_fn = launcher_fn.replace(".", "-32.")
+    return resources.files('setuptools').joinpath(launcher_fn).read_bytes()
+
+
+def load_launcher_manifest(name):
+    res = resources.files(__name__).joinpath('launcher manifest.xml')
+    return res.read_text(encoding='utf-8') % vars()
+
+
+def _first_line_re():
+    """
+    Return a regular expression based on first_line_re suitable for matching
+    strings.
+    """
+    if isinstance(first_line_re.pattern, str):
+        return first_line_re
+
+    # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
+    return re.compile(first_line_re.pattern.decode())
+
+
+def is_64bit():
+    return struct.calcsize("P") == 8
+
+
+def isascii(s):
+    try:
+        s.encode('ascii')
+    except UnicodeError:
+        return False
+    return True
diff --git a/setuptools/_shutil.py b/setuptools/_shutil.py
new file mode 100644
index 0000000000..b9a514efcc
--- /dev/null
+++ b/setuptools/_shutil.py
@@ -0,0 +1,60 @@
+"""Convenience layer on top of stdlib's shutil and os"""
+
+import os
+import stat
+from collections.abc import Callable
+from typing import TypeVar
+
+from .compat import py311
+
+from distutils import log
+
+try:
+    from os import chmod  # pyright: ignore[reportAssignmentType]
+    # Losing type-safety w/ pyright, but that's ok
+except ImportError:  # pragma: no cover
+    # Jython compatibility
+    def chmod(*args: object, **kwargs: object) -> None:  # type: ignore[misc] # Mypy reuses the imported definition anyway
+        pass
+
+
+_T = TypeVar("_T")
+
+
+def attempt_chmod_verbose(path, mode):
+    log.debug("changing mode of %s to %o", path, mode)
+    try:
+        chmod(path, mode)
+    except OSError as e:  # pragma: no cover
+        log.debug("chmod failed: %s", e)
+
+
+# Must match shutil._OnExcCallback
+def _auto_chmod(
+    func: Callable[..., _T], arg: str, exc: BaseException
+) -> _T:  # pragma: no cover
+    """shutils onexc callback to automatically call chmod for certain functions."""
+    # Only retry for scenarios known to have an issue
+    if func in [os.unlink, os.remove] and os.name == 'nt':
+        attempt_chmod_verbose(arg, stat.S_IWRITE)
+        return func(arg)
+    raise exc
+
+
+def rmtree(path, ignore_errors=False, onexc=_auto_chmod):
+    """
+    Similar to ``shutil.rmtree`` but automatically executes ``chmod``
+    for well know Windows failure scenarios.
+    """
+    return py311.shutil_rmtree(path, ignore_errors, onexc)
+
+
+def rmdir(path, **opts):
+    if os.path.isdir(path):
+        rmtree(path, **opts)
+
+
+def current_umask():
+    tmp = os.umask(0o022)
+    os.umask(tmp)
+    return tmp
diff --git a/setuptools/_static.py b/setuptools/_static.py
new file mode 100644
index 0000000000..af35862cf8
--- /dev/null
+++ b/setuptools/_static.py
@@ -0,0 +1,188 @@
+from functools import wraps
+from typing import TypeVar
+
+import packaging.specifiers
+
+from .warnings import SetuptoolsDeprecationWarning
+
+
+class Static:
+    """
+    Wrapper for built-in object types that are allow setuptools to identify
+    static core metadata (in opposition to ``Dynamic``, as defined :pep:`643`).
+
+    The trick is to mark values with :class:`Static` when they come from
+    ``pyproject.toml`` or ``setup.cfg``, so if any plugin overwrite the value
+    with a built-in, setuptools will be able to recognise the change.
+
+    We inherit from built-in classes, so that we don't need to change the existing
+    code base to deal with the new types.
+    We also should strive for immutability objects to avoid changes after the
+    initial parsing.
+    """
+
+    _mutated_: bool = False  # TODO: Remove after deprecation warning is solved
+
+
+def _prevent_modification(target: type, method: str, copying: str) -> None:
+    """
+    Because setuptools is very flexible we cannot fully prevent
+    plugins and user customizations from modifying static values that were
+    parsed from config files.
+    But we can attempt to block "in-place" mutations and identify when they
+    were done.
+    """
+    fn = getattr(target, method, None)
+    if fn is None:
+        return
+
+    @wraps(fn)
+    def _replacement(self: Static, *args, **kwargs):
+        # TODO: After deprecation period raise NotImplementedError instead of warning
+        #       which obviated the existence and checks of the `_mutated_` attribute.
+        self._mutated_ = True
+        SetuptoolsDeprecationWarning.emit(
+            "Direct modification of value will be disallowed",
+            f"""
+            In an effort to implement PEP 643, direct/in-place changes of static values
+            that come from configuration files are deprecated.
+            If you need to modify this value, please first create a copy with {copying}
+            and make sure conform to all relevant standards when overriding setuptools
+            functionality (https://packaging.python.org/en/latest/specifications/).
+            """,
+            due_date=(2025, 10, 10),  # Initially introduced in 2024-09-06
+        )
+        return fn(self, *args, **kwargs)
+
+    _replacement.__doc__ = ""  # otherwise doctest may fail.
+    setattr(target, method, _replacement)
+
+
+class Str(str, Static):
+    pass
+
+
+class Tuple(tuple, Static):
+    pass
+
+
+class List(list, Static):
+    """
+    :meta private:
+    >>> x = List([1, 2, 3])
+    >>> is_static(x)
+    True
+    >>> x += [0]  # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+    SetuptoolsDeprecationWarning: Direct modification ...
+    >>> is_static(x)  # no longer static after modification
+    False
+    >>> y = list(x)
+    >>> y.clear()
+    >>> y
+    []
+    >>> y == x
+    False
+    >>> is_static(List(y))
+    True
+    """
+
+
+# Make `List` immutable-ish
+# (certain places of setuptools/distutils issue a warn if we use tuple instead of list)
+for _method in (
+    '__delitem__',
+    '__iadd__',
+    '__setitem__',
+    'append',
+    'clear',
+    'extend',
+    'insert',
+    'remove',
+    'reverse',
+    'pop',
+):
+    _prevent_modification(List, _method, "`list(value)`")
+
+
+class Dict(dict, Static):
+    """
+    :meta private:
+    >>> x = Dict({'a': 1, 'b': 2})
+    >>> is_static(x)
+    True
+    >>> x['c'] = 0  # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+    SetuptoolsDeprecationWarning: Direct modification ...
+    >>> x._mutated_
+    True
+    >>> is_static(x)  # no longer static after modification
+    False
+    >>> y = dict(x)
+    >>> y.popitem()
+    ('b', 2)
+    >>> y == x
+    False
+    >>> is_static(Dict(y))
+    True
+    """
+
+
+# Make `Dict` immutable-ish (we cannot inherit from types.MappingProxyType):
+for _method in (
+    '__delitem__',
+    '__ior__',
+    '__setitem__',
+    'clear',
+    'pop',
+    'popitem',
+    'setdefault',
+    'update',
+):
+    _prevent_modification(Dict, _method, "`dict(value)`")
+
+
+class SpecifierSet(packaging.specifiers.SpecifierSet, Static):
+    """Not exactly a built-in type but useful for ``requires-python``"""
+
+
+T = TypeVar("T")
+
+
+def noop(value: T) -> T:
+    """
+    >>> noop(42)
+    42
+    """
+    return value
+
+
+_CONVERSIONS = {str: Str, tuple: Tuple, list: List, dict: Dict}
+
+
+def attempt_conversion(value: T) -> T:
+    """
+    >>> is_static(attempt_conversion("hello"))
+    True
+    >>> is_static(object())
+    False
+    """
+    return _CONVERSIONS.get(type(value), noop)(value)  # type: ignore[call-overload]
+
+
+def is_static(value: object) -> bool:
+    """
+    >>> is_static(a := Dict({'a': 1}))
+    True
+    >>> is_static(dict(a))
+    False
+    >>> is_static(b := List([1, 2, 3]))
+    True
+    >>> is_static(list(b))
+    False
+    """
+    return isinstance(value, Static) and not value._mutated_
+
+
+EMPTY_LIST = List()
+EMPTY_DICT = Dict()
diff --git a/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/REQUESTED b/setuptools/_vendor/.lock
similarity index 100%
rename from pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/REQUESTED
rename to setuptools/_vendor/.lock
diff --git a/setuptools/_vendor/__init__.py b/setuptools/_vendor/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/setuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLER b/setuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLER
new file mode 100644
index 0000000000..5c69047b2e
--- /dev/null
+++ b/setuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/setuptools/_vendor/autocommand-2.2.2.dist-info/LICENSE b/setuptools/_vendor/autocommand-2.2.2.dist-info/LICENSE
new file mode 100644
index 0000000000..b49c3af060
--- /dev/null
+++ b/setuptools/_vendor/autocommand-2.2.2.dist-info/LICENSE
@@ -0,0 +1,166 @@
+GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. 
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+  This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+  0. Additional Definitions.
+
+  As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+  "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+  An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+  A "Combined Work" is a work produced by combining or linking an
+Application with the Library.  The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+  The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+  The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+  1. Exception to Section 3 of the GNU GPL.
+
+  You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+  2. Conveying Modified Versions.
+
+  If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+   a) under this License, provided that you make a good faith effort to
+   ensure that, in the event an Application does not supply the
+   function or data, the facility still operates, and performs
+   whatever part of its purpose remains meaningful, or
+
+   b) under the GNU GPL, with none of the additional permissions of
+   this License applicable to that copy.
+
+  3. Object Code Incorporating Material from Library Header Files.
+
+  The object code form of an Application may incorporate material from
+a header file that is part of the Library.  You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+   a) Give prominent notice with each copy of the object code that the
+   Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the object code with a copy of the GNU GPL and this license
+   document.
+
+  4. Combined Works.
+
+  You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+   a) Give prominent notice with each copy of the Combined Work that
+   the Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the Combined Work with a copy of the GNU GPL and this license
+   document.
+
+   c) For a Combined Work that displays copyright notices during
+   execution, include the copyright notice for the Library among
+   these notices, as well as a reference directing the user to the
+   copies of the GNU GPL and this license document.
+
+   d) Do one of the following:
+
+       0) Convey the Minimal Corresponding Source under the terms of this
+       License, and the Corresponding Application Code in a form
+       suitable for, and under terms that permit, the user to
+       recombine or relink the Application with a modified version of
+       the Linked Version to produce a modified Combined Work, in the
+       manner specified by section 6 of the GNU GPL for conveying
+       Corresponding Source.
+
+       1) Use a suitable shared library mechanism for linking with the
+       Library.  A suitable mechanism is one that (a) uses at run time
+       a copy of the Library already present on the user's computer
+       system, and (b) will operate properly with a modified version
+       of the Library that is interface-compatible with the Linked
+       Version.
+
+   e) Provide Installation Information, but only if you would otherwise
+   be required to provide such information under section 6 of the
+   GNU GPL, and only to the extent that such information is
+   necessary to install and execute a modified version of the
+   Combined Work produced by recombining or relinking the
+   Application with a modified version of the Linked Version. (If
+   you use option 4d0, the Installation Information must accompany
+   the Minimal Corresponding Source and Corresponding Application
+   Code. If you use option 4d1, you must provide the Installation
+   Information in the manner specified by section 6 of the GNU GPL
+   for conveying Corresponding Source.)
+
+  5. Combined Libraries.
+
+  You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+   a) Accompany the combined library with a copy of the same work based
+   on the Library, uncombined with any other library facilities,
+   conveyed under the terms of this License.
+
+   b) Give prominent notice with the combined library that part of it
+   is a work based on the Library, and explaining where to find the
+   accompanying uncombined form of the same work.
+
+  6. Revised Versions of the GNU Lesser General Public License.
+
+  The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+  Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+  If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
+
diff --git a/setuptools/_vendor/autocommand-2.2.2.dist-info/METADATA b/setuptools/_vendor/autocommand-2.2.2.dist-info/METADATA
new file mode 100644
index 0000000000..32214fb440
--- /dev/null
+++ b/setuptools/_vendor/autocommand-2.2.2.dist-info/METADATA
@@ -0,0 +1,420 @@
+Metadata-Version: 2.1
+Name: autocommand
+Version: 2.2.2
+Summary: A library to create a command-line program from a function
+Home-page: https://github.com/Lucretiel/autocommand
+Author: Nathan West
+License: LGPLv3
+Project-URL: Homepage, https://github.com/Lucretiel/autocommand
+Project-URL: Bug Tracker, https://github.com/Lucretiel/autocommand/issues
+Platform: any
+Classifier: Development Status :: 6 - Mature
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Topic :: Software Development
+Classifier: Topic :: Software Development :: Libraries
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Python: >=3.7
+Description-Content-Type: text/markdown
+License-File: LICENSE
+
+[![PyPI version](https://badge.fury.io/py/autocommand.svg)](https://badge.fury.io/py/autocommand)
+
+# autocommand
+
+A library to automatically generate and run simple argparse parsers from function signatures.
+
+## Installation
+
+Autocommand is installed via pip:
+
+```
+$ pip install autocommand
+```
+
+## Usage
+
+Autocommand turns a function into a command-line program. It converts the function's parameter signature into command-line arguments, and automatically runs the function if the module was called as `__main__`. In effect, it lets your create a smart main function.
+
+```python
+from autocommand import autocommand
+
+# This program takes exactly one argument and echos it.
+@autocommand(__name__)
+def echo(thing):
+    print(thing)
+```
+
+```
+$ python echo.py hello
+hello
+$ python echo.py -h
+usage: echo [-h] thing
+
+positional arguments:
+  thing
+
+optional arguments:
+  -h, --help  show this help message and exit
+$ python echo.py hello world  # too many arguments
+usage: echo.py [-h] thing
+echo.py: error: unrecognized arguments: world
+```
+
+As you can see, autocommand converts the signature of the function into an argument spec. When you run the file as a program, autocommand collects the command-line arguments and turns them into function arguments. The function is executed with these arguments, and then the program exits with the return value of the function, via `sys.exit`. Autocommand also automatically creates a usage message, which can be invoked with `-h` or `--help`, and automatically prints an error message when provided with invalid arguments.
+
+### Types
+
+You can use a type annotation to give an argument a type. Any type (or in fact any callable) that returns an object when given a string argument can be used, though there are a few special cases that are described later.
+
+```python
+@autocommand(__name__)
+def net_client(host, port: int):
+    ...
+```
+
+Autocommand will catch `TypeErrors` raised by the type during argument parsing, so you can supply a callable and do some basic argument validation as well.
+
+### Trailing Arguments
+
+You can add a `*args` parameter to your function to give it trailing arguments. The command will collect 0 or more trailing arguments and supply them to `args` as a tuple. If a type annotation is supplied, the type is applied to each argument.
+
+```python
+# Write the contents of each file, one by one
+@autocommand(__name__)
+def cat(*files):
+    for filename in files:
+        with open(filename) as file:
+            for line in file:
+                print(line.rstrip())
+```
+
+```
+$ python cat.py -h
+usage: ipython [-h] [file [file ...]]
+
+positional arguments:
+  file
+
+optional arguments:
+  -h, --help  show this help message and exit
+```
+
+### Options
+
+To create `--option` switches, just assign a default. Autocommand will automatically create `--long` and `-s`hort switches.
+
+```python
+@autocommand(__name__)
+def do_with_config(argument, config='~/foo.conf'):
+    pass
+```
+
+```
+$ python example.py -h
+usage: example.py [-h] [-c CONFIG] argument
+
+positional arguments:
+  argument
+
+optional arguments:
+  -h, --help            show this help message and exit
+  -c CONFIG, --config CONFIG
+```
+
+The option's type is automatically deduced from the default, unless one is explicitly given in an annotation:
+
+```python
+@autocommand(__name__)
+def http_connect(host, port=80):
+    print('{}:{}'.format(host, port))
+```
+
+```
+$ python http.py -h
+usage: http.py [-h] [-p PORT] host
+
+positional arguments:
+  host
+
+optional arguments:
+  -h, --help            show this help message and exit
+  -p PORT, --port PORT
+$ python http.py localhost
+localhost:80
+$ python http.py localhost -p 8080
+localhost:8080
+$ python http.py localhost -p blah
+usage: http.py [-h] [-p PORT] host
+http.py: error: argument -p/--port: invalid int value: 'blah'
+```
+
+#### None
+
+If an option is given a default value of `None`, it reads in a value as normal, but supplies `None` if the option isn't provided.
+
+#### Switches
+
+If an argument is given a default value of `True` or `False`, or
+given an explicit `bool` type, it becomes an option switch.
+
+```python
+    @autocommand(__name__)
+    def example(verbose=False, quiet=False):
+        pass
+```
+
+```
+$ python example.py -h
+usage: example.py [-h] [-v] [-q]
+
+optional arguments:
+  -h, --help     show this help message and exit
+  -v, --verbose
+  -q, --quiet
+```
+
+Autocommand attempts to do the "correct thing" in these cases- if the default is `True`, then supplying the switch makes the argument `False`; if the type is `bool` and the default is some other `True` value, then supplying the switch makes the argument `False`, while not supplying the switch makes the argument the default value.
+
+Autocommand also supports the creation of switch inverters. Pass `add_nos=True` to `autocommand` to enable this.
+
+```
+    @autocommand(__name__, add_nos=True)
+    def example(verbose=False):
+        pass
+```
+
+```
+$ python example.py -h
+usage: ipython [-h] [-v] [--no-verbose]
+
+optional arguments:
+  -h, --help     show this help message and exit
+  -v, --verbose
+  --no-verbose
+```
+
+Using the `--no-` version of a switch will pass the opposite value in as a function argument. If multiple switches are present, the last one takes precedence.
+
+#### Files
+
+If the default value is a file object, such as `sys.stdout`, then autocommand just looks for a string, for a file path. It doesn't do any special checking on the string, though (such as checking if the file exists); it's better to let the client decide how to handle errors in this case. Instead, it provides a special context manager called `smart_open`, which behaves exactly like `open` if a filename or other openable type is provided, but also lets you use already open files:
+
+```python
+from autocommand import autocommand, smart_open
+import sys
+
+# Write the contents of stdin, or a file, to stdout
+@autocommand(__name__)
+def write_out(infile=sys.stdin):
+    with smart_open(infile) as f:
+        for line in f:
+            print(line.rstrip())
+    # If a file was opened, it is closed here. If it was just stdin, it is untouched.
+```
+
+```
+$ echo "Hello World!" | python write_out.py | tee hello.txt
+Hello World!
+$ python write_out.py --infile hello.txt
+Hello World!
+```
+
+### Descriptions and docstrings
+
+The `autocommand` decorator accepts `description` and `epilog` kwargs, corresponding to the `description `_ and `epilog `_ of the `ArgumentParser`. If no description is given, but the decorated function has a docstring, then it is taken as the `description` for the `ArgumentParser`. You can also provide both the description and epilog in the docstring by splitting it into two sections with 4 or more - characters.
+
+```python
+@autocommand(__name__)
+def copy(infile=sys.stdin, outfile=sys.stdout):
+    '''
+    Copy an the contents of a file (or stdin) to another file (or stdout)
+    ----------
+    Some extra documentation in the epilog
+    '''
+    with smart_open(infile) as istr:
+        with smart_open(outfile, 'w') as ostr:
+            for line in istr:
+                ostr.write(line)
+```
+
+```
+$ python copy.py -h
+usage: copy.py [-h] [-i INFILE] [-o OUTFILE]
+
+Copy an the contents of a file (or stdin) to another file (or stdout)
+
+optional arguments:
+  -h, --help            show this help message and exit
+  -i INFILE, --infile INFILE
+  -o OUTFILE, --outfile OUTFILE
+
+Some extra documentation in the epilog
+$ echo "Hello World" | python copy.py --outfile hello.txt
+$ python copy.py --infile hello.txt --outfile hello2.txt
+$ python copy.py --infile hello2.txt
+Hello World
+```
+
+### Parameter descriptions
+
+You can also attach description text to individual parameters in the annotation. To attach both a type and a description, supply them both in any order in a tuple
+
+```python
+@autocommand(__name__)
+def copy_net(
+    infile: 'The name of the file to send',
+    host: 'The host to send the file to',
+    port: (int, 'The port to connect to')):
+
+    '''
+    Copy a file over raw TCP to a remote destination.
+    '''
+    # Left as an exercise to the reader
+```
+
+### Decorators and wrappers
+
+Autocommand automatically follows wrapper chains created by `@functools.wraps`. This means that you can apply other wrapping decorators to your main function, and autocommand will still correctly detect the signature.
+
+```python
+from functools import wraps
+from autocommand import autocommand
+
+def print_yielded(func):
+    '''
+    Convert a generator into a function that prints all yielded elements
+    '''
+    @wraps(func)
+    def wrapper(*args, **kwargs):
+        for thing in func(*args, **kwargs):
+            print(thing)
+    return wrapper
+
+@autocommand(__name__,
+    description= 'Print all the values from START to STOP, inclusive, in steps of STEP',
+    epilog=      'STOP and STEP default to 1')
+@print_yielded
+def seq(stop, start=1, step=1):
+    for i in range(start, stop + 1, step):
+        yield i
+```
+
+```
+$ seq.py -h
+usage: seq.py [-h] [-s START] [-S STEP] stop
+
+Print all the values from START to STOP, inclusive, in steps of STEP
+
+positional arguments:
+  stop
+
+optional arguments:
+  -h, --help            show this help message and exit
+  -s START, --start START
+  -S STEP, --step STEP
+
+STOP and STEP default to 1
+```
+
+Even though autocommand is being applied to the `wrapper` returned by `print_yielded`, it still retreives the signature of the underlying `seq` function to create the argument parsing.
+
+### Custom Parser
+
+While autocommand's automatic parser generator is a powerful convenience, it doesn't cover all of the different features that argparse provides. If you need these features, you can provide your own parser as a kwarg to `autocommand`:
+
+```python
+from argparse import ArgumentParser
+from autocommand import autocommand
+
+parser = ArgumentParser()
+# autocommand can't do optional positonal parameters
+parser.add_argument('arg', nargs='?')
+# or mutually exclusive options
+group = parser.add_mutually_exclusive_group()
+group.add_argument('-v', '--verbose', action='store_true')
+group.add_argument('-q', '--quiet', action='store_true')
+
+@autocommand(__name__, parser=parser)
+def main(arg, verbose, quiet):
+    print(arg, verbose, quiet)
+```
+
+```
+$ python parser.py -h
+usage: write_file.py [-h] [-v | -q] [arg]
+
+positional arguments:
+  arg
+
+optional arguments:
+  -h, --help     show this help message and exit
+  -v, --verbose
+  -q, --quiet
+$ python parser.py
+None False False
+$ python parser.py hello
+hello False False
+$ python parser.py -v
+None True False
+$ python parser.py -q
+None False True
+$ python parser.py -vq
+usage: parser.py [-h] [-v | -q] [arg]
+parser.py: error: argument -q/--quiet: not allowed with argument -v/--verbose
+```
+
+Any parser should work fine, so long as each of the parser's arguments has a corresponding parameter in the decorated main function. The order of parameters doesn't matter, as long as they are all present. Note that when using a custom parser, autocommand doesn't modify the parser or the retrieved arguments. This means that no description/epilog will be added, and the function's type annotations and defaults (if present) will be ignored.
+
+## Testing and Library use
+
+The decorated function is only called and exited from if the first argument to `autocommand` is `'__main__'` or `True`. If it is neither of these values, or no argument is given, then a new main function is created by the decorator. This function has the signature `main(argv=None)`, and is intended to be called with arguments as if via `main(sys.argv[1:])`. The function has the attributes `parser` and `main`, which are the generated `ArgumentParser` and the original main function that was decorated. This is to facilitate testing and library use of your main. Calling the function triggers a `parse_args()` with the supplied arguments, and returns the result of the main function. Note that, while it returns instead of calling `sys.exit`, the `parse_args()` function will raise a `SystemExit` in the event of a parsing error or `-h/--help` argument.
+
+```python
+    @autocommand()
+    def test_prog(arg1, arg2: int, quiet=False, verbose=False):
+        if not quiet:
+            print(arg1, arg2)
+            if verbose:
+                print("LOUD NOISES")
+
+        return 0
+
+    print(test_prog(['-v', 'hello', '80']))
+```
+
+```
+$ python test_prog.py
+hello 80
+LOUD NOISES
+0
+```
+
+If the function is called with no arguments, `sys.argv[1:]` is used. This is to allow the autocommand function to be used as a setuptools entry point.
+
+## Exceptions and limitations
+
+- There are a few possible exceptions that `autocommand` can raise. All of them derive from `autocommand.AutocommandError`.
+
+  - If an invalid annotation is given (that is, it isn't a `type`, `str`, `(type, str)`, or `(str, type)`, an `AnnotationError` is raised. The `type` may be any callable, as described in the `Types`_ section.
+  - If the function has a `**kwargs` parameter, a `KWargError` is raised.
+  - If, somehow, the function has a positional-only parameter, a `PositionalArgError` is raised. This means that the argument doesn't have a name, which is currently not possible with a plain `def` or `lambda`, though many built-in functions have this kind of parameter.
+
+- There are a few argparse features that are not supported by autocommand.
+
+  - It isn't possible to have an optional positional argument (as opposed to a `--option`). POSIX thinks this is bad form anyway.
+  - It isn't possible to have mutually exclusive arguments or options
+  - It isn't possible to have subcommands or subparsers, though I'm working on a few solutions involving classes or nested function definitions to allow this.
+
+## Development
+
+Autocommand cannot be important from the project root; this is to enforce separation of concerns and prevent accidental importing of `setup.py` or tests. To develop, install the project in editable mode:
+
+```
+$ python setup.py develop
+```
+
+This will create a link to the source files in the deployment directory, so that any source changes are reflected when it is imported.
diff --git a/setuptools/_vendor/autocommand-2.2.2.dist-info/RECORD b/setuptools/_vendor/autocommand-2.2.2.dist-info/RECORD
new file mode 100644
index 0000000000..8cd7450980
--- /dev/null
+++ b/setuptools/_vendor/autocommand-2.2.2.dist-info/RECORD
@@ -0,0 +1,13 @@
+autocommand-2.2.2.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+autocommand-2.2.2.dist-info/LICENSE,sha256=reeNBJgtaZctREqOFKlPh6IzTdOFXMgDSOqOJAqg3y0,7634
+autocommand-2.2.2.dist-info/METADATA,sha256=OADZuR3O6iBlpu1ieTgzYul6w4uOVrk0P0BO5TGGAJk,15006
+autocommand-2.2.2.dist-info/RECORD,,
+autocommand-2.2.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+autocommand-2.2.2.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92
+autocommand-2.2.2.dist-info/top_level.txt,sha256=AzfhgKKS8EdAwWUTSF8mgeVQbXOY9kokHB6kSqwwqu0,12
+autocommand/__init__.py,sha256=zko5Rnvolvb-UXjCx_2ArPTGBWwUK5QY4LIQIKYR7As,1037
+autocommand/autoasync.py,sha256=AMdyrxNS4pqWJfP_xuoOcImOHWD-qT7x06wmKN1Vp-U,5680
+autocommand/autocommand.py,sha256=hmkEmQ72HtL55gnURVjDOnsfYlGd5lLXbvT4KG496Qw,2505
+autocommand/automain.py,sha256=A2b8i754Mxc_DjU9WFr6vqYDWlhz0cn8miu8d8EsxV8,2076
+autocommand/autoparse.py,sha256=WVWmZJPcbzUKXP40raQw_0HD8qPJ2V9VG1eFFmmnFxw,11642
+autocommand/errors.py,sha256=7aa3roh9Herd6nIKpQHNWEslWE8oq7GiHYVUuRqORnA,886
diff --git a/pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/REQUESTED b/setuptools/_vendor/autocommand-2.2.2.dist-info/REQUESTED
similarity index 100%
rename from pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/REQUESTED
rename to setuptools/_vendor/autocommand-2.2.2.dist-info/REQUESTED
diff --git a/pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/WHEEL b/setuptools/_vendor/autocommand-2.2.2.dist-info/WHEEL
similarity index 100%
rename from pkg_resources/_vendor/importlib_resources-5.10.2.dist-info/WHEEL
rename to setuptools/_vendor/autocommand-2.2.2.dist-info/WHEEL
diff --git a/setuptools/_vendor/autocommand-2.2.2.dist-info/top_level.txt b/setuptools/_vendor/autocommand-2.2.2.dist-info/top_level.txt
new file mode 100644
index 0000000000..dda5158ff6
--- /dev/null
+++ b/setuptools/_vendor/autocommand-2.2.2.dist-info/top_level.txt
@@ -0,0 +1 @@
+autocommand
diff --git a/setuptools/_vendor/autocommand/__init__.py b/setuptools/_vendor/autocommand/__init__.py
new file mode 100644
index 0000000000..73fbfca6b3
--- /dev/null
+++ b/setuptools/_vendor/autocommand/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2014-2016 Nathan West
+#
+# This file is part of autocommand.
+#
+# autocommand is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# autocommand is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with autocommand.  If not, see .
+
+# flake8 flags all these imports as unused, hence the NOQAs everywhere.
+
+from .automain import automain  # NOQA
+from .autoparse import autoparse, smart_open  # NOQA
+from .autocommand import autocommand  # NOQA
+
+try:
+    from .autoasync import autoasync  # NOQA
+except ImportError:  # pragma: no cover
+    pass
diff --git a/setuptools/_vendor/autocommand/autoasync.py b/setuptools/_vendor/autocommand/autoasync.py
new file mode 100644
index 0000000000..688f7e0554
--- /dev/null
+++ b/setuptools/_vendor/autocommand/autoasync.py
@@ -0,0 +1,142 @@
+# Copyright 2014-2015 Nathan West
+#
+# This file is part of autocommand.
+#
+# autocommand is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# autocommand is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with autocommand.  If not, see .
+
+from asyncio import get_event_loop, iscoroutine
+from functools import wraps
+from inspect import signature
+
+
+async def _run_forever_coro(coro, args, kwargs, loop):
+    '''
+    This helper function launches an async main function that was tagged with
+    forever=True. There are two possibilities:
+
+    - The function is a normal function, which handles initializing the event
+      loop, which is then run forever
+    - The function is a coroutine, which needs to be scheduled in the event
+      loop, which is then run forever
+      - There is also the possibility that the function is a normal function
+        wrapping a coroutine function
+
+    The function is therefore called unconditionally and scheduled in the event
+    loop if the return value is a coroutine object.
+
+    The reason this is a separate function is to make absolutely sure that all
+    the objects created are garbage collected after all is said and done; we
+    do this to ensure that any exceptions raised in the tasks are collected
+    ASAP.
+    '''
+
+    # Personal note: I consider this an antipattern, as it relies on the use of
+    # unowned resources. The setup function dumps some stuff into the event
+    # loop where it just whirls in the ether without a well defined owner or
+    # lifetime. For this reason, there's a good chance I'll remove the
+    # forever=True feature from autoasync at some point in the future.
+    thing = coro(*args, **kwargs)
+    if iscoroutine(thing):
+        await thing
+
+
+def autoasync(coro=None, *, loop=None, forever=False, pass_loop=False):
+    '''
+    Convert an asyncio coroutine into a function which, when called, is
+    evaluted in an event loop, and the return value returned. This is intented
+    to make it easy to write entry points into asyncio coroutines, which
+    otherwise need to be explictly evaluted with an event loop's
+    run_until_complete.
+
+    If `loop` is given, it is used as the event loop to run the coro in. If it
+    is None (the default), the loop is retreived using asyncio.get_event_loop.
+    This call is defered until the decorated function is called, so that
+    callers can install custom event loops or event loop policies after
+    @autoasync is applied.
+
+    If `forever` is True, the loop is run forever after the decorated coroutine
+    is finished. Use this for servers created with asyncio.start_server and the
+    like.
+
+    If `pass_loop` is True, the event loop object is passed into the coroutine
+    as the `loop` kwarg when the wrapper function is called. In this case, the
+    wrapper function's __signature__ is updated to remove this parameter, so
+    that autoparse can still be used on it without generating a parameter for
+    `loop`.
+
+    This coroutine can be called with ( @autoasync(...) ) or without
+    ( @autoasync ) arguments.
+
+    Examples:
+
+    @autoasync
+    def get_file(host, port):
+        reader, writer = yield from asyncio.open_connection(host, port)
+        data = reader.read()
+        sys.stdout.write(data.decode())
+
+    get_file(host, port)
+
+    @autoasync(forever=True, pass_loop=True)
+    def server(host, port, loop):
+        yield_from loop.create_server(Proto, host, port)
+
+    server('localhost', 8899)
+
+    '''
+    if coro is None:
+        return lambda c: autoasync(
+            c, loop=loop,
+            forever=forever,
+            pass_loop=pass_loop)
+
+    # The old and new signatures are required to correctly bind the loop
+    # parameter in 100% of cases, even if it's a positional parameter.
+    # NOTE: A future release will probably require the loop parameter to be
+    # a kwonly parameter.
+    if pass_loop:
+        old_sig = signature(coro)
+        new_sig = old_sig.replace(parameters=(
+            param for name, param in old_sig.parameters.items()
+            if name != "loop"))
+
+    @wraps(coro)
+    def autoasync_wrapper(*args, **kwargs):
+        # Defer the call to get_event_loop so that, if a custom policy is
+        # installed after the autoasync decorator, it is respected at call time
+        local_loop = get_event_loop() if loop is None else loop
+
+        # Inject the 'loop' argument. We have to use this signature binding to
+        # ensure it's injected in the correct place (positional, keyword, etc)
+        if pass_loop:
+            bound_args = old_sig.bind_partial()
+            bound_args.arguments.update(
+                loop=local_loop,
+                **new_sig.bind(*args, **kwargs).arguments)
+            args, kwargs = bound_args.args, bound_args.kwargs
+
+        if forever:
+            local_loop.create_task(_run_forever_coro(
+                coro, args, kwargs, local_loop
+            ))
+            local_loop.run_forever()
+        else:
+            return local_loop.run_until_complete(coro(*args, **kwargs))
+
+    # Attach the updated signature. This allows 'pass_loop' to be used with
+    # autoparse
+    if pass_loop:
+        autoasync_wrapper.__signature__ = new_sig
+
+    return autoasync_wrapper
diff --git a/setuptools/_vendor/autocommand/autocommand.py b/setuptools/_vendor/autocommand/autocommand.py
new file mode 100644
index 0000000000..097e86de07
--- /dev/null
+++ b/setuptools/_vendor/autocommand/autocommand.py
@@ -0,0 +1,70 @@
+# Copyright 2014-2015 Nathan West
+#
+# This file is part of autocommand.
+#
+# autocommand is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# autocommand is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with autocommand.  If not, see .
+
+from .autoparse import autoparse
+from .automain import automain
+try:
+    from .autoasync import autoasync
+except ImportError:  # pragma: no cover
+    pass
+
+
+def autocommand(
+        module, *,
+        description=None,
+        epilog=None,
+        add_nos=False,
+        parser=None,
+        loop=None,
+        forever=False,
+        pass_loop=False):
+
+    if callable(module):
+        raise TypeError('autocommand requires a module name argument')
+
+    def autocommand_decorator(func):
+        # Step 1: if requested, run it all in an asyncio event loop. autoasync
+        # patches the __signature__ of the decorated function, so that in the
+        # event that pass_loop is True, the `loop` parameter of the original
+        # function will *not* be interpreted as a command-line argument by
+        # autoparse
+        if loop is not None or forever or pass_loop:
+            func = autoasync(
+                func,
+                loop=None if loop is True else loop,
+                pass_loop=pass_loop,
+                forever=forever)
+
+        # Step 2: create parser. We do this second so that the arguments are
+        # parsed and passed *before* entering the asyncio event loop, if it
+        # exists. This simplifies the stack trace and ensures errors are
+        # reported earlier. It also ensures that errors raised during parsing &
+        # passing are still raised if `forever` is True.
+        func = autoparse(
+            func,
+            description=description,
+            epilog=epilog,
+            add_nos=add_nos,
+            parser=parser)
+
+        # Step 3: call the function automatically if __name__ == '__main__' (or
+        # if True was provided)
+        func = automain(module)(func)
+
+        return func
+
+    return autocommand_decorator
diff --git a/setuptools/_vendor/autocommand/automain.py b/setuptools/_vendor/autocommand/automain.py
new file mode 100644
index 0000000000..6cc45db66a
--- /dev/null
+++ b/setuptools/_vendor/autocommand/automain.py
@@ -0,0 +1,59 @@
+# Copyright 2014-2015 Nathan West
+#
+# This file is part of autocommand.
+#
+# autocommand is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# autocommand is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with autocommand.  If not, see .
+
+import sys
+from .errors import AutocommandError
+
+
+class AutomainRequiresModuleError(AutocommandError, TypeError):
+    pass
+
+
+def automain(module, *, args=(), kwargs=None):
+    '''
+    This decorator automatically invokes a function if the module is being run
+    as the "__main__" module. Optionally, provide args or kwargs with which to
+    call the function. If `module` is "__main__", the function is called, and
+    the program is `sys.exit`ed with the return value. You can also pass `True`
+    to cause the function to be called unconditionally. If the function is not
+    called, it is returned unchanged by the decorator.
+
+    Usage:
+
+    @automain(__name__)  # Pass __name__ to check __name__=="__main__"
+    def main():
+        ...
+
+    If __name__ is "__main__" here, the main function is called, and then
+    sys.exit called with the return value.
+    '''
+
+    # Check that @automain(...) was called, rather than @automain
+    if callable(module):
+        raise AutomainRequiresModuleError(module)
+
+    if module == '__main__' or module is True:
+        if kwargs is None:
+            kwargs = {}
+
+        # Use a function definition instead of a lambda for a neater traceback
+        def automain_decorator(main):
+            sys.exit(main(*args, **kwargs))
+
+        return automain_decorator
+    else:
+        return lambda main: main
diff --git a/setuptools/_vendor/autocommand/autoparse.py b/setuptools/_vendor/autocommand/autoparse.py
new file mode 100644
index 0000000000..0276a3fae1
--- /dev/null
+++ b/setuptools/_vendor/autocommand/autoparse.py
@@ -0,0 +1,333 @@
+# Copyright 2014-2015 Nathan West
+#
+# This file is part of autocommand.
+#
+# autocommand is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# autocommand is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with autocommand.  If not, see .
+
+import sys
+from re import compile as compile_regex
+from inspect import signature, getdoc, Parameter
+from argparse import ArgumentParser
+from contextlib import contextmanager
+from functools import wraps
+from io import IOBase
+from autocommand.errors import AutocommandError
+
+
+_empty = Parameter.empty
+
+
+class AnnotationError(AutocommandError):
+    '''Annotation error: annotation must be a string, type, or tuple of both'''
+
+
+class PositionalArgError(AutocommandError):
+    '''
+    Postional Arg Error: autocommand can't handle postional-only parameters
+    '''
+
+
+class KWArgError(AutocommandError):
+    '''kwarg Error: autocommand can't handle a **kwargs parameter'''
+
+
+class DocstringError(AutocommandError):
+    '''Docstring error'''
+
+
+class TooManySplitsError(DocstringError):
+    '''
+    The docstring had too many ---- section splits. Currently we only support
+    using up to a single split, to split the docstring into description and
+    epilog parts.
+    '''
+
+
+def _get_type_description(annotation):
+    '''
+    Given an annotation, return the (type, description) for the parameter.
+    If you provide an annotation that is somehow both a string and a callable,
+    the behavior is undefined.
+    '''
+    if annotation is _empty:
+        return None, None
+    elif callable(annotation):
+        return annotation, None
+    elif isinstance(annotation, str):
+        return None, annotation
+    elif isinstance(annotation, tuple):
+        try:
+            arg1, arg2 = annotation
+        except ValueError as e:
+            raise AnnotationError(annotation) from e
+        else:
+            if callable(arg1) and isinstance(arg2, str):
+                return arg1, arg2
+            elif isinstance(arg1, str) and callable(arg2):
+                return arg2, arg1
+
+    raise AnnotationError(annotation)
+
+
+def _add_arguments(param, parser, used_char_args, add_nos):
+    '''
+    Add the argument(s) to an ArgumentParser (using add_argument) for a given
+    parameter. used_char_args is the set of -short options currently already in
+    use, and is updated (if necessary) by this function. If add_nos is True,
+    this will also add an inverse switch for all boolean options. For
+    instance, for the boolean parameter "verbose", this will create --verbose
+    and --no-verbose.
+    '''
+
+    # Impl note: This function is kept separate from make_parser because it's
+    # already very long and I wanted to separate out as much as possible into
+    # its own call scope, to prevent even the possibility of suble mutation
+    # bugs.
+    if param.kind is param.POSITIONAL_ONLY:
+        raise PositionalArgError(param)
+    elif param.kind is param.VAR_KEYWORD:
+        raise KWArgError(param)
+
+    # These are the kwargs for the add_argument function.
+    arg_spec = {}
+    is_option = False
+
+    # Get the type and default from the annotation.
+    arg_type, description = _get_type_description(param.annotation)
+
+    # Get the default value
+    default = param.default
+
+    # If there is no explicit type, and the default is present and not None,
+    # infer the type from the default.
+    if arg_type is None and default not in {_empty, None}:
+        arg_type = type(default)
+
+    # Add default. The presence of a default means this is an option, not an
+    # argument.
+    if default is not _empty:
+        arg_spec['default'] = default
+        is_option = True
+
+    # Add the type
+    if arg_type is not None:
+        # Special case for bool: make it just a --switch
+        if arg_type is bool:
+            if not default or default is _empty:
+                arg_spec['action'] = 'store_true'
+            else:
+                arg_spec['action'] = 'store_false'
+
+            # Switches are always options
+            is_option = True
+
+        # Special case for file types: make it a string type, for filename
+        elif isinstance(default, IOBase):
+            arg_spec['type'] = str
+
+        # TODO: special case for list type.
+        #   - How to specificy type of list members?
+        #       - param: [int]
+        #       - param: int =[]
+        #   - action='append' vs nargs='*'
+
+        else:
+            arg_spec['type'] = arg_type
+
+    # nargs: if the signature includes *args, collect them as trailing CLI
+    # arguments in a list. *args can't have a default value, so it can never be
+    # an option.
+    if param.kind is param.VAR_POSITIONAL:
+        # TODO: consider depluralizing metavar/name here.
+        arg_spec['nargs'] = '*'
+
+    # Add description.
+    if description is not None:
+        arg_spec['help'] = description
+
+    # Get the --flags
+    flags = []
+    name = param.name
+
+    if is_option:
+        # Add the first letter as a -short option.
+        for letter in name[0], name[0].swapcase():
+            if letter not in used_char_args:
+                used_char_args.add(letter)
+                flags.append('-{}'.format(letter))
+                break
+
+        # If the parameter is a --long option, or is a -short option that
+        # somehow failed to get a flag, add it.
+        if len(name) > 1 or not flags:
+            flags.append('--{}'.format(name))
+
+        arg_spec['dest'] = name
+    else:
+        flags.append(name)
+
+    parser.add_argument(*flags, **arg_spec)
+
+    # Create the --no- version for boolean switches
+    if add_nos and arg_type is bool:
+        parser.add_argument(
+            '--no-{}'.format(name),
+            action='store_const',
+            dest=name,
+            const=default if default is not _empty else False)
+
+
+def make_parser(func_sig, description, epilog, add_nos):
+    '''
+    Given the signature of a function, create an ArgumentParser
+    '''
+    parser = ArgumentParser(description=description, epilog=epilog)
+
+    used_char_args = {'h'}
+
+    # Arange the params so that single-character arguments are first. This
+    # esnures they don't have to get --long versions. sorted is stable, so the
+    # parameters will otherwise still be in relative order.
+    params = sorted(
+        func_sig.parameters.values(),
+        key=lambda param: len(param.name) > 1)
+
+    for param in params:
+        _add_arguments(param, parser, used_char_args, add_nos)
+
+    return parser
+
+
+_DOCSTRING_SPLIT = compile_regex(r'\n\s*-{4,}\s*\n')
+
+
+def parse_docstring(docstring):
+    '''
+    Given a docstring, parse it into a description and epilog part
+    '''
+    if docstring is None:
+        return '', ''
+
+    parts = _DOCSTRING_SPLIT.split(docstring)
+
+    if len(parts) == 1:
+        return docstring, ''
+    elif len(parts) == 2:
+        return parts[0], parts[1]
+    else:
+        raise TooManySplitsError()
+
+
+def autoparse(
+        func=None, *,
+        description=None,
+        epilog=None,
+        add_nos=False,
+        parser=None):
+    '''
+    This decorator converts a function that takes normal arguments into a
+    function which takes a single optional argument, argv, parses it using an
+    argparse.ArgumentParser, and calls the underlying function with the parsed
+    arguments. If it is not given, sys.argv[1:] is used. This is so that the
+    function can be used as a setuptools entry point, as well as a normal main
+    function. sys.argv[1:] is not evaluated until the function is called, to
+    allow injecting different arguments for testing.
+
+    It uses the argument signature of the function to create an
+    ArgumentParser. Parameters without defaults become positional parameters,
+    while parameters *with* defaults become --options. Use annotations to set
+    the type of the parameter.
+
+    The `desctiption` and `epilog` parameters corrospond to the same respective
+    argparse parameters. If no description is given, it defaults to the
+    decorated functions's docstring, if present.
+
+    If add_nos is True, every boolean option (that is, every parameter with a
+    default of True/False or a type of bool) will have a --no- version created
+    as well, which inverts the option. For instance, the --verbose option will
+    have a --no-verbose counterpart. These are not mutually exclusive-
+    whichever one appears last in the argument list will have precedence.
+
+    If a parser is given, it is used instead of one generated from the function
+    signature. In this case, no parser is created; instead, the given parser is
+    used to parse the argv argument. The parser's results' argument names must
+    match up with the parameter names of the decorated function.
+
+    The decorated function is attached to the result as the `func` attribute,
+    and the parser is attached as the `parser` attribute.
+    '''
+
+    # If @autoparse(...) is used instead of @autoparse
+    if func is None:
+        return lambda f: autoparse(
+            f, description=description,
+            epilog=epilog,
+            add_nos=add_nos,
+            parser=parser)
+
+    func_sig = signature(func)
+
+    docstr_description, docstr_epilog = parse_docstring(getdoc(func))
+
+    if parser is None:
+        parser = make_parser(
+            func_sig,
+            description or docstr_description,
+            epilog or docstr_epilog,
+            add_nos)
+
+    @wraps(func)
+    def autoparse_wrapper(argv=None):
+        if argv is None:
+            argv = sys.argv[1:]
+
+        # Get empty argument binding, to fill with parsed arguments. This
+        # object does all the heavy lifting of turning named arguments into
+        # into correctly bound *args and **kwargs.
+        parsed_args = func_sig.bind_partial()
+        parsed_args.arguments.update(vars(parser.parse_args(argv)))
+
+        return func(*parsed_args.args, **parsed_args.kwargs)
+
+    # TODO: attach an updated __signature__ to autoparse_wrapper, just in case.
+
+    # Attach the wrapped function and parser, and return the wrapper.
+    autoparse_wrapper.func = func
+    autoparse_wrapper.parser = parser
+    return autoparse_wrapper
+
+
+@contextmanager
+def smart_open(filename_or_file, *args, **kwargs):
+    '''
+    This context manager allows you to open a filename, if you want to default
+    some already-existing file object, like sys.stdout, which shouldn't be
+    closed at the end of the context. If the filename argument is a str, bytes,
+    or int, the file object is created via a call to open with the given *args
+    and **kwargs, sent to the context, and closed at the end of the context,
+    just like "with open(filename) as f:". If it isn't one of the openable
+    types, the object simply sent to the context unchanged, and left unclosed
+    at the end of the context. Example:
+
+        def work_with_file(name=sys.stdout):
+            with smart_open(name) as f:
+                # Works correctly if name is a str filename or sys.stdout
+                print("Some stuff", file=f)
+                # If it was a filename, f is closed at the end here.
+    '''
+    if isinstance(filename_or_file, (str, bytes, int)):
+        with open(filename_or_file, *args, **kwargs) as file:
+            yield file
+    else:
+        yield filename_or_file
diff --git a/setuptools/_vendor/autocommand/errors.py b/setuptools/_vendor/autocommand/errors.py
new file mode 100644
index 0000000000..2570607399
--- /dev/null
+++ b/setuptools/_vendor/autocommand/errors.py
@@ -0,0 +1,23 @@
+# Copyright 2014-2016 Nathan West
+#
+# This file is part of autocommand.
+#
+# autocommand is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# autocommand is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with autocommand.  If not, see .
+
+
+class AutocommandError(Exception):
+    '''Base class for autocommand exceptions'''
+    pass
+
+# Individual modules will define errors specific to that module.
diff --git a/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/INSTALLER b/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/INSTALLER
new file mode 100644
index 0000000000..5c69047b2e
--- /dev/null
+++ b/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/pkg_resources/_vendor/zipp-3.7.0.dist-info/LICENSE b/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/LICENSE
similarity index 97%
rename from pkg_resources/_vendor/zipp-3.7.0.dist-info/LICENSE
rename to setuptools/_vendor/backports.tarfile-1.2.0.dist-info/LICENSE
index 353924be0e..1bb5a44356 100644
--- a/pkg_resources/_vendor/zipp-3.7.0.dist-info/LICENSE
+++ b/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/LICENSE
@@ -1,5 +1,3 @@
-Copyright Jason R. Coombs
-
 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
diff --git a/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/METADATA b/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/METADATA
new file mode 100644
index 0000000000..db0a2dcdbe
--- /dev/null
+++ b/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/METADATA
@@ -0,0 +1,46 @@
+Metadata-Version: 2.1
+Name: backports.tarfile
+Version: 1.2.0
+Summary: Backport of CPython tarfile module
+Author-email: "Jason R. Coombs" 
+Project-URL: Homepage, https://github.com/jaraco/backports.tarfile
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Provides-Extra: docs
+Requires-Dist: sphinx >=3.5 ; extra == 'docs'
+Requires-Dist: jaraco.packaging >=9.3 ; extra == 'docs'
+Requires-Dist: rst.linker >=1.9 ; extra == 'docs'
+Requires-Dist: furo ; extra == 'docs'
+Requires-Dist: sphinx-lint ; extra == 'docs'
+Provides-Extra: testing
+Requires-Dist: pytest !=8.1.*,>=6 ; extra == 'testing'
+Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'testing'
+Requires-Dist: pytest-cov ; extra == 'testing'
+Requires-Dist: pytest-enabler >=2.2 ; extra == 'testing'
+Requires-Dist: jaraco.test ; extra == 'testing'
+Requires-Dist: pytest !=8.0.* ; extra == 'testing'
+
+.. image:: https://img.shields.io/pypi/v/backports.tarfile.svg
+   :target: https://pypi.org/project/backports.tarfile
+
+.. image:: https://img.shields.io/pypi/pyversions/backports.tarfile.svg
+
+.. image:: https://github.com/jaraco/backports.tarfile/actions/workflows/main.yml/badge.svg
+   :target: https://github.com/jaraco/backports.tarfile/actions?query=workflow%3A%22tests%22
+   :alt: tests
+
+.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json
+    :target: https://github.com/astral-sh/ruff
+    :alt: Ruff
+
+.. .. image:: https://readthedocs.org/projects/backportstarfile/badge/?version=latest
+..    :target: https://backportstarfile.readthedocs.io/en/latest/?badge=latest
+
+.. image:: https://img.shields.io/badge/skeleton-2024-informational
+   :target: https://blog.jaraco.com/skeleton
diff --git a/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/RECORD b/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/RECORD
new file mode 100644
index 0000000000..c7d2c25bc1
--- /dev/null
+++ b/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/RECORD
@@ -0,0 +1,12 @@
+backports.tarfile-1.2.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+backports.tarfile-1.2.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
+backports.tarfile-1.2.0.dist-info/METADATA,sha256=ghXFTq132dxaEIolxr3HK1mZqm9iyUmaRANZQSr6WlE,2020
+backports.tarfile-1.2.0.dist-info/RECORD,,
+backports.tarfile-1.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+backports.tarfile-1.2.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
+backports.tarfile-1.2.0.dist-info/top_level.txt,sha256=cGjaLMOoBR1FK0ApojtzWVmViTtJ7JGIK_HwXiEsvtU,10
+backports/__init__.py,sha256=iOEMwnlORWezdO8-2vxBIPSR37D7JGjluZ8f55vzxls,81
+backports/tarfile/__init__.py,sha256=Pwf2qUIfB0SolJPCKcx3vz3UEu_aids4g4sAfxy94qg,108491
+backports/tarfile/__main__.py,sha256=Yw2oGT1afrz2eBskzdPYL8ReB_3liApmhFkN2EbDmc4,59
+backports/tarfile/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+backports/tarfile/compat/py38.py,sha256=iYkyt_gvWjLzGUTJD9TuTfMMjOk-ersXZmRlvQYN2qE,568
diff --git a/pkg_resources/_vendor/packaging-23.1.dist-info/REQUESTED b/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/REQUESTED
similarity index 100%
rename from pkg_resources/_vendor/packaging-23.1.dist-info/REQUESTED
rename to setuptools/_vendor/backports.tarfile-1.2.0.dist-info/REQUESTED
diff --git a/pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/WHEEL b/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/WHEEL
similarity index 65%
rename from pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/WHEEL
rename to setuptools/_vendor/backports.tarfile-1.2.0.dist-info/WHEEL
index 57e3d840d5..bab98d6758 100644
--- a/pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/WHEEL
+++ b/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/WHEEL
@@ -1,5 +1,5 @@
 Wheel-Version: 1.0
-Generator: bdist_wheel (0.38.4)
+Generator: bdist_wheel (0.43.0)
 Root-Is-Purelib: true
 Tag: py3-none-any
 
diff --git a/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/top_level.txt b/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/top_level.txt
new file mode 100644
index 0000000000..99d2be5b64
--- /dev/null
+++ b/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+backports
diff --git a/setuptools/_vendor/backports/__init__.py b/setuptools/_vendor/backports/__init__.py
new file mode 100644
index 0000000000..0d1f7edf5d
--- /dev/null
+++ b/setuptools/_vendor/backports/__init__.py
@@ -0,0 +1 @@
+__path__ = __import__('pkgutil').extend_path(__path__, __name__)  # type: ignore
diff --git a/setuptools/_vendor/backports/tarfile/__init__.py b/setuptools/_vendor/backports/tarfile/__init__.py
new file mode 100644
index 0000000000..8c16881cb3
--- /dev/null
+++ b/setuptools/_vendor/backports/tarfile/__init__.py
@@ -0,0 +1,2937 @@
+#-------------------------------------------------------------------
+# tarfile.py
+#-------------------------------------------------------------------
+# Copyright (C) 2002 Lars Gustaebel 
+# All rights reserved.
+#
+# 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.
+#
+"""Read from and write to tar format archives.
+"""
+
+version     = "0.9.0"
+__author__  = "Lars Gust\u00e4bel (lars@gustaebel.de)"
+__credits__ = "Gustavo Niemeyer, Niels Gust\u00e4bel, Richard Townsend."
+
+#---------
+# Imports
+#---------
+from builtins import open as bltn_open
+import sys
+import os
+import io
+import shutil
+import stat
+import time
+import struct
+import copy
+import re
+
+from .compat.py38 import removesuffix
+
+try:
+    import pwd
+except ImportError:
+    pwd = None
+try:
+    import grp
+except ImportError:
+    grp = None
+
+# os.symlink on Windows prior to 6.0 raises NotImplementedError
+# OSError (winerror=1314) will be raised if the caller does not hold the
+# SeCreateSymbolicLinkPrivilege privilege
+symlink_exception = (AttributeError, NotImplementedError, OSError)
+
+# from tarfile import *
+__all__ = ["TarFile", "TarInfo", "is_tarfile", "TarError", "ReadError",
+           "CompressionError", "StreamError", "ExtractError", "HeaderError",
+           "ENCODING", "USTAR_FORMAT", "GNU_FORMAT", "PAX_FORMAT",
+           "DEFAULT_FORMAT", "open","fully_trusted_filter", "data_filter",
+           "tar_filter", "FilterError", "AbsoluteLinkError",
+           "OutsideDestinationError", "SpecialFileError", "AbsolutePathError",
+           "LinkOutsideDestinationError"]
+
+
+#---------------------------------------------------------
+# tar constants
+#---------------------------------------------------------
+NUL = b"\0"                     # the null character
+BLOCKSIZE = 512                 # length of processing blocks
+RECORDSIZE = BLOCKSIZE * 20     # length of records
+GNU_MAGIC = b"ustar  \0"        # magic gnu tar string
+POSIX_MAGIC = b"ustar\x0000"    # magic posix tar string
+
+LENGTH_NAME = 100               # maximum length of a filename
+LENGTH_LINK = 100               # maximum length of a linkname
+LENGTH_PREFIX = 155             # maximum length of the prefix field
+
+REGTYPE = b"0"                  # regular file
+AREGTYPE = b"\0"                # regular file
+LNKTYPE = b"1"                  # link (inside tarfile)
+SYMTYPE = b"2"                  # symbolic link
+CHRTYPE = b"3"                  # character special device
+BLKTYPE = b"4"                  # block special device
+DIRTYPE = b"5"                  # directory
+FIFOTYPE = b"6"                 # fifo special device
+CONTTYPE = b"7"                 # contiguous file
+
+GNUTYPE_LONGNAME = b"L"         # GNU tar longname
+GNUTYPE_LONGLINK = b"K"         # GNU tar longlink
+GNUTYPE_SPARSE = b"S"           # GNU tar sparse file
+
+XHDTYPE = b"x"                  # POSIX.1-2001 extended header
+XGLTYPE = b"g"                  # POSIX.1-2001 global header
+SOLARIS_XHDTYPE = b"X"          # Solaris extended header
+
+USTAR_FORMAT = 0                # POSIX.1-1988 (ustar) format
+GNU_FORMAT = 1                  # GNU tar format
+PAX_FORMAT = 2                  # POSIX.1-2001 (pax) format
+DEFAULT_FORMAT = PAX_FORMAT
+
+#---------------------------------------------------------
+# tarfile constants
+#---------------------------------------------------------
+# File types that tarfile supports:
+SUPPORTED_TYPES = (REGTYPE, AREGTYPE, LNKTYPE,
+                   SYMTYPE, DIRTYPE, FIFOTYPE,
+                   CONTTYPE, CHRTYPE, BLKTYPE,
+                   GNUTYPE_LONGNAME, GNUTYPE_LONGLINK,
+                   GNUTYPE_SPARSE)
+
+# File types that will be treated as a regular file.
+REGULAR_TYPES = (REGTYPE, AREGTYPE,
+                 CONTTYPE, GNUTYPE_SPARSE)
+
+# File types that are part of the GNU tar format.
+GNU_TYPES = (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK,
+             GNUTYPE_SPARSE)
+
+# Fields from a pax header that override a TarInfo attribute.
+PAX_FIELDS = ("path", "linkpath", "size", "mtime",
+              "uid", "gid", "uname", "gname")
+
+# Fields from a pax header that are affected by hdrcharset.
+PAX_NAME_FIELDS = {"path", "linkpath", "uname", "gname"}
+
+# Fields in a pax header that are numbers, all other fields
+# are treated as strings.
+PAX_NUMBER_FIELDS = {
+    "atime": float,
+    "ctime": float,
+    "mtime": float,
+    "uid": int,
+    "gid": int,
+    "size": int
+}
+
+#---------------------------------------------------------
+# initialization
+#---------------------------------------------------------
+if os.name == "nt":
+    ENCODING = "utf-8"
+else:
+    ENCODING = sys.getfilesystemencoding()
+
+#---------------------------------------------------------
+# Some useful functions
+#---------------------------------------------------------
+
+def stn(s, length, encoding, errors):
+    """Convert a string to a null-terminated bytes object.
+    """
+    if s is None:
+        raise ValueError("metadata cannot contain None")
+    s = s.encode(encoding, errors)
+    return s[:length] + (length - len(s)) * NUL
+
+def nts(s, encoding, errors):
+    """Convert a null-terminated bytes object to a string.
+    """
+    p = s.find(b"\0")
+    if p != -1:
+        s = s[:p]
+    return s.decode(encoding, errors)
+
+def nti(s):
+    """Convert a number field to a python number.
+    """
+    # There are two possible encodings for a number field, see
+    # itn() below.
+    if s[0] in (0o200, 0o377):
+        n = 0
+        for i in range(len(s) - 1):
+            n <<= 8
+            n += s[i + 1]
+        if s[0] == 0o377:
+            n = -(256 ** (len(s) - 1) - n)
+    else:
+        try:
+            s = nts(s, "ascii", "strict")
+            n = int(s.strip() or "0", 8)
+        except ValueError:
+            raise InvalidHeaderError("invalid header")
+    return n
+
+def itn(n, digits=8, format=DEFAULT_FORMAT):
+    """Convert a python number to a number field.
+    """
+    # POSIX 1003.1-1988 requires numbers to be encoded as a string of
+    # octal digits followed by a null-byte, this allows values up to
+    # (8**(digits-1))-1. GNU tar allows storing numbers greater than
+    # that if necessary. A leading 0o200 or 0o377 byte indicate this
+    # particular encoding, the following digits-1 bytes are a big-endian
+    # base-256 representation. This allows values up to (256**(digits-1))-1.
+    # A 0o200 byte indicates a positive number, a 0o377 byte a negative
+    # number.
+    original_n = n
+    n = int(n)
+    if 0 <= n < 8 ** (digits - 1):
+        s = bytes("%0*o" % (digits - 1, n), "ascii") + NUL
+    elif format == GNU_FORMAT and -256 ** (digits - 1) <= n < 256 ** (digits - 1):
+        if n >= 0:
+            s = bytearray([0o200])
+        else:
+            s = bytearray([0o377])
+            n = 256 ** digits + n
+
+        for i in range(digits - 1):
+            s.insert(1, n & 0o377)
+            n >>= 8
+    else:
+        raise ValueError("overflow in number field")
+
+    return s
+
+def calc_chksums(buf):
+    """Calculate the checksum for a member's header by summing up all
+       characters except for the chksum field which is treated as if
+       it was filled with spaces. According to the GNU tar sources,
+       some tars (Sun and NeXT) calculate chksum with signed char,
+       which will be different if there are chars in the buffer with
+       the high bit set. So we calculate two checksums, unsigned and
+       signed.
+    """
+    unsigned_chksum = 256 + sum(struct.unpack_from("148B8x356B", buf))
+    signed_chksum = 256 + sum(struct.unpack_from("148b8x356b", buf))
+    return unsigned_chksum, signed_chksum
+
+def copyfileobj(src, dst, length=None, exception=OSError, bufsize=None):
+    """Copy length bytes from fileobj src to fileobj dst.
+       If length is None, copy the entire content.
+    """
+    bufsize = bufsize or 16 * 1024
+    if length == 0:
+        return
+    if length is None:
+        shutil.copyfileobj(src, dst, bufsize)
+        return
+
+    blocks, remainder = divmod(length, bufsize)
+    for b in range(blocks):
+        buf = src.read(bufsize)
+        if len(buf) < bufsize:
+            raise exception("unexpected end of data")
+        dst.write(buf)
+
+    if remainder != 0:
+        buf = src.read(remainder)
+        if len(buf) < remainder:
+            raise exception("unexpected end of data")
+        dst.write(buf)
+    return
+
+def _safe_print(s):
+    encoding = getattr(sys.stdout, 'encoding', None)
+    if encoding is not None:
+        s = s.encode(encoding, 'backslashreplace').decode(encoding)
+    print(s, end=' ')
+
+
+class TarError(Exception):
+    """Base exception."""
+    pass
+class ExtractError(TarError):
+    """General exception for extract errors."""
+    pass
+class ReadError(TarError):
+    """Exception for unreadable tar archives."""
+    pass
+class CompressionError(TarError):
+    """Exception for unavailable compression methods."""
+    pass
+class StreamError(TarError):
+    """Exception for unsupported operations on stream-like TarFiles."""
+    pass
+class HeaderError(TarError):
+    """Base exception for header errors."""
+    pass
+class EmptyHeaderError(HeaderError):
+    """Exception for empty headers."""
+    pass
+class TruncatedHeaderError(HeaderError):
+    """Exception for truncated headers."""
+    pass
+class EOFHeaderError(HeaderError):
+    """Exception for end of file headers."""
+    pass
+class InvalidHeaderError(HeaderError):
+    """Exception for invalid headers."""
+    pass
+class SubsequentHeaderError(HeaderError):
+    """Exception for missing and invalid extended headers."""
+    pass
+
+#---------------------------
+# internal stream interface
+#---------------------------
+class _LowLevelFile:
+    """Low-level file object. Supports reading and writing.
+       It is used instead of a regular file object for streaming
+       access.
+    """
+
+    def __init__(self, name, mode):
+        mode = {
+            "r": os.O_RDONLY,
+            "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
+        }[mode]
+        if hasattr(os, "O_BINARY"):
+            mode |= os.O_BINARY
+        self.fd = os.open(name, mode, 0o666)
+
+    def close(self):
+        os.close(self.fd)
+
+    def read(self, size):
+        return os.read(self.fd, size)
+
+    def write(self, s):
+        os.write(self.fd, s)
+
+class _Stream:
+    """Class that serves as an adapter between TarFile and
+       a stream-like object.  The stream-like object only
+       needs to have a read() or write() method that works with bytes,
+       and the method is accessed blockwise.
+       Use of gzip or bzip2 compression is possible.
+       A stream-like object could be for example: sys.stdin.buffer,
+       sys.stdout.buffer, a socket, a tape device etc.
+
+       _Stream is intended to be used only internally.
+    """
+
+    def __init__(self, name, mode, comptype, fileobj, bufsize,
+                 compresslevel):
+        """Construct a _Stream object.
+        """
+        self._extfileobj = True
+        if fileobj is None:
+            fileobj = _LowLevelFile(name, mode)
+            self._extfileobj = False
+
+        if comptype == '*':
+            # Enable transparent compression detection for the
+            # stream interface
+            fileobj = _StreamProxy(fileobj)
+            comptype = fileobj.getcomptype()
+
+        self.name     = name or ""
+        self.mode     = mode
+        self.comptype = comptype
+        self.fileobj  = fileobj
+        self.bufsize  = bufsize
+        self.buf      = b""
+        self.pos      = 0
+        self.closed   = False
+
+        try:
+            if comptype == "gz":
+                try:
+                    import zlib
+                except ImportError:
+                    raise CompressionError("zlib module is not available") from None
+                self.zlib = zlib
+                self.crc = zlib.crc32(b"")
+                if mode == "r":
+                    self.exception = zlib.error
+                    self._init_read_gz()
+                else:
+                    self._init_write_gz(compresslevel)
+
+            elif comptype == "bz2":
+                try:
+                    import bz2
+                except ImportError:
+                    raise CompressionError("bz2 module is not available") from None
+                if mode == "r":
+                    self.dbuf = b""
+                    self.cmp = bz2.BZ2Decompressor()
+                    self.exception = OSError
+                else:
+                    self.cmp = bz2.BZ2Compressor(compresslevel)
+
+            elif comptype == "xz":
+                try:
+                    import lzma
+                except ImportError:
+                    raise CompressionError("lzma module is not available") from None
+                if mode == "r":
+                    self.dbuf = b""
+                    self.cmp = lzma.LZMADecompressor()
+                    self.exception = lzma.LZMAError
+                else:
+                    self.cmp = lzma.LZMACompressor()
+
+            elif comptype != "tar":
+                raise CompressionError("unknown compression type %r" % comptype)
+
+        except:
+            if not self._extfileobj:
+                self.fileobj.close()
+            self.closed = True
+            raise
+
+    def __del__(self):
+        if hasattr(self, "closed") and not self.closed:
+            self.close()
+
+    def _init_write_gz(self, compresslevel):
+        """Initialize for writing with gzip compression.
+        """
+        self.cmp = self.zlib.compressobj(compresslevel,
+                                         self.zlib.DEFLATED,
+                                         -self.zlib.MAX_WBITS,
+                                         self.zlib.DEF_MEM_LEVEL,
+                                         0)
+        timestamp = struct.pack(" self.bufsize:
+            self.fileobj.write(self.buf[:self.bufsize])
+            self.buf = self.buf[self.bufsize:]
+
+    def close(self):
+        """Close the _Stream object. No operation should be
+           done on it afterwards.
+        """
+        if self.closed:
+            return
+
+        self.closed = True
+        try:
+            if self.mode == "w" and self.comptype != "tar":
+                self.buf += self.cmp.flush()
+
+            if self.mode == "w" and self.buf:
+                self.fileobj.write(self.buf)
+                self.buf = b""
+                if self.comptype == "gz":
+                    self.fileobj.write(struct.pack("= 0:
+            blocks, remainder = divmod(pos - self.pos, self.bufsize)
+            for i in range(blocks):
+                self.read(self.bufsize)
+            self.read(remainder)
+        else:
+            raise StreamError("seeking backwards is not allowed")
+        return self.pos
+
+    def read(self, size):
+        """Return the next size number of bytes from the stream."""
+        assert size is not None
+        buf = self._read(size)
+        self.pos += len(buf)
+        return buf
+
+    def _read(self, size):
+        """Return size bytes from the stream.
+        """
+        if self.comptype == "tar":
+            return self.__read(size)
+
+        c = len(self.dbuf)
+        t = [self.dbuf]
+        while c < size:
+            # Skip underlying buffer to avoid unaligned double buffering.
+            if self.buf:
+                buf = self.buf
+                self.buf = b""
+            else:
+                buf = self.fileobj.read(self.bufsize)
+                if not buf:
+                    break
+            try:
+                buf = self.cmp.decompress(buf)
+            except self.exception as e:
+                raise ReadError("invalid compressed data") from e
+            t.append(buf)
+            c += len(buf)
+        t = b"".join(t)
+        self.dbuf = t[size:]
+        return t[:size]
+
+    def __read(self, size):
+        """Return size bytes from stream. If internal buffer is empty,
+           read another block from the stream.
+        """
+        c = len(self.buf)
+        t = [self.buf]
+        while c < size:
+            buf = self.fileobj.read(self.bufsize)
+            if not buf:
+                break
+            t.append(buf)
+            c += len(buf)
+        t = b"".join(t)
+        self.buf = t[size:]
+        return t[:size]
+# class _Stream
+
+class _StreamProxy(object):
+    """Small proxy class that enables transparent compression
+       detection for the Stream interface (mode 'r|*').
+    """
+
+    def __init__(self, fileobj):
+        self.fileobj = fileobj
+        self.buf = self.fileobj.read(BLOCKSIZE)
+
+    def read(self, size):
+        self.read = self.fileobj.read
+        return self.buf
+
+    def getcomptype(self):
+        if self.buf.startswith(b"\x1f\x8b\x08"):
+            return "gz"
+        elif self.buf[0:3] == b"BZh" and self.buf[4:10] == b"1AY&SY":
+            return "bz2"
+        elif self.buf.startswith((b"\x5d\x00\x00\x80", b"\xfd7zXZ")):
+            return "xz"
+        else:
+            return "tar"
+
+    def close(self):
+        self.fileobj.close()
+# class StreamProxy
+
+#------------------------
+# Extraction file object
+#------------------------
+class _FileInFile(object):
+    """A thin wrapper around an existing file object that
+       provides a part of its data as an individual file
+       object.
+    """
+
+    def __init__(self, fileobj, offset, size, name, blockinfo=None):
+        self.fileobj = fileobj
+        self.offset = offset
+        self.size = size
+        self.position = 0
+        self.name = name
+        self.closed = False
+
+        if blockinfo is None:
+            blockinfo = [(0, size)]
+
+        # Construct a map with data and zero blocks.
+        self.map_index = 0
+        self.map = []
+        lastpos = 0
+        realpos = self.offset
+        for offset, size in blockinfo:
+            if offset > lastpos:
+                self.map.append((False, lastpos, offset, None))
+            self.map.append((True, offset, offset + size, realpos))
+            realpos += size
+            lastpos = offset + size
+        if lastpos < self.size:
+            self.map.append((False, lastpos, self.size, None))
+
+    def flush(self):
+        pass
+
+    @property
+    def mode(self):
+        return 'rb'
+
+    def readable(self):
+        return True
+
+    def writable(self):
+        return False
+
+    def seekable(self):
+        return self.fileobj.seekable()
+
+    def tell(self):
+        """Return the current file position.
+        """
+        return self.position
+
+    def seek(self, position, whence=io.SEEK_SET):
+        """Seek to a position in the file.
+        """
+        if whence == io.SEEK_SET:
+            self.position = min(max(position, 0), self.size)
+        elif whence == io.SEEK_CUR:
+            if position < 0:
+                self.position = max(self.position + position, 0)
+            else:
+                self.position = min(self.position + position, self.size)
+        elif whence == io.SEEK_END:
+            self.position = max(min(self.size + position, self.size), 0)
+        else:
+            raise ValueError("Invalid argument")
+        return self.position
+
+    def read(self, size=None):
+        """Read data from the file.
+        """
+        if size is None:
+            size = self.size - self.position
+        else:
+            size = min(size, self.size - self.position)
+
+        buf = b""
+        while size > 0:
+            while True:
+                data, start, stop, offset = self.map[self.map_index]
+                if start <= self.position < stop:
+                    break
+                else:
+                    self.map_index += 1
+                    if self.map_index == len(self.map):
+                        self.map_index = 0
+            length = min(size, stop - self.position)
+            if data:
+                self.fileobj.seek(offset + (self.position - start))
+                b = self.fileobj.read(length)
+                if len(b) != length:
+                    raise ReadError("unexpected end of data")
+                buf += b
+            else:
+                buf += NUL * length
+            size -= length
+            self.position += length
+        return buf
+
+    def readinto(self, b):
+        buf = self.read(len(b))
+        b[:len(buf)] = buf
+        return len(buf)
+
+    def close(self):
+        self.closed = True
+#class _FileInFile
+
+class ExFileObject(io.BufferedReader):
+
+    def __init__(self, tarfile, tarinfo):
+        fileobj = _FileInFile(tarfile.fileobj, tarinfo.offset_data,
+                tarinfo.size, tarinfo.name, tarinfo.sparse)
+        super().__init__(fileobj)
+#class ExFileObject
+
+
+#-----------------------------
+# extraction filters (PEP 706)
+#-----------------------------
+
+class FilterError(TarError):
+    pass
+
+class AbsolutePathError(FilterError):
+    def __init__(self, tarinfo):
+        self.tarinfo = tarinfo
+        super().__init__(f'member {tarinfo.name!r} has an absolute path')
+
+class OutsideDestinationError(FilterError):
+    def __init__(self, tarinfo, path):
+        self.tarinfo = tarinfo
+        self._path = path
+        super().__init__(f'{tarinfo.name!r} would be extracted to {path!r}, '
+                         + 'which is outside the destination')
+
+class SpecialFileError(FilterError):
+    def __init__(self, tarinfo):
+        self.tarinfo = tarinfo
+        super().__init__(f'{tarinfo.name!r} is a special file')
+
+class AbsoluteLinkError(FilterError):
+    def __init__(self, tarinfo):
+        self.tarinfo = tarinfo
+        super().__init__(f'{tarinfo.name!r} is a link to an absolute path')
+
+class LinkOutsideDestinationError(FilterError):
+    def __init__(self, tarinfo, path):
+        self.tarinfo = tarinfo
+        self._path = path
+        super().__init__(f'{tarinfo.name!r} would link to {path!r}, '
+                         + 'which is outside the destination')
+
+def _get_filtered_attrs(member, dest_path, for_data=True):
+    new_attrs = {}
+    name = member.name
+    dest_path = os.path.realpath(dest_path)
+    # Strip leading / (tar's directory separator) from filenames.
+    # Include os.sep (target OS directory separator) as well.
+    if name.startswith(('/', os.sep)):
+        name = new_attrs['name'] = member.path.lstrip('/' + os.sep)
+    if os.path.isabs(name):
+        # Path is absolute even after stripping.
+        # For example, 'C:/foo' on Windows.
+        raise AbsolutePathError(member)
+    # Ensure we stay in the destination
+    target_path = os.path.realpath(os.path.join(dest_path, name))
+    if os.path.commonpath([target_path, dest_path]) != dest_path:
+        raise OutsideDestinationError(member, target_path)
+    # Limit permissions (no high bits, and go-w)
+    mode = member.mode
+    if mode is not None:
+        # Strip high bits & group/other write bits
+        mode = mode & 0o755
+        if for_data:
+            # For data, handle permissions & file types
+            if member.isreg() or member.islnk():
+                if not mode & 0o100:
+                    # Clear executable bits if not executable by user
+                    mode &= ~0o111
+                # Ensure owner can read & write
+                mode |= 0o600
+            elif member.isdir() or member.issym():
+                # Ignore mode for directories & symlinks
+                mode = None
+            else:
+                # Reject special files
+                raise SpecialFileError(member)
+        if mode != member.mode:
+            new_attrs['mode'] = mode
+    if for_data:
+        # Ignore ownership for 'data'
+        if member.uid is not None:
+            new_attrs['uid'] = None
+        if member.gid is not None:
+            new_attrs['gid'] = None
+        if member.uname is not None:
+            new_attrs['uname'] = None
+        if member.gname is not None:
+            new_attrs['gname'] = None
+        # Check link destination for 'data'
+        if member.islnk() or member.issym():
+            if os.path.isabs(member.linkname):
+                raise AbsoluteLinkError(member)
+            if member.issym():
+                target_path = os.path.join(dest_path,
+                                           os.path.dirname(name),
+                                           member.linkname)
+            else:
+                target_path = os.path.join(dest_path,
+                                           member.linkname)
+            target_path = os.path.realpath(target_path)
+            if os.path.commonpath([target_path, dest_path]) != dest_path:
+                raise LinkOutsideDestinationError(member, target_path)
+    return new_attrs
+
+def fully_trusted_filter(member, dest_path):
+    return member
+
+def tar_filter(member, dest_path):
+    new_attrs = _get_filtered_attrs(member, dest_path, False)
+    if new_attrs:
+        return member.replace(**new_attrs, deep=False)
+    return member
+
+def data_filter(member, dest_path):
+    new_attrs = _get_filtered_attrs(member, dest_path, True)
+    if new_attrs:
+        return member.replace(**new_attrs, deep=False)
+    return member
+
+_NAMED_FILTERS = {
+    "fully_trusted": fully_trusted_filter,
+    "tar": tar_filter,
+    "data": data_filter,
+}
+
+#------------------
+# Exported Classes
+#------------------
+
+# Sentinel for replace() defaults, meaning "don't change the attribute"
+_KEEP = object()
+
+class TarInfo(object):
+    """Informational class which holds the details about an
+       archive member given by a tar header block.
+       TarInfo objects are returned by TarFile.getmember(),
+       TarFile.getmembers() and TarFile.gettarinfo() and are
+       usually created internally.
+    """
+
+    __slots__ = dict(
+        name = 'Name of the archive member.',
+        mode = 'Permission bits.',
+        uid = 'User ID of the user who originally stored this member.',
+        gid = 'Group ID of the user who originally stored this member.',
+        size = 'Size in bytes.',
+        mtime = 'Time of last modification.',
+        chksum = 'Header checksum.',
+        type = ('File type. type is usually one of these constants: '
+                'REGTYPE, AREGTYPE, LNKTYPE, SYMTYPE, DIRTYPE, FIFOTYPE, '
+                'CONTTYPE, CHRTYPE, BLKTYPE, GNUTYPE_SPARSE.'),
+        linkname = ('Name of the target file name, which is only present '
+                    'in TarInfo objects of type LNKTYPE and SYMTYPE.'),
+        uname = 'User name.',
+        gname = 'Group name.',
+        devmajor = 'Device major number.',
+        devminor = 'Device minor number.',
+        offset = 'The tar header starts here.',
+        offset_data = "The file's data starts here.",
+        pax_headers = ('A dictionary containing key-value pairs of an '
+                       'associated pax extended header.'),
+        sparse = 'Sparse member information.',
+        _tarfile = None,
+        _sparse_structs = None,
+        _link_target = None,
+        )
+
+    def __init__(self, name=""):
+        """Construct a TarInfo object. name is the optional name
+           of the member.
+        """
+        self.name = name        # member name
+        self.mode = 0o644       # file permissions
+        self.uid = 0            # user id
+        self.gid = 0            # group id
+        self.size = 0           # file size
+        self.mtime = 0          # modification time
+        self.chksum = 0         # header checksum
+        self.type = REGTYPE     # member type
+        self.linkname = ""      # link name
+        self.uname = ""         # user name
+        self.gname = ""         # group name
+        self.devmajor = 0       # device major number
+        self.devminor = 0       # device minor number
+
+        self.offset = 0         # the tar header starts here
+        self.offset_data = 0    # the file's data starts here
+
+        self.sparse = None      # sparse member information
+        self.pax_headers = {}   # pax header information
+
+    @property
+    def tarfile(self):
+        import warnings
+        warnings.warn(
+            'The undocumented "tarfile" attribute of TarInfo objects '
+            + 'is deprecated and will be removed in Python 3.16',
+            DeprecationWarning, stacklevel=2)
+        return self._tarfile
+
+    @tarfile.setter
+    def tarfile(self, tarfile):
+        import warnings
+        warnings.warn(
+            'The undocumented "tarfile" attribute of TarInfo objects '
+            + 'is deprecated and will be removed in Python 3.16',
+            DeprecationWarning, stacklevel=2)
+        self._tarfile = tarfile
+
+    @property
+    def path(self):
+        'In pax headers, "name" is called "path".'
+        return self.name
+
+    @path.setter
+    def path(self, name):
+        self.name = name
+
+    @property
+    def linkpath(self):
+        'In pax headers, "linkname" is called "linkpath".'
+        return self.linkname
+
+    @linkpath.setter
+    def linkpath(self, linkname):
+        self.linkname = linkname
+
+    def __repr__(self):
+        return "<%s %r at %#x>" % (self.__class__.__name__,self.name,id(self))
+
+    def replace(self, *,
+                name=_KEEP, mtime=_KEEP, mode=_KEEP, linkname=_KEEP,
+                uid=_KEEP, gid=_KEEP, uname=_KEEP, gname=_KEEP,
+                deep=True, _KEEP=_KEEP):
+        """Return a deep copy of self with the given attributes replaced.
+        """
+        if deep:
+            result = copy.deepcopy(self)
+        else:
+            result = copy.copy(self)
+        if name is not _KEEP:
+            result.name = name
+        if mtime is not _KEEP:
+            result.mtime = mtime
+        if mode is not _KEEP:
+            result.mode = mode
+        if linkname is not _KEEP:
+            result.linkname = linkname
+        if uid is not _KEEP:
+            result.uid = uid
+        if gid is not _KEEP:
+            result.gid = gid
+        if uname is not _KEEP:
+            result.uname = uname
+        if gname is not _KEEP:
+            result.gname = gname
+        return result
+
+    def get_info(self):
+        """Return the TarInfo's attributes as a dictionary.
+        """
+        if self.mode is None:
+            mode = None
+        else:
+            mode = self.mode & 0o7777
+        info = {
+            "name":     self.name,
+            "mode":     mode,
+            "uid":      self.uid,
+            "gid":      self.gid,
+            "size":     self.size,
+            "mtime":    self.mtime,
+            "chksum":   self.chksum,
+            "type":     self.type,
+            "linkname": self.linkname,
+            "uname":    self.uname,
+            "gname":    self.gname,
+            "devmajor": self.devmajor,
+            "devminor": self.devminor
+        }
+
+        if info["type"] == DIRTYPE and not info["name"].endswith("/"):
+            info["name"] += "/"
+
+        return info
+
+    def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"):
+        """Return a tar header as a string of 512 byte blocks.
+        """
+        info = self.get_info()
+        for name, value in info.items():
+            if value is None:
+                raise ValueError("%s may not be None" % name)
+
+        if format == USTAR_FORMAT:
+            return self.create_ustar_header(info, encoding, errors)
+        elif format == GNU_FORMAT:
+            return self.create_gnu_header(info, encoding, errors)
+        elif format == PAX_FORMAT:
+            return self.create_pax_header(info, encoding)
+        else:
+            raise ValueError("invalid format")
+
+    def create_ustar_header(self, info, encoding, errors):
+        """Return the object as a ustar header block.
+        """
+        info["magic"] = POSIX_MAGIC
+
+        if len(info["linkname"].encode(encoding, errors)) > LENGTH_LINK:
+            raise ValueError("linkname is too long")
+
+        if len(info["name"].encode(encoding, errors)) > LENGTH_NAME:
+            info["prefix"], info["name"] = self._posix_split_name(info["name"], encoding, errors)
+
+        return self._create_header(info, USTAR_FORMAT, encoding, errors)
+
+    def create_gnu_header(self, info, encoding, errors):
+        """Return the object as a GNU header block sequence.
+        """
+        info["magic"] = GNU_MAGIC
+
+        buf = b""
+        if len(info["linkname"].encode(encoding, errors)) > LENGTH_LINK:
+            buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK, encoding, errors)
+
+        if len(info["name"].encode(encoding, errors)) > LENGTH_NAME:
+            buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME, encoding, errors)
+
+        return buf + self._create_header(info, GNU_FORMAT, encoding, errors)
+
+    def create_pax_header(self, info, encoding):
+        """Return the object as a ustar header block. If it cannot be
+           represented this way, prepend a pax extended header sequence
+           with supplement information.
+        """
+        info["magic"] = POSIX_MAGIC
+        pax_headers = self.pax_headers.copy()
+
+        # Test string fields for values that exceed the field length or cannot
+        # be represented in ASCII encoding.
+        for name, hname, length in (
+                ("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK),
+                ("uname", "uname", 32), ("gname", "gname", 32)):
+
+            if hname in pax_headers:
+                # The pax header has priority.
+                continue
+
+            # Try to encode the string as ASCII.
+            try:
+                info[name].encode("ascii", "strict")
+            except UnicodeEncodeError:
+                pax_headers[hname] = info[name]
+                continue
+
+            if len(info[name]) > length:
+                pax_headers[hname] = info[name]
+
+        # Test number fields for values that exceed the field limit or values
+        # that like to be stored as float.
+        for name, digits in (("uid", 8), ("gid", 8), ("size", 12), ("mtime", 12)):
+            needs_pax = False
+
+            val = info[name]
+            val_is_float = isinstance(val, float)
+            val_int = round(val) if val_is_float else val
+            if not 0 <= val_int < 8 ** (digits - 1):
+                # Avoid overflow.
+                info[name] = 0
+                needs_pax = True
+            elif val_is_float:
+                # Put rounded value in ustar header, and full
+                # precision value in pax header.
+                info[name] = val_int
+                needs_pax = True
+
+            # The existing pax header has priority.
+            if needs_pax and name not in pax_headers:
+                pax_headers[name] = str(val)
+
+        # Create a pax extended header if necessary.
+        if pax_headers:
+            buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding)
+        else:
+            buf = b""
+
+        return buf + self._create_header(info, USTAR_FORMAT, "ascii", "replace")
+
+    @classmethod
+    def create_pax_global_header(cls, pax_headers):
+        """Return the object as a pax global header block sequence.
+        """
+        return cls._create_pax_generic_header(pax_headers, XGLTYPE, "utf-8")
+
+    def _posix_split_name(self, name, encoding, errors):
+        """Split a name longer than 100 chars into a prefix
+           and a name part.
+        """
+        components = name.split("/")
+        for i in range(1, len(components)):
+            prefix = "/".join(components[:i])
+            name = "/".join(components[i:])
+            if len(prefix.encode(encoding, errors)) <= LENGTH_PREFIX and \
+                    len(name.encode(encoding, errors)) <= LENGTH_NAME:
+                break
+        else:
+            raise ValueError("name is too long")
+
+        return prefix, name
+
+    @staticmethod
+    def _create_header(info, format, encoding, errors):
+        """Return a header block. info is a dictionary with file
+           information, format must be one of the *_FORMAT constants.
+        """
+        has_device_fields = info.get("type") in (CHRTYPE, BLKTYPE)
+        if has_device_fields:
+            devmajor = itn(info.get("devmajor", 0), 8, format)
+            devminor = itn(info.get("devminor", 0), 8, format)
+        else:
+            devmajor = stn("", 8, encoding, errors)
+            devminor = stn("", 8, encoding, errors)
+
+        # None values in metadata should cause ValueError.
+        # itn()/stn() do this for all fields except type.
+        filetype = info.get("type", REGTYPE)
+        if filetype is None:
+            raise ValueError("TarInfo.type must not be None")
+
+        parts = [
+            stn(info.get("name", ""), 100, encoding, errors),
+            itn(info.get("mode", 0) & 0o7777, 8, format),
+            itn(info.get("uid", 0), 8, format),
+            itn(info.get("gid", 0), 8, format),
+            itn(info.get("size", 0), 12, format),
+            itn(info.get("mtime", 0), 12, format),
+            b"        ", # checksum field
+            filetype,
+            stn(info.get("linkname", ""), 100, encoding, errors),
+            info.get("magic", POSIX_MAGIC),
+            stn(info.get("uname", ""), 32, encoding, errors),
+            stn(info.get("gname", ""), 32, encoding, errors),
+            devmajor,
+            devminor,
+            stn(info.get("prefix", ""), 155, encoding, errors)
+        ]
+
+        buf = struct.pack("%ds" % BLOCKSIZE, b"".join(parts))
+        chksum = calc_chksums(buf[-BLOCKSIZE:])[0]
+        buf = buf[:-364] + bytes("%06o\0" % chksum, "ascii") + buf[-357:]
+        return buf
+
+    @staticmethod
+    def _create_payload(payload):
+        """Return the string payload filled with zero bytes
+           up to the next 512 byte border.
+        """
+        blocks, remainder = divmod(len(payload), BLOCKSIZE)
+        if remainder > 0:
+            payload += (BLOCKSIZE - remainder) * NUL
+        return payload
+
+    @classmethod
+    def _create_gnu_long_header(cls, name, type, encoding, errors):
+        """Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence
+           for name.
+        """
+        name = name.encode(encoding, errors) + NUL
+
+        info = {}
+        info["name"] = "././@LongLink"
+        info["type"] = type
+        info["size"] = len(name)
+        info["magic"] = GNU_MAGIC
+
+        # create extended header + name blocks.
+        return cls._create_header(info, USTAR_FORMAT, encoding, errors) + \
+                cls._create_payload(name)
+
+    @classmethod
+    def _create_pax_generic_header(cls, pax_headers, type, encoding):
+        """Return a POSIX.1-2008 extended or global header sequence
+           that contains a list of keyword, value pairs. The values
+           must be strings.
+        """
+        # Check if one of the fields contains surrogate characters and thereby
+        # forces hdrcharset=BINARY, see _proc_pax() for more information.
+        binary = False
+        for keyword, value in pax_headers.items():
+            try:
+                value.encode("utf-8", "strict")
+            except UnicodeEncodeError:
+                binary = True
+                break
+
+        records = b""
+        if binary:
+            # Put the hdrcharset field at the beginning of the header.
+            records += b"21 hdrcharset=BINARY\n"
+
+        for keyword, value in pax_headers.items():
+            keyword = keyword.encode("utf-8")
+            if binary:
+                # Try to restore the original byte representation of 'value'.
+                # Needless to say, that the encoding must match the string.
+                value = value.encode(encoding, "surrogateescape")
+            else:
+                value = value.encode("utf-8")
+
+            l = len(keyword) + len(value) + 3   # ' ' + '=' + '\n'
+            n = p = 0
+            while True:
+                n = l + len(str(p))
+                if n == p:
+                    break
+                p = n
+            records += bytes(str(p), "ascii") + b" " + keyword + b"=" + value + b"\n"
+
+        # We use a hardcoded "././@PaxHeader" name like star does
+        # instead of the one that POSIX recommends.
+        info = {}
+        info["name"] = "././@PaxHeader"
+        info["type"] = type
+        info["size"] = len(records)
+        info["magic"] = POSIX_MAGIC
+
+        # Create pax header + record blocks.
+        return cls._create_header(info, USTAR_FORMAT, "ascii", "replace") + \
+                cls._create_payload(records)
+
+    @classmethod
+    def frombuf(cls, buf, encoding, errors):
+        """Construct a TarInfo object from a 512 byte bytes object.
+        """
+        if len(buf) == 0:
+            raise EmptyHeaderError("empty header")
+        if len(buf) != BLOCKSIZE:
+            raise TruncatedHeaderError("truncated header")
+        if buf.count(NUL) == BLOCKSIZE:
+            raise EOFHeaderError("end of file header")
+
+        chksum = nti(buf[148:156])
+        if chksum not in calc_chksums(buf):
+            raise InvalidHeaderError("bad checksum")
+
+        obj = cls()
+        obj.name = nts(buf[0:100], encoding, errors)
+        obj.mode = nti(buf[100:108])
+        obj.uid = nti(buf[108:116])
+        obj.gid = nti(buf[116:124])
+        obj.size = nti(buf[124:136])
+        obj.mtime = nti(buf[136:148])
+        obj.chksum = chksum
+        obj.type = buf[156:157]
+        obj.linkname = nts(buf[157:257], encoding, errors)
+        obj.uname = nts(buf[265:297], encoding, errors)
+        obj.gname = nts(buf[297:329], encoding, errors)
+        obj.devmajor = nti(buf[329:337])
+        obj.devminor = nti(buf[337:345])
+        prefix = nts(buf[345:500], encoding, errors)
+
+        # Old V7 tar format represents a directory as a regular
+        # file with a trailing slash.
+        if obj.type == AREGTYPE and obj.name.endswith("/"):
+            obj.type = DIRTYPE
+
+        # The old GNU sparse format occupies some of the unused
+        # space in the buffer for up to 4 sparse structures.
+        # Save them for later processing in _proc_sparse().
+        if obj.type == GNUTYPE_SPARSE:
+            pos = 386
+            structs = []
+            for i in range(4):
+                try:
+                    offset = nti(buf[pos:pos + 12])
+                    numbytes = nti(buf[pos + 12:pos + 24])
+                except ValueError:
+                    break
+                structs.append((offset, numbytes))
+                pos += 24
+            isextended = bool(buf[482])
+            origsize = nti(buf[483:495])
+            obj._sparse_structs = (structs, isextended, origsize)
+
+        # Remove redundant slashes from directories.
+        if obj.isdir():
+            obj.name = obj.name.rstrip("/")
+
+        # Reconstruct a ustar longname.
+        if prefix and obj.type not in GNU_TYPES:
+            obj.name = prefix + "/" + obj.name
+        return obj
+
+    @classmethod
+    def fromtarfile(cls, tarfile):
+        """Return the next TarInfo object from TarFile object
+           tarfile.
+        """
+        buf = tarfile.fileobj.read(BLOCKSIZE)
+        obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors)
+        obj.offset = tarfile.fileobj.tell() - BLOCKSIZE
+        return obj._proc_member(tarfile)
+
+    #--------------------------------------------------------------------------
+    # The following are methods that are called depending on the type of a
+    # member. The entry point is _proc_member() which can be overridden in a
+    # subclass to add custom _proc_*() methods. A _proc_*() method MUST
+    # implement the following
+    # operations:
+    # 1. Set self.offset_data to the position where the data blocks begin,
+    #    if there is data that follows.
+    # 2. Set tarfile.offset to the position where the next member's header will
+    #    begin.
+    # 3. Return self or another valid TarInfo object.
+    def _proc_member(self, tarfile):
+        """Choose the right processing method depending on
+           the type and call it.
+        """
+        if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
+            return self._proc_gnulong(tarfile)
+        elif self.type == GNUTYPE_SPARSE:
+            return self._proc_sparse(tarfile)
+        elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE):
+            return self._proc_pax(tarfile)
+        else:
+            return self._proc_builtin(tarfile)
+
+    def _proc_builtin(self, tarfile):
+        """Process a builtin type or an unknown type which
+           will be treated as a regular file.
+        """
+        self.offset_data = tarfile.fileobj.tell()
+        offset = self.offset_data
+        if self.isreg() or self.type not in SUPPORTED_TYPES:
+            # Skip the following data blocks.
+            offset += self._block(self.size)
+        tarfile.offset = offset
+
+        # Patch the TarInfo object with saved global
+        # header information.
+        self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors)
+
+        # Remove redundant slashes from directories. This is to be consistent
+        # with frombuf().
+        if self.isdir():
+            self.name = self.name.rstrip("/")
+
+        return self
+
+    def _proc_gnulong(self, tarfile):
+        """Process the blocks that hold a GNU longname
+           or longlink member.
+        """
+        buf = tarfile.fileobj.read(self._block(self.size))
+
+        # Fetch the next header and process it.
+        try:
+            next = self.fromtarfile(tarfile)
+        except HeaderError as e:
+            raise SubsequentHeaderError(str(e)) from None
+
+        # Patch the TarInfo object from the next header with
+        # the longname information.
+        next.offset = self.offset
+        if self.type == GNUTYPE_LONGNAME:
+            next.name = nts(buf, tarfile.encoding, tarfile.errors)
+        elif self.type == GNUTYPE_LONGLINK:
+            next.linkname = nts(buf, tarfile.encoding, tarfile.errors)
+
+        # Remove redundant slashes from directories. This is to be consistent
+        # with frombuf().
+        if next.isdir():
+            next.name = removesuffix(next.name, "/")
+
+        return next
+
+    def _proc_sparse(self, tarfile):
+        """Process a GNU sparse header plus extra headers.
+        """
+        # We already collected some sparse structures in frombuf().
+        structs, isextended, origsize = self._sparse_structs
+        del self._sparse_structs
+
+        # Collect sparse structures from extended header blocks.
+        while isextended:
+            buf = tarfile.fileobj.read(BLOCKSIZE)
+            pos = 0
+            for i in range(21):
+                try:
+                    offset = nti(buf[pos:pos + 12])
+                    numbytes = nti(buf[pos + 12:pos + 24])
+                except ValueError:
+                    break
+                if offset and numbytes:
+                    structs.append((offset, numbytes))
+                pos += 24
+            isextended = bool(buf[504])
+        self.sparse = structs
+
+        self.offset_data = tarfile.fileobj.tell()
+        tarfile.offset = self.offset_data + self._block(self.size)
+        self.size = origsize
+        return self
+
+    def _proc_pax(self, tarfile):
+        """Process an extended or global header as described in
+           POSIX.1-2008.
+        """
+        # Read the header information.
+        buf = tarfile.fileobj.read(self._block(self.size))
+
+        # A pax header stores supplemental information for either
+        # the following file (extended) or all following files
+        # (global).
+        if self.type == XGLTYPE:
+            pax_headers = tarfile.pax_headers
+        else:
+            pax_headers = tarfile.pax_headers.copy()
+
+        # Check if the pax header contains a hdrcharset field. This tells us
+        # the encoding of the path, linkpath, uname and gname fields. Normally,
+        # these fields are UTF-8 encoded but since POSIX.1-2008 tar
+        # implementations are allowed to store them as raw binary strings if
+        # the translation to UTF-8 fails.
+        match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf)
+        if match is not None:
+            pax_headers["hdrcharset"] = match.group(1).decode("utf-8")
+
+        # For the time being, we don't care about anything other than "BINARY".
+        # The only other value that is currently allowed by the standard is
+        # "ISO-IR 10646 2000 UTF-8" in other words UTF-8.
+        hdrcharset = pax_headers.get("hdrcharset")
+        if hdrcharset == "BINARY":
+            encoding = tarfile.encoding
+        else:
+            encoding = "utf-8"
+
+        # Parse pax header information. A record looks like that:
+        # "%d %s=%s\n" % (length, keyword, value). length is the size
+        # of the complete record including the length field itself and
+        # the newline. keyword and value are both UTF-8 encoded strings.
+        regex = re.compile(br"(\d+) ([^=]+)=")
+        pos = 0
+        while match := regex.match(buf, pos):
+            length, keyword = match.groups()
+            length = int(length)
+            if length == 0:
+                raise InvalidHeaderError("invalid header")
+            value = buf[match.end(2) + 1:match.start(1) + length - 1]
+
+            # Normally, we could just use "utf-8" as the encoding and "strict"
+            # as the error handler, but we better not take the risk. For
+            # example, GNU tar <= 1.23 is known to store filenames it cannot
+            # translate to UTF-8 as raw strings (unfortunately without a
+            # hdrcharset=BINARY header).
+            # We first try the strict standard encoding, and if that fails we
+            # fall back on the user's encoding and error handler.
+            keyword = self._decode_pax_field(keyword, "utf-8", "utf-8",
+                    tarfile.errors)
+            if keyword in PAX_NAME_FIELDS:
+                value = self._decode_pax_field(value, encoding, tarfile.encoding,
+                        tarfile.errors)
+            else:
+                value = self._decode_pax_field(value, "utf-8", "utf-8",
+                        tarfile.errors)
+
+            pax_headers[keyword] = value
+            pos += length
+
+        # Fetch the next header.
+        try:
+            next = self.fromtarfile(tarfile)
+        except HeaderError as e:
+            raise SubsequentHeaderError(str(e)) from None
+
+        # Process GNU sparse information.
+        if "GNU.sparse.map" in pax_headers:
+            # GNU extended sparse format version 0.1.
+            self._proc_gnusparse_01(next, pax_headers)
+
+        elif "GNU.sparse.size" in pax_headers:
+            # GNU extended sparse format version 0.0.
+            self._proc_gnusparse_00(next, pax_headers, buf)
+
+        elif pax_headers.get("GNU.sparse.major") == "1" and pax_headers.get("GNU.sparse.minor") == "0":
+            # GNU extended sparse format version 1.0.
+            self._proc_gnusparse_10(next, pax_headers, tarfile)
+
+        if self.type in (XHDTYPE, SOLARIS_XHDTYPE):
+            # Patch the TarInfo object with the extended header info.
+            next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors)
+            next.offset = self.offset
+
+            if "size" in pax_headers:
+                # If the extended header replaces the size field,
+                # we need to recalculate the offset where the next
+                # header starts.
+                offset = next.offset_data
+                if next.isreg() or next.type not in SUPPORTED_TYPES:
+                    offset += next._block(next.size)
+                tarfile.offset = offset
+
+        return next
+
+    def _proc_gnusparse_00(self, next, pax_headers, buf):
+        """Process a GNU tar extended sparse header, version 0.0.
+        """
+        offsets = []
+        for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf):
+            offsets.append(int(match.group(1)))
+        numbytes = []
+        for match in re.finditer(br"\d+ GNU.sparse.numbytes=(\d+)\n", buf):
+            numbytes.append(int(match.group(1)))
+        next.sparse = list(zip(offsets, numbytes))
+
+    def _proc_gnusparse_01(self, next, pax_headers):
+        """Process a GNU tar extended sparse header, version 0.1.
+        """
+        sparse = [int(x) for x in pax_headers["GNU.sparse.map"].split(",")]
+        next.sparse = list(zip(sparse[::2], sparse[1::2]))
+
+    def _proc_gnusparse_10(self, next, pax_headers, tarfile):
+        """Process a GNU tar extended sparse header, version 1.0.
+        """
+        fields = None
+        sparse = []
+        buf = tarfile.fileobj.read(BLOCKSIZE)
+        fields, buf = buf.split(b"\n", 1)
+        fields = int(fields)
+        while len(sparse) < fields * 2:
+            if b"\n" not in buf:
+                buf += tarfile.fileobj.read(BLOCKSIZE)
+            number, buf = buf.split(b"\n", 1)
+            sparse.append(int(number))
+        next.offset_data = tarfile.fileobj.tell()
+        next.sparse = list(zip(sparse[::2], sparse[1::2]))
+
+    def _apply_pax_info(self, pax_headers, encoding, errors):
+        """Replace fields with supplemental information from a previous
+           pax extended or global header.
+        """
+        for keyword, value in pax_headers.items():
+            if keyword == "GNU.sparse.name":
+                setattr(self, "path", value)
+            elif keyword == "GNU.sparse.size":
+                setattr(self, "size", int(value))
+            elif keyword == "GNU.sparse.realsize":
+                setattr(self, "size", int(value))
+            elif keyword in PAX_FIELDS:
+                if keyword in PAX_NUMBER_FIELDS:
+                    try:
+                        value = PAX_NUMBER_FIELDS[keyword](value)
+                    except ValueError:
+                        value = 0
+                if keyword == "path":
+                    value = value.rstrip("/")
+                setattr(self, keyword, value)
+
+        self.pax_headers = pax_headers.copy()
+
+    def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors):
+        """Decode a single field from a pax record.
+        """
+        try:
+            return value.decode(encoding, "strict")
+        except UnicodeDecodeError:
+            return value.decode(fallback_encoding, fallback_errors)
+
+    def _block(self, count):
+        """Round up a byte count by BLOCKSIZE and return it,
+           e.g. _block(834) => 1024.
+        """
+        blocks, remainder = divmod(count, BLOCKSIZE)
+        if remainder:
+            blocks += 1
+        return blocks * BLOCKSIZE
+
+    def isreg(self):
+        'Return True if the Tarinfo object is a regular file.'
+        return self.type in REGULAR_TYPES
+
+    def isfile(self):
+        'Return True if the Tarinfo object is a regular file.'
+        return self.isreg()
+
+    def isdir(self):
+        'Return True if it is a directory.'
+        return self.type == DIRTYPE
+
+    def issym(self):
+        'Return True if it is a symbolic link.'
+        return self.type == SYMTYPE
+
+    def islnk(self):
+        'Return True if it is a hard link.'
+        return self.type == LNKTYPE
+
+    def ischr(self):
+        'Return True if it is a character device.'
+        return self.type == CHRTYPE
+
+    def isblk(self):
+        'Return True if it is a block device.'
+        return self.type == BLKTYPE
+
+    def isfifo(self):
+        'Return True if it is a FIFO.'
+        return self.type == FIFOTYPE
+
+    def issparse(self):
+        return self.sparse is not None
+
+    def isdev(self):
+        'Return True if it is one of character device, block device or FIFO.'
+        return self.type in (CHRTYPE, BLKTYPE, FIFOTYPE)
+# class TarInfo
+
+class TarFile(object):
+    """The TarFile Class provides an interface to tar archives.
+    """
+
+    debug = 0                   # May be set from 0 (no msgs) to 3 (all msgs)
+
+    dereference = False         # If true, add content of linked file to the
+                                # tar file, else the link.
+
+    ignore_zeros = False        # If true, skips empty or invalid blocks and
+                                # continues processing.
+
+    errorlevel = 1              # If 0, fatal errors only appear in debug
+                                # messages (if debug >= 0). If > 0, errors
+                                # are passed to the caller as exceptions.
+
+    format = DEFAULT_FORMAT     # The format to use when creating an archive.
+
+    encoding = ENCODING         # Encoding for 8-bit character strings.
+
+    errors = None               # Error handler for unicode conversion.
+
+    tarinfo = TarInfo           # The default TarInfo class to use.
+
+    fileobject = ExFileObject   # The file-object for extractfile().
+
+    extraction_filter = None    # The default filter for extraction.
+
+    def __init__(self, name=None, mode="r", fileobj=None, format=None,
+            tarinfo=None, dereference=None, ignore_zeros=None, encoding=None,
+            errors="surrogateescape", pax_headers=None, debug=None,
+            errorlevel=None, copybufsize=None, stream=False):
+        """Open an (uncompressed) tar archive 'name'. 'mode' is either 'r' to
+           read from an existing archive, 'a' to append data to an existing
+           file or 'w' to create a new file overwriting an existing one. 'mode'
+           defaults to 'r'.
+           If 'fileobj' is given, it is used for reading or writing data. If it
+           can be determined, 'mode' is overridden by 'fileobj's mode.
+           'fileobj' is not closed, when TarFile is closed.
+        """
+        modes = {"r": "rb", "a": "r+b", "w": "wb", "x": "xb"}
+        if mode not in modes:
+            raise ValueError("mode must be 'r', 'a', 'w' or 'x'")
+        self.mode = mode
+        self._mode = modes[mode]
+
+        if not fileobj:
+            if self.mode == "a" and not os.path.exists(name):
+                # Create nonexistent files in append mode.
+                self.mode = "w"
+                self._mode = "wb"
+            fileobj = bltn_open(name, self._mode)
+            self._extfileobj = False
+        else:
+            if (name is None and hasattr(fileobj, "name") and
+                isinstance(fileobj.name, (str, bytes))):
+                name = fileobj.name
+            if hasattr(fileobj, "mode"):
+                self._mode = fileobj.mode
+            self._extfileobj = True
+        self.name = os.path.abspath(name) if name else None
+        self.fileobj = fileobj
+
+        self.stream = stream
+
+        # Init attributes.
+        if format is not None:
+            self.format = format
+        if tarinfo is not None:
+            self.tarinfo = tarinfo
+        if dereference is not None:
+            self.dereference = dereference
+        if ignore_zeros is not None:
+            self.ignore_zeros = ignore_zeros
+        if encoding is not None:
+            self.encoding = encoding
+        self.errors = errors
+
+        if pax_headers is not None and self.format == PAX_FORMAT:
+            self.pax_headers = pax_headers
+        else:
+            self.pax_headers = {}
+
+        if debug is not None:
+            self.debug = debug
+        if errorlevel is not None:
+            self.errorlevel = errorlevel
+
+        # Init datastructures.
+        self.copybufsize = copybufsize
+        self.closed = False
+        self.members = []       # list of members as TarInfo objects
+        self._loaded = False    # flag if all members have been read
+        self.offset = self.fileobj.tell()
+                                # current position in the archive file
+        self.inodes = {}        # dictionary caching the inodes of
+                                # archive members already added
+
+        try:
+            if self.mode == "r":
+                self.firstmember = None
+                self.firstmember = self.next()
+
+            if self.mode == "a":
+                # Move to the end of the archive,
+                # before the first empty block.
+                while True:
+                    self.fileobj.seek(self.offset)
+                    try:
+                        tarinfo = self.tarinfo.fromtarfile(self)
+                        self.members.append(tarinfo)
+                    except EOFHeaderError:
+                        self.fileobj.seek(self.offset)
+                        break
+                    except HeaderError as e:
+                        raise ReadError(str(e)) from None
+
+            if self.mode in ("a", "w", "x"):
+                self._loaded = True
+
+                if self.pax_headers:
+                    buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy())
+                    self.fileobj.write(buf)
+                    self.offset += len(buf)
+        except:
+            if not self._extfileobj:
+                self.fileobj.close()
+            self.closed = True
+            raise
+
+    #--------------------------------------------------------------------------
+    # Below are the classmethods which act as alternate constructors to the
+    # TarFile class. The open() method is the only one that is needed for
+    # public use; it is the "super"-constructor and is able to select an
+    # adequate "sub"-constructor for a particular compression using the mapping
+    # from OPEN_METH.
+    #
+    # This concept allows one to subclass TarFile without losing the comfort of
+    # the super-constructor. A sub-constructor is registered and made available
+    # by adding it to the mapping in OPEN_METH.
+
+    @classmethod
+    def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs):
+        r"""Open a tar archive for reading, writing or appending. Return
+           an appropriate TarFile class.
+
+           mode:
+           'r' or 'r:\*' open for reading with transparent compression
+           'r:'         open for reading exclusively uncompressed
+           'r:gz'       open for reading with gzip compression
+           'r:bz2'      open for reading with bzip2 compression
+           'r:xz'       open for reading with lzma compression
+           'a' or 'a:'  open for appending, creating the file if necessary
+           'w' or 'w:'  open for writing without compression
+           'w:gz'       open for writing with gzip compression
+           'w:bz2'      open for writing with bzip2 compression
+           'w:xz'       open for writing with lzma compression
+
+           'x' or 'x:'  create a tarfile exclusively without compression, raise
+                        an exception if the file is already created
+           'x:gz'       create a gzip compressed tarfile, raise an exception
+                        if the file is already created
+           'x:bz2'      create a bzip2 compressed tarfile, raise an exception
+                        if the file is already created
+           'x:xz'       create an lzma compressed tarfile, raise an exception
+                        if the file is already created
+
+           'r|\*'        open a stream of tar blocks with transparent compression
+           'r|'         open an uncompressed stream of tar blocks for reading
+           'r|gz'       open a gzip compressed stream of tar blocks
+           'r|bz2'      open a bzip2 compressed stream of tar blocks
+           'r|xz'       open an lzma compressed stream of tar blocks
+           'w|'         open an uncompressed stream for writing
+           'w|gz'       open a gzip compressed stream for writing
+           'w|bz2'      open a bzip2 compressed stream for writing
+           'w|xz'       open an lzma compressed stream for writing
+        """
+
+        if not name and not fileobj:
+            raise ValueError("nothing to open")
+
+        if mode in ("r", "r:*"):
+            # Find out which *open() is appropriate for opening the file.
+            def not_compressed(comptype):
+                return cls.OPEN_METH[comptype] == 'taropen'
+            error_msgs = []
+            for comptype in sorted(cls.OPEN_METH, key=not_compressed):
+                func = getattr(cls, cls.OPEN_METH[comptype])
+                if fileobj is not None:
+                    saved_pos = fileobj.tell()
+                try:
+                    return func(name, "r", fileobj, **kwargs)
+                except (ReadError, CompressionError) as e:
+                    error_msgs.append(f'- method {comptype}: {e!r}')
+                    if fileobj is not None:
+                        fileobj.seek(saved_pos)
+                    continue
+            error_msgs_summary = '\n'.join(error_msgs)
+            raise ReadError(f"file could not be opened successfully:\n{error_msgs_summary}")
+
+        elif ":" in mode:
+            filemode, comptype = mode.split(":", 1)
+            filemode = filemode or "r"
+            comptype = comptype or "tar"
+
+            # Select the *open() function according to
+            # given compression.
+            if comptype in cls.OPEN_METH:
+                func = getattr(cls, cls.OPEN_METH[comptype])
+            else:
+                raise CompressionError("unknown compression type %r" % comptype)
+            return func(name, filemode, fileobj, **kwargs)
+
+        elif "|" in mode:
+            filemode, comptype = mode.split("|", 1)
+            filemode = filemode or "r"
+            comptype = comptype or "tar"
+
+            if filemode not in ("r", "w"):
+                raise ValueError("mode must be 'r' or 'w'")
+
+            compresslevel = kwargs.pop("compresslevel", 9)
+            stream = _Stream(name, filemode, comptype, fileobj, bufsize,
+                             compresslevel)
+            try:
+                t = cls(name, filemode, stream, **kwargs)
+            except:
+                stream.close()
+                raise
+            t._extfileobj = False
+            return t
+
+        elif mode in ("a", "w", "x"):
+            return cls.taropen(name, mode, fileobj, **kwargs)
+
+        raise ValueError("undiscernible mode")
+
+    @classmethod
+    def taropen(cls, name, mode="r", fileobj=None, **kwargs):
+        """Open uncompressed tar archive name for reading or writing.
+        """
+        if mode not in ("r", "a", "w", "x"):
+            raise ValueError("mode must be 'r', 'a', 'w' or 'x'")
+        return cls(name, mode, fileobj, **kwargs)
+
+    @classmethod
+    def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
+        """Open gzip compressed tar archive name for reading or writing.
+           Appending is not allowed.
+        """
+        if mode not in ("r", "w", "x"):
+            raise ValueError("mode must be 'r', 'w' or 'x'")
+
+        try:
+            from gzip import GzipFile
+        except ImportError:
+            raise CompressionError("gzip module is not available") from None
+
+        try:
+            fileobj = GzipFile(name, mode + "b", compresslevel, fileobj)
+        except OSError as e:
+            if fileobj is not None and mode == 'r':
+                raise ReadError("not a gzip file") from e
+            raise
+
+        try:
+            t = cls.taropen(name, mode, fileobj, **kwargs)
+        except OSError as e:
+            fileobj.close()
+            if mode == 'r':
+                raise ReadError("not a gzip file") from e
+            raise
+        except:
+            fileobj.close()
+            raise
+        t._extfileobj = False
+        return t
+
+    @classmethod
+    def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
+        """Open bzip2 compressed tar archive name for reading or writing.
+           Appending is not allowed.
+        """
+        if mode not in ("r", "w", "x"):
+            raise ValueError("mode must be 'r', 'w' or 'x'")
+
+        try:
+            from bz2 import BZ2File
+        except ImportError:
+            raise CompressionError("bz2 module is not available") from None
+
+        fileobj = BZ2File(fileobj or name, mode, compresslevel=compresslevel)
+
+        try:
+            t = cls.taropen(name, mode, fileobj, **kwargs)
+        except (OSError, EOFError) as e:
+            fileobj.close()
+            if mode == 'r':
+                raise ReadError("not a bzip2 file") from e
+            raise
+        except:
+            fileobj.close()
+            raise
+        t._extfileobj = False
+        return t
+
+    @classmethod
+    def xzopen(cls, name, mode="r", fileobj=None, preset=None, **kwargs):
+        """Open lzma compressed tar archive name for reading or writing.
+           Appending is not allowed.
+        """
+        if mode not in ("r", "w", "x"):
+            raise ValueError("mode must be 'r', 'w' or 'x'")
+
+        try:
+            from lzma import LZMAFile, LZMAError
+        except ImportError:
+            raise CompressionError("lzma module is not available") from None
+
+        fileobj = LZMAFile(fileobj or name, mode, preset=preset)
+
+        try:
+            t = cls.taropen(name, mode, fileobj, **kwargs)
+        except (LZMAError, EOFError) as e:
+            fileobj.close()
+            if mode == 'r':
+                raise ReadError("not an lzma file") from e
+            raise
+        except:
+            fileobj.close()
+            raise
+        t._extfileobj = False
+        return t
+
+    # All *open() methods are registered here.
+    OPEN_METH = {
+        "tar": "taropen",   # uncompressed tar
+        "gz":  "gzopen",    # gzip compressed tar
+        "bz2": "bz2open",   # bzip2 compressed tar
+        "xz":  "xzopen"     # lzma compressed tar
+    }
+
+    #--------------------------------------------------------------------------
+    # The public methods which TarFile provides:
+
+    def close(self):
+        """Close the TarFile. In write-mode, two finishing zero blocks are
+           appended to the archive.
+        """
+        if self.closed:
+            return
+
+        self.closed = True
+        try:
+            if self.mode in ("a", "w", "x"):
+                self.fileobj.write(NUL * (BLOCKSIZE * 2))
+                self.offset += (BLOCKSIZE * 2)
+                # fill up the end with zero-blocks
+                # (like option -b20 for tar does)
+                blocks, remainder = divmod(self.offset, RECORDSIZE)
+                if remainder > 0:
+                    self.fileobj.write(NUL * (RECORDSIZE - remainder))
+        finally:
+            if not self._extfileobj:
+                self.fileobj.close()
+
+    def getmember(self, name):
+        """Return a TarInfo object for member 'name'. If 'name' can not be
+           found in the archive, KeyError is raised. If a member occurs more
+           than once in the archive, its last occurrence is assumed to be the
+           most up-to-date version.
+        """
+        tarinfo = self._getmember(name.rstrip('/'))
+        if tarinfo is None:
+            raise KeyError("filename %r not found" % name)
+        return tarinfo
+
+    def getmembers(self):
+        """Return the members of the archive as a list of TarInfo objects. The
+           list has the same order as the members in the archive.
+        """
+        self._check()
+        if not self._loaded:    # if we want to obtain a list of
+            self._load()        # all members, we first have to
+                                # scan the whole archive.
+        return self.members
+
+    def getnames(self):
+        """Return the members of the archive as a list of their names. It has
+           the same order as the list returned by getmembers().
+        """
+        return [tarinfo.name for tarinfo in self.getmembers()]
+
+    def gettarinfo(self, name=None, arcname=None, fileobj=None):
+        """Create a TarInfo object from the result of os.stat or equivalent
+           on an existing file. The file is either named by 'name', or
+           specified as a file object 'fileobj' with a file descriptor. If
+           given, 'arcname' specifies an alternative name for the file in the
+           archive, otherwise, the name is taken from the 'name' attribute of
+           'fileobj', or the 'name' argument. The name should be a text
+           string.
+        """
+        self._check("awx")
+
+        # When fileobj is given, replace name by
+        # fileobj's real name.
+        if fileobj is not None:
+            name = fileobj.name
+
+        # Building the name of the member in the archive.
+        # Backward slashes are converted to forward slashes,
+        # Absolute paths are turned to relative paths.
+        if arcname is None:
+            arcname = name
+        drv, arcname = os.path.splitdrive(arcname)
+        arcname = arcname.replace(os.sep, "/")
+        arcname = arcname.lstrip("/")
+
+        # Now, fill the TarInfo object with
+        # information specific for the file.
+        tarinfo = self.tarinfo()
+        tarinfo._tarfile = self  # To be removed in 3.16.
+
+        # Use os.stat or os.lstat, depending on if symlinks shall be resolved.
+        if fileobj is None:
+            if not self.dereference:
+                statres = os.lstat(name)
+            else:
+                statres = os.stat(name)
+        else:
+            statres = os.fstat(fileobj.fileno())
+        linkname = ""
+
+        stmd = statres.st_mode
+        if stat.S_ISREG(stmd):
+            inode = (statres.st_ino, statres.st_dev)
+            if not self.dereference and statres.st_nlink > 1 and \
+                    inode in self.inodes and arcname != self.inodes[inode]:
+                # Is it a hardlink to an already
+                # archived file?
+                type = LNKTYPE
+                linkname = self.inodes[inode]
+            else:
+                # The inode is added only if its valid.
+                # For win32 it is always 0.
+                type = REGTYPE
+                if inode[0]:
+                    self.inodes[inode] = arcname
+        elif stat.S_ISDIR(stmd):
+            type = DIRTYPE
+        elif stat.S_ISFIFO(stmd):
+            type = FIFOTYPE
+        elif stat.S_ISLNK(stmd):
+            type = SYMTYPE
+            linkname = os.readlink(name)
+        elif stat.S_ISCHR(stmd):
+            type = CHRTYPE
+        elif stat.S_ISBLK(stmd):
+            type = BLKTYPE
+        else:
+            return None
+
+        # Fill the TarInfo object with all
+        # information we can get.
+        tarinfo.name = arcname
+        tarinfo.mode = stmd
+        tarinfo.uid = statres.st_uid
+        tarinfo.gid = statres.st_gid
+        if type == REGTYPE:
+            tarinfo.size = statres.st_size
+        else:
+            tarinfo.size = 0
+        tarinfo.mtime = statres.st_mtime
+        tarinfo.type = type
+        tarinfo.linkname = linkname
+        if pwd:
+            try:
+                tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0]
+            except KeyError:
+                pass
+        if grp:
+            try:
+                tarinfo.gname = grp.getgrgid(tarinfo.gid)[0]
+            except KeyError:
+                pass
+
+        if type in (CHRTYPE, BLKTYPE):
+            if hasattr(os, "major") and hasattr(os, "minor"):
+                tarinfo.devmajor = os.major(statres.st_rdev)
+                tarinfo.devminor = os.minor(statres.st_rdev)
+        return tarinfo
+
+    def list(self, verbose=True, *, members=None):
+        """Print a table of contents to sys.stdout. If 'verbose' is False, only
+           the names of the members are printed. If it is True, an 'ls -l'-like
+           output is produced. 'members' is optional and must be a subset of the
+           list returned by getmembers().
+        """
+        # Convert tarinfo type to stat type.
+        type2mode = {REGTYPE: stat.S_IFREG, SYMTYPE: stat.S_IFLNK,
+                     FIFOTYPE: stat.S_IFIFO, CHRTYPE: stat.S_IFCHR,
+                     DIRTYPE: stat.S_IFDIR, BLKTYPE: stat.S_IFBLK}
+        self._check()
+
+        if members is None:
+            members = self
+        for tarinfo in members:
+            if verbose:
+                if tarinfo.mode is None:
+                    _safe_print("??????????")
+                else:
+                    modetype = type2mode.get(tarinfo.type, 0)
+                    _safe_print(stat.filemode(modetype | tarinfo.mode))
+                _safe_print("%s/%s" % (tarinfo.uname or tarinfo.uid,
+                                       tarinfo.gname or tarinfo.gid))
+                if tarinfo.ischr() or tarinfo.isblk():
+                    _safe_print("%10s" %
+                            ("%d,%d" % (tarinfo.devmajor, tarinfo.devminor)))
+                else:
+                    _safe_print("%10d" % tarinfo.size)
+                if tarinfo.mtime is None:
+                    _safe_print("????-??-?? ??:??:??")
+                else:
+                    _safe_print("%d-%02d-%02d %02d:%02d:%02d" \
+                                % time.localtime(tarinfo.mtime)[:6])
+
+            _safe_print(tarinfo.name + ("/" if tarinfo.isdir() else ""))
+
+            if verbose:
+                if tarinfo.issym():
+                    _safe_print("-> " + tarinfo.linkname)
+                if tarinfo.islnk():
+                    _safe_print("link to " + tarinfo.linkname)
+            print()
+
+    def add(self, name, arcname=None, recursive=True, *, filter=None):
+        """Add the file 'name' to the archive. 'name' may be any type of file
+           (directory, fifo, symbolic link, etc.). If given, 'arcname'
+           specifies an alternative name for the file in the archive.
+           Directories are added recursively by default. This can be avoided by
+           setting 'recursive' to False. 'filter' is a function
+           that expects a TarInfo object argument and returns the changed
+           TarInfo object, if it returns None the TarInfo object will be
+           excluded from the archive.
+        """
+        self._check("awx")
+
+        if arcname is None:
+            arcname = name
+
+        # Skip if somebody tries to archive the archive...
+        if self.name is not None and os.path.abspath(name) == self.name:
+            self._dbg(2, "tarfile: Skipped %r" % name)
+            return
+
+        self._dbg(1, name)
+
+        # Create a TarInfo object from the file.
+        tarinfo = self.gettarinfo(name, arcname)
+
+        if tarinfo is None:
+            self._dbg(1, "tarfile: Unsupported type %r" % name)
+            return
+
+        # Change or exclude the TarInfo object.
+        if filter is not None:
+            tarinfo = filter(tarinfo)
+            if tarinfo is None:
+                self._dbg(2, "tarfile: Excluded %r" % name)
+                return
+
+        # Append the tar header and data to the archive.
+        if tarinfo.isreg():
+            with bltn_open(name, "rb") as f:
+                self.addfile(tarinfo, f)
+
+        elif tarinfo.isdir():
+            self.addfile(tarinfo)
+            if recursive:
+                for f in sorted(os.listdir(name)):
+                    self.add(os.path.join(name, f), os.path.join(arcname, f),
+                            recursive, filter=filter)
+
+        else:
+            self.addfile(tarinfo)
+
+    def addfile(self, tarinfo, fileobj=None):
+        """Add the TarInfo object 'tarinfo' to the archive. If 'tarinfo' represents
+           a non zero-size regular file, the 'fileobj' argument should be a binary file,
+           and tarinfo.size bytes are read from it and added to the archive.
+           You can create TarInfo objects directly, or by using gettarinfo().
+        """
+        self._check("awx")
+
+        if fileobj is None and tarinfo.isreg() and tarinfo.size != 0:
+            raise ValueError("fileobj not provided for non zero-size regular file")
+
+        tarinfo = copy.copy(tarinfo)
+
+        buf = tarinfo.tobuf(self.format, self.encoding, self.errors)
+        self.fileobj.write(buf)
+        self.offset += len(buf)
+        bufsize=self.copybufsize
+        # If there's data to follow, append it.
+        if fileobj is not None:
+            copyfileobj(fileobj, self.fileobj, tarinfo.size, bufsize=bufsize)
+            blocks, remainder = divmod(tarinfo.size, BLOCKSIZE)
+            if remainder > 0:
+                self.fileobj.write(NUL * (BLOCKSIZE - remainder))
+                blocks += 1
+            self.offset += blocks * BLOCKSIZE
+
+        self.members.append(tarinfo)
+
+    def _get_filter_function(self, filter):
+        if filter is None:
+            filter = self.extraction_filter
+            if filter is None:
+                import warnings
+                warnings.warn(
+                    'Python 3.14 will, by default, filter extracted tar '
+                    + 'archives and reject files or modify their metadata. '
+                    + 'Use the filter argument to control this behavior.',
+                    DeprecationWarning, stacklevel=3)
+                return fully_trusted_filter
+            if isinstance(filter, str):
+                raise TypeError(
+                    'String names are not supported for '
+                    + 'TarFile.extraction_filter. Use a function such as '
+                    + 'tarfile.data_filter directly.')
+            return filter
+        if callable(filter):
+            return filter
+        try:
+            return _NAMED_FILTERS[filter]
+        except KeyError:
+            raise ValueError(f"filter {filter!r} not found") from None
+
+    def extractall(self, path=".", members=None, *, numeric_owner=False,
+                   filter=None):
+        """Extract all members from the archive to the current working
+           directory and set owner, modification time and permissions on
+           directories afterwards. 'path' specifies a different directory
+           to extract to. 'members' is optional and must be a subset of the
+           list returned by getmembers(). If 'numeric_owner' is True, only
+           the numbers for user/group names are used and not the names.
+
+           The 'filter' function will be called on each member just
+           before extraction.
+           It can return a changed TarInfo or None to skip the member.
+           String names of common filters are accepted.
+        """
+        directories = []
+
+        filter_function = self._get_filter_function(filter)
+        if members is None:
+            members = self
+
+        for member in members:
+            tarinfo = self._get_extract_tarinfo(member, filter_function, path)
+            if tarinfo is None:
+                continue
+            if tarinfo.isdir():
+                # For directories, delay setting attributes until later,
+                # since permissions can interfere with extraction and
+                # extracting contents can reset mtime.
+                directories.append(tarinfo)
+            self._extract_one(tarinfo, path, set_attrs=not tarinfo.isdir(),
+                              numeric_owner=numeric_owner)
+
+        # Reverse sort directories.
+        directories.sort(key=lambda a: a.name, reverse=True)
+
+        # Set correct owner, mtime and filemode on directories.
+        for tarinfo in directories:
+            dirpath = os.path.join(path, tarinfo.name)
+            try:
+                self.chown(tarinfo, dirpath, numeric_owner=numeric_owner)
+                self.utime(tarinfo, dirpath)
+                self.chmod(tarinfo, dirpath)
+            except ExtractError as e:
+                self._handle_nonfatal_error(e)
+
+    def extract(self, member, path="", set_attrs=True, *, numeric_owner=False,
+                filter=None):
+        """Extract a member from the archive to the current working directory,
+           using its full name. Its file information is extracted as accurately
+           as possible. 'member' may be a filename or a TarInfo object. You can
+           specify a different directory using 'path'. File attributes (owner,
+           mtime, mode) are set unless 'set_attrs' is False. If 'numeric_owner'
+           is True, only the numbers for user/group names are used and not
+           the names.
+
+           The 'filter' function will be called before extraction.
+           It can return a changed TarInfo or None to skip the member.
+           String names of common filters are accepted.
+        """
+        filter_function = self._get_filter_function(filter)
+        tarinfo = self._get_extract_tarinfo(member, filter_function, path)
+        if tarinfo is not None:
+            self._extract_one(tarinfo, path, set_attrs, numeric_owner)
+
+    def _get_extract_tarinfo(self, member, filter_function, path):
+        """Get filtered TarInfo (or None) from member, which might be a str"""
+        if isinstance(member, str):
+            tarinfo = self.getmember(member)
+        else:
+            tarinfo = member
+
+        unfiltered = tarinfo
+        try:
+            tarinfo = filter_function(tarinfo, path)
+        except (OSError, FilterError) as e:
+            self._handle_fatal_error(e)
+        except ExtractError as e:
+            self._handle_nonfatal_error(e)
+        if tarinfo is None:
+            self._dbg(2, "tarfile: Excluded %r" % unfiltered.name)
+            return None
+        # Prepare the link target for makelink().
+        if tarinfo.islnk():
+            tarinfo = copy.copy(tarinfo)
+            tarinfo._link_target = os.path.join(path, tarinfo.linkname)
+        return tarinfo
+
+    def _extract_one(self, tarinfo, path, set_attrs, numeric_owner):
+        """Extract from filtered tarinfo to disk"""
+        self._check("r")
+
+        try:
+            self._extract_member(tarinfo, os.path.join(path, tarinfo.name),
+                                 set_attrs=set_attrs,
+                                 numeric_owner=numeric_owner)
+        except OSError as e:
+            self._handle_fatal_error(e)
+        except ExtractError as e:
+            self._handle_nonfatal_error(e)
+
+    def _handle_nonfatal_error(self, e):
+        """Handle non-fatal error (ExtractError) according to errorlevel"""
+        if self.errorlevel > 1:
+            raise
+        else:
+            self._dbg(1, "tarfile: %s" % e)
+
+    def _handle_fatal_error(self, e):
+        """Handle "fatal" error according to self.errorlevel"""
+        if self.errorlevel > 0:
+            raise
+        elif isinstance(e, OSError):
+            if e.filename is None:
+                self._dbg(1, "tarfile: %s" % e.strerror)
+            else:
+                self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename))
+        else:
+            self._dbg(1, "tarfile: %s %s" % (type(e).__name__, e))
+
+    def extractfile(self, member):
+        """Extract a member from the archive as a file object. 'member' may be
+           a filename or a TarInfo object. If 'member' is a regular file or
+           a link, an io.BufferedReader object is returned. For all other
+           existing members, None is returned. If 'member' does not appear
+           in the archive, KeyError is raised.
+        """
+        self._check("r")
+
+        if isinstance(member, str):
+            tarinfo = self.getmember(member)
+        else:
+            tarinfo = member
+
+        if tarinfo.isreg() or tarinfo.type not in SUPPORTED_TYPES:
+            # Members with unknown types are treated as regular files.
+            return self.fileobject(self, tarinfo)
+
+        elif tarinfo.islnk() or tarinfo.issym():
+            if isinstance(self.fileobj, _Stream):
+                # A small but ugly workaround for the case that someone tries
+                # to extract a (sym)link as a file-object from a non-seekable
+                # stream of tar blocks.
+                raise StreamError("cannot extract (sym)link as file object")
+            else:
+                # A (sym)link's file object is its target's file object.
+                return self.extractfile(self._find_link_target(tarinfo))
+        else:
+            # If there's no data associated with the member (directory, chrdev,
+            # blkdev, etc.), return None instead of a file object.
+            return None
+
+    def _extract_member(self, tarinfo, targetpath, set_attrs=True,
+                        numeric_owner=False):
+        """Extract the TarInfo object tarinfo to a physical
+           file called targetpath.
+        """
+        # Fetch the TarInfo object for the given name
+        # and build the destination pathname, replacing
+        # forward slashes to platform specific separators.
+        targetpath = targetpath.rstrip("/")
+        targetpath = targetpath.replace("/", os.sep)
+
+        # Create all upper directories.
+        upperdirs = os.path.dirname(targetpath)
+        if upperdirs and not os.path.exists(upperdirs):
+            # Create directories that are not part of the archive with
+            # default permissions.
+            os.makedirs(upperdirs, exist_ok=True)
+
+        if tarinfo.islnk() or tarinfo.issym():
+            self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname))
+        else:
+            self._dbg(1, tarinfo.name)
+
+        if tarinfo.isreg():
+            self.makefile(tarinfo, targetpath)
+        elif tarinfo.isdir():
+            self.makedir(tarinfo, targetpath)
+        elif tarinfo.isfifo():
+            self.makefifo(tarinfo, targetpath)
+        elif tarinfo.ischr() or tarinfo.isblk():
+            self.makedev(tarinfo, targetpath)
+        elif tarinfo.islnk() or tarinfo.issym():
+            self.makelink(tarinfo, targetpath)
+        elif tarinfo.type not in SUPPORTED_TYPES:
+            self.makeunknown(tarinfo, targetpath)
+        else:
+            self.makefile(tarinfo, targetpath)
+
+        if set_attrs:
+            self.chown(tarinfo, targetpath, numeric_owner)
+            if not tarinfo.issym():
+                self.chmod(tarinfo, targetpath)
+                self.utime(tarinfo, targetpath)
+
+    #--------------------------------------------------------------------------
+    # Below are the different file methods. They are called via
+    # _extract_member() when extract() is called. They can be replaced in a
+    # subclass to implement other functionality.
+
+    def makedir(self, tarinfo, targetpath):
+        """Make a directory called targetpath.
+        """
+        try:
+            if tarinfo.mode is None:
+                # Use the system's default mode
+                os.mkdir(targetpath)
+            else:
+                # Use a safe mode for the directory, the real mode is set
+                # later in _extract_member().
+                os.mkdir(targetpath, 0o700)
+        except FileExistsError:
+            if not os.path.isdir(targetpath):
+                raise
+
+    def makefile(self, tarinfo, targetpath):
+        """Make a file called targetpath.
+        """
+        source = self.fileobj
+        source.seek(tarinfo.offset_data)
+        bufsize = self.copybufsize
+        with bltn_open(targetpath, "wb") as target:
+            if tarinfo.sparse is not None:
+                for offset, size in tarinfo.sparse:
+                    target.seek(offset)
+                    copyfileobj(source, target, size, ReadError, bufsize)
+                target.seek(tarinfo.size)
+                target.truncate()
+            else:
+                copyfileobj(source, target, tarinfo.size, ReadError, bufsize)
+
+    def makeunknown(self, tarinfo, targetpath):
+        """Make a file from a TarInfo object with an unknown type
+           at targetpath.
+        """
+        self.makefile(tarinfo, targetpath)
+        self._dbg(1, "tarfile: Unknown file type %r, " \
+                     "extracted as regular file." % tarinfo.type)
+
+    def makefifo(self, tarinfo, targetpath):
+        """Make a fifo called targetpath.
+        """
+        if hasattr(os, "mkfifo"):
+            os.mkfifo(targetpath)
+        else:
+            raise ExtractError("fifo not supported by system")
+
+    def makedev(self, tarinfo, targetpath):
+        """Make a character or block device called targetpath.
+        """
+        if not hasattr(os, "mknod") or not hasattr(os, "makedev"):
+            raise ExtractError("special devices not supported by system")
+
+        mode = tarinfo.mode
+        if mode is None:
+            # Use mknod's default
+            mode = 0o600
+        if tarinfo.isblk():
+            mode |= stat.S_IFBLK
+        else:
+            mode |= stat.S_IFCHR
+
+        os.mknod(targetpath, mode,
+                 os.makedev(tarinfo.devmajor, tarinfo.devminor))
+
+    def makelink(self, tarinfo, targetpath):
+        """Make a (symbolic) link called targetpath. If it cannot be created
+          (platform limitation), we try to make a copy of the referenced file
+          instead of a link.
+        """
+        try:
+            # For systems that support symbolic and hard links.
+            if tarinfo.issym():
+                if os.path.lexists(targetpath):
+                    # Avoid FileExistsError on following os.symlink.
+                    os.unlink(targetpath)
+                os.symlink(tarinfo.linkname, targetpath)
+            else:
+                if os.path.exists(tarinfo._link_target):
+                    os.link(tarinfo._link_target, targetpath)
+                else:
+                    self._extract_member(self._find_link_target(tarinfo),
+                                         targetpath)
+        except symlink_exception:
+            try:
+                self._extract_member(self._find_link_target(tarinfo),
+                                     targetpath)
+            except KeyError:
+                raise ExtractError("unable to resolve link inside archive") from None
+
+    def chown(self, tarinfo, targetpath, numeric_owner):
+        """Set owner of targetpath according to tarinfo. If numeric_owner
+           is True, use .gid/.uid instead of .gname/.uname. If numeric_owner
+           is False, fall back to .gid/.uid when the search based on name
+           fails.
+        """
+        if hasattr(os, "geteuid") and os.geteuid() == 0:
+            # We have to be root to do so.
+            g = tarinfo.gid
+            u = tarinfo.uid
+            if not numeric_owner:
+                try:
+                    if grp and tarinfo.gname:
+                        g = grp.getgrnam(tarinfo.gname)[2]
+                except KeyError:
+                    pass
+                try:
+                    if pwd and tarinfo.uname:
+                        u = pwd.getpwnam(tarinfo.uname)[2]
+                except KeyError:
+                    pass
+            if g is None:
+                g = -1
+            if u is None:
+                u = -1
+            try:
+                if tarinfo.issym() and hasattr(os, "lchown"):
+                    os.lchown(targetpath, u, g)
+                else:
+                    os.chown(targetpath, u, g)
+            except (OSError, OverflowError) as e:
+                # OverflowError can be raised if an ID doesn't fit in 'id_t'
+                raise ExtractError("could not change owner") from e
+
+    def chmod(self, tarinfo, targetpath):
+        """Set file permissions of targetpath according to tarinfo.
+        """
+        if tarinfo.mode is None:
+            return
+        try:
+            os.chmod(targetpath, tarinfo.mode)
+        except OSError as e:
+            raise ExtractError("could not change mode") from e
+
+    def utime(self, tarinfo, targetpath):
+        """Set modification time of targetpath according to tarinfo.
+        """
+        mtime = tarinfo.mtime
+        if mtime is None:
+            return
+        if not hasattr(os, 'utime'):
+            return
+        try:
+            os.utime(targetpath, (mtime, mtime))
+        except OSError as e:
+            raise ExtractError("could not change modification time") from e
+
+    #--------------------------------------------------------------------------
+    def next(self):
+        """Return the next member of the archive as a TarInfo object, when
+           TarFile is opened for reading. Return None if there is no more
+           available.
+        """
+        self._check("ra")
+        if self.firstmember is not None:
+            m = self.firstmember
+            self.firstmember = None
+            return m
+
+        # Advance the file pointer.
+        if self.offset != self.fileobj.tell():
+            if self.offset == 0:
+                return None
+            self.fileobj.seek(self.offset - 1)
+            if not self.fileobj.read(1):
+                raise ReadError("unexpected end of data")
+
+        # Read the next block.
+        tarinfo = None
+        while True:
+            try:
+                tarinfo = self.tarinfo.fromtarfile(self)
+            except EOFHeaderError as e:
+                if self.ignore_zeros:
+                    self._dbg(2, "0x%X: %s" % (self.offset, e))
+                    self.offset += BLOCKSIZE
+                    continue
+            except InvalidHeaderError as e:
+                if self.ignore_zeros:
+                    self._dbg(2, "0x%X: %s" % (self.offset, e))
+                    self.offset += BLOCKSIZE
+                    continue
+                elif self.offset == 0:
+                    raise ReadError(str(e)) from None
+            except EmptyHeaderError:
+                if self.offset == 0:
+                    raise ReadError("empty file") from None
+            except TruncatedHeaderError as e:
+                if self.offset == 0:
+                    raise ReadError(str(e)) from None
+            except SubsequentHeaderError as e:
+                raise ReadError(str(e)) from None
+            except Exception as e:
+                try:
+                    import zlib
+                    if isinstance(e, zlib.error):
+                        raise ReadError(f'zlib error: {e}') from None
+                    else:
+                        raise e
+                except ImportError:
+                    raise e
+            break
+
+        if tarinfo is not None:
+            # if streaming the file we do not want to cache the tarinfo
+            if not self.stream:
+                self.members.append(tarinfo)
+        else:
+            self._loaded = True
+
+        return tarinfo
+
+    #--------------------------------------------------------------------------
+    # Little helper methods:
+
+    def _getmember(self, name, tarinfo=None, normalize=False):
+        """Find an archive member by name from bottom to top.
+           If tarinfo is given, it is used as the starting point.
+        """
+        # Ensure that all members have been loaded.
+        members = self.getmembers()
+
+        # Limit the member search list up to tarinfo.
+        skipping = False
+        if tarinfo is not None:
+            try:
+                index = members.index(tarinfo)
+            except ValueError:
+                # The given starting point might be a (modified) copy.
+                # We'll later skip members until we find an equivalent.
+                skipping = True
+            else:
+                # Happy fast path
+                members = members[:index]
+
+        if normalize:
+            name = os.path.normpath(name)
+
+        for member in reversed(members):
+            if skipping:
+                if tarinfo.offset == member.offset:
+                    skipping = False
+                continue
+            if normalize:
+                member_name = os.path.normpath(member.name)
+            else:
+                member_name = member.name
+
+            if name == member_name:
+                return member
+
+        if skipping:
+            # Starting point was not found
+            raise ValueError(tarinfo)
+
+    def _load(self):
+        """Read through the entire archive file and look for readable
+           members. This should not run if the file is set to stream.
+        """
+        if not self.stream:
+            while self.next() is not None:
+                pass
+            self._loaded = True
+
+    def _check(self, mode=None):
+        """Check if TarFile is still open, and if the operation's mode
+           corresponds to TarFile's mode.
+        """
+        if self.closed:
+            raise OSError("%s is closed" % self.__class__.__name__)
+        if mode is not None and self.mode not in mode:
+            raise OSError("bad operation for mode %r" % self.mode)
+
+    def _find_link_target(self, tarinfo):
+        """Find the target member of a symlink or hardlink member in the
+           archive.
+        """
+        if tarinfo.issym():
+            # Always search the entire archive.
+            linkname = "/".join(filter(None, (os.path.dirname(tarinfo.name), tarinfo.linkname)))
+            limit = None
+        else:
+            # Search the archive before the link, because a hard link is
+            # just a reference to an already archived file.
+            linkname = tarinfo.linkname
+            limit = tarinfo
+
+        member = self._getmember(linkname, tarinfo=limit, normalize=True)
+        if member is None:
+            raise KeyError("linkname %r not found" % linkname)
+        return member
+
+    def __iter__(self):
+        """Provide an iterator object.
+        """
+        if self._loaded:
+            yield from self.members
+            return
+
+        # Yield items using TarFile's next() method.
+        # When all members have been read, set TarFile as _loaded.
+        index = 0
+        # Fix for SF #1100429: Under rare circumstances it can
+        # happen that getmembers() is called during iteration,
+        # which will have already exhausted the next() method.
+        if self.firstmember is not None:
+            tarinfo = self.next()
+            index += 1
+            yield tarinfo
+
+        while True:
+            if index < len(self.members):
+                tarinfo = self.members[index]
+            elif not self._loaded:
+                tarinfo = self.next()
+                if not tarinfo:
+                    self._loaded = True
+                    return
+            else:
+                return
+            index += 1
+            yield tarinfo
+
+    def _dbg(self, level, msg):
+        """Write debugging output to sys.stderr.
+        """
+        if level <= self.debug:
+            print(msg, file=sys.stderr)
+
+    def __enter__(self):
+        self._check()
+        return self
+
+    def __exit__(self, type, value, traceback):
+        if type is None:
+            self.close()
+        else:
+            # An exception occurred. We must not call close() because
+            # it would try to write end-of-archive blocks and padding.
+            if not self._extfileobj:
+                self.fileobj.close()
+            self.closed = True
+
+#--------------------
+# exported functions
+#--------------------
+
+def is_tarfile(name):
+    """Return True if name points to a tar archive that we
+       are able to handle, else return False.
+
+       'name' should be a string, file, or file-like object.
+    """
+    try:
+        if hasattr(name, "read"):
+            pos = name.tell()
+            t = open(fileobj=name)
+            name.seek(pos)
+        else:
+            t = open(name)
+        t.close()
+        return True
+    except TarError:
+        return False
+
+open = TarFile.open
+
+
+def main():
+    import argparse
+
+    description = 'A simple command-line interface for tarfile module.'
+    parser = argparse.ArgumentParser(description=description)
+    parser.add_argument('-v', '--verbose', action='store_true', default=False,
+                        help='Verbose output')
+    parser.add_argument('--filter', metavar='',
+                        choices=_NAMED_FILTERS,
+                        help='Filter for extraction')
+
+    group = parser.add_mutually_exclusive_group(required=True)
+    group.add_argument('-l', '--list', metavar='',
+                       help='Show listing of a tarfile')
+    group.add_argument('-e', '--extract', nargs='+',
+                       metavar=('', ''),
+                       help='Extract tarfile into target dir')
+    group.add_argument('-c', '--create', nargs='+',
+                       metavar=('', ''),
+                       help='Create tarfile from sources')
+    group.add_argument('-t', '--test', metavar='',
+                       help='Test if a tarfile is valid')
+
+    args = parser.parse_args()
+
+    if args.filter and args.extract is None:
+        parser.exit(1, '--filter is only valid for extraction\n')
+
+    if args.test is not None:
+        src = args.test
+        if is_tarfile(src):
+            with open(src, 'r') as tar:
+                tar.getmembers()
+                print(tar.getmembers(), file=sys.stderr)
+            if args.verbose:
+                print('{!r} is a tar archive.'.format(src))
+        else:
+            parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
+
+    elif args.list is not None:
+        src = args.list
+        if is_tarfile(src):
+            with TarFile.open(src, 'r:*') as tf:
+                tf.list(verbose=args.verbose)
+        else:
+            parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
+
+    elif args.extract is not None:
+        if len(args.extract) == 1:
+            src = args.extract[0]
+            curdir = os.curdir
+        elif len(args.extract) == 2:
+            src, curdir = args.extract
+        else:
+            parser.exit(1, parser.format_help())
+
+        if is_tarfile(src):
+            with TarFile.open(src, 'r:*') as tf:
+                tf.extractall(path=curdir, filter=args.filter)
+            if args.verbose:
+                if curdir == '.':
+                    msg = '{!r} file is extracted.'.format(src)
+                else:
+                    msg = ('{!r} file is extracted '
+                           'into {!r} directory.').format(src, curdir)
+                print(msg)
+        else:
+            parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
+
+    elif args.create is not None:
+        tar_name = args.create.pop(0)
+        _, ext = os.path.splitext(tar_name)
+        compressions = {
+            # gz
+            '.gz': 'gz',
+            '.tgz': 'gz',
+            # xz
+            '.xz': 'xz',
+            '.txz': 'xz',
+            # bz2
+            '.bz2': 'bz2',
+            '.tbz': 'bz2',
+            '.tbz2': 'bz2',
+            '.tb2': 'bz2',
+        }
+        tar_mode = 'w:' + compressions[ext] if ext in compressions else 'w'
+        tar_files = args.create
+
+        with TarFile.open(tar_name, tar_mode) as tf:
+            for file_name in tar_files:
+                tf.add(file_name)
+
+        if args.verbose:
+            print('{!r} file created.'.format(tar_name))
+
+if __name__ == '__main__':
+    main()
diff --git a/setuptools/_vendor/backports/tarfile/__main__.py b/setuptools/_vendor/backports/tarfile/__main__.py
new file mode 100644
index 0000000000..daf5509086
--- /dev/null
+++ b/setuptools/_vendor/backports/tarfile/__main__.py
@@ -0,0 +1,5 @@
+from . import main
+
+
+if __name__ == '__main__':
+    main()
diff --git a/pkg_resources/_vendor/importlib_resources/tests/__init__.py b/setuptools/_vendor/backports/tarfile/compat/__init__.py
similarity index 100%
rename from pkg_resources/_vendor/importlib_resources/tests/__init__.py
rename to setuptools/_vendor/backports/tarfile/compat/__init__.py
diff --git a/setuptools/_vendor/backports/tarfile/compat/py38.py b/setuptools/_vendor/backports/tarfile/compat/py38.py
new file mode 100644
index 0000000000..20fbbfc1c0
--- /dev/null
+++ b/setuptools/_vendor/backports/tarfile/compat/py38.py
@@ -0,0 +1,24 @@
+import sys
+
+
+if sys.version_info < (3, 9):
+
+    def removesuffix(self, suffix):
+        # suffix='' should not call self[:-0].
+        if suffix and self.endswith(suffix):
+            return self[: -len(suffix)]
+        else:
+            return self[:]
+
+    def removeprefix(self, prefix):
+        if self.startswith(prefix):
+            return self[len(prefix) :]
+        else:
+            return self[:]
+else:
+
+    def removesuffix(self, suffix):
+        return self.removesuffix(suffix)
+
+    def removeprefix(self, prefix):
+        return self.removeprefix(prefix)
diff --git a/setuptools/_vendor/importlib_metadata-6.0.0.dist-info/INSTALLER b/setuptools/_vendor/importlib_metadata-6.0.0.dist-info/INSTALLER
deleted file mode 100644
index a1b589e38a..0000000000
--- a/setuptools/_vendor/importlib_metadata-6.0.0.dist-info/INSTALLER
+++ /dev/null
@@ -1 +0,0 @@
-pip
diff --git a/setuptools/_vendor/importlib_metadata-6.0.0.dist-info/LICENSE b/setuptools/_vendor/importlib_metadata-6.0.0.dist-info/LICENSE
deleted file mode 100644
index d645695673..0000000000
--- a/setuptools/_vendor/importlib_metadata-6.0.0.dist-info/LICENSE
+++ /dev/null
@@ -1,202 +0,0 @@
-
-                                 Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
-
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
-
-   END OF TERMS AND CONDITIONS
-
-   APPENDIX: How to apply the Apache License to your work.
-
-      To apply the Apache License to your work, attach the following
-      boilerplate notice, with the fields enclosed by brackets "[]"
-      replaced with your own identifying information. (Don't include
-      the brackets!)  The text should be enclosed in the appropriate
-      comment syntax for the file format. We also recommend that a
-      file or class name and description of purpose be included on the
-      same "printed page" as the copyright notice for easier
-      identification within third-party archives.
-
-   Copyright [yyyy] [name of copyright owner]
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-   you may not use this file except in compliance with the License.
-   You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
diff --git a/setuptools/_vendor/importlib_metadata-6.0.0.dist-info/RECORD b/setuptools/_vendor/importlib_metadata-6.0.0.dist-info/RECORD
deleted file mode 100644
index 01f235677f..0000000000
--- a/setuptools/_vendor/importlib_metadata-6.0.0.dist-info/RECORD
+++ /dev/null
@@ -1,26 +0,0 @@
-importlib_metadata-6.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-importlib_metadata-6.0.0.dist-info/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
-importlib_metadata-6.0.0.dist-info/METADATA,sha256=tZIEx9HdEXD34SWuitkNXaYBqSnyNukx2l4FKQAz9hY,4958
-importlib_metadata-6.0.0.dist-info/RECORD,,
-importlib_metadata-6.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-importlib_metadata-6.0.0.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92
-importlib_metadata-6.0.0.dist-info/top_level.txt,sha256=CO3fD9yylANiXkrMo4qHLV_mqXL2sC5JFKgt1yWAT-A,19
-importlib_metadata/__init__.py,sha256=wiMJxNXXhPtRRHSX2N9gGLnTh0YszmE1rn3uKYRrNcs,26490
-importlib_metadata/__pycache__/__init__.cpython-311.pyc,,
-importlib_metadata/__pycache__/_adapters.cpython-311.pyc,,
-importlib_metadata/__pycache__/_collections.cpython-311.pyc,,
-importlib_metadata/__pycache__/_compat.cpython-311.pyc,,
-importlib_metadata/__pycache__/_functools.cpython-311.pyc,,
-importlib_metadata/__pycache__/_itertools.cpython-311.pyc,,
-importlib_metadata/__pycache__/_meta.cpython-311.pyc,,
-importlib_metadata/__pycache__/_py39compat.cpython-311.pyc,,
-importlib_metadata/__pycache__/_text.cpython-311.pyc,,
-importlib_metadata/_adapters.py,sha256=i8S6Ib1OQjcILA-l4gkzktMZe18TaeUNI49PLRp6OBU,2454
-importlib_metadata/_collections.py,sha256=CJ0OTCHIjWA0ZIVS4voORAsn2R4R2cQBEtPsZEJpASY,743
-importlib_metadata/_compat.py,sha256=9zOKf0eDgkCMnnaEhU5kQVxHd1P8BIYV7Stso7av5h8,1857
-importlib_metadata/_functools.py,sha256=PsY2-4rrKX4RVeRC1oGp1lB1pmC9eKN88_f-bD9uOoA,2895
-importlib_metadata/_itertools.py,sha256=cvr_2v8BRbxcIl5x5ldfqdHjhI8Yi8s8yk50G_nm6jQ,2068
-importlib_metadata/_meta.py,sha256=v5e1ZDG7yZTH3h7TjbS5bM5p8AGzMPVOu8skDMv4h6k,1165
-importlib_metadata/_py39compat.py,sha256=2Tk5twb_VgLCY-1NEAQjdZp_S9OFMC-pUzP2isuaPsQ,1098
-importlib_metadata/_text.py,sha256=HCsFksZpJLeTP3NEk_ngrAeXVRRtTrtyh9eOABoRP4A,2166
-importlib_metadata/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
diff --git a/setuptools/_vendor/importlib_metadata-6.0.0.dist-info/WHEEL b/setuptools/_vendor/importlib_metadata-6.0.0.dist-info/WHEEL
deleted file mode 100644
index 57e3d840d5..0000000000
--- a/setuptools/_vendor/importlib_metadata-6.0.0.dist-info/WHEEL
+++ /dev/null
@@ -1,5 +0,0 @@
-Wheel-Version: 1.0
-Generator: bdist_wheel (0.38.4)
-Root-Is-Purelib: true
-Tag: py3-none-any
-
diff --git a/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/INSTALLER b/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/INSTALLER
new file mode 100644
index 0000000000..5c69047b2e
--- /dev/null
+++ b/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/setuptools/_vendor/importlib_metadata-6.0.0.dist-info/METADATA b/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/METADATA
similarity index 55%
rename from setuptools/_vendor/importlib_metadata-6.0.0.dist-info/METADATA
rename to setuptools/_vendor/importlib_metadata-8.7.1.dist-info/METADATA
index 663c0c8720..9d894b433d 100644
--- a/setuptools/_vendor/importlib_metadata-6.0.0.dist-info/METADATA
+++ b/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/METADATA
@@ -1,60 +1,63 @@
-Metadata-Version: 2.1
-Name: importlib-metadata
-Version: 6.0.0
+Metadata-Version: 2.4
+Name: importlib_metadata
+Version: 8.7.1
 Summary: Read metadata from Python packages
-Home-page: https://github.com/python/importlib_metadata
-Author: Jason R. Coombs
-Author-email: jaraco@jaraco.com
+Author-email: "Jason R. Coombs" 
+License-Expression: Apache-2.0
+Project-URL: Source, https://github.com/python/importlib_metadata
 Classifier: Development Status :: 5 - Production/Stable
 Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: Apache Software License
 Classifier: Programming Language :: Python :: 3
 Classifier: Programming Language :: Python :: 3 :: Only
-Requires-Python: >=3.7
+Requires-Python: >=3.9
+Description-Content-Type: text/x-rst
 License-File: LICENSE
-Requires-Dist: zipp (>=0.5)
-Requires-Dist: typing-extensions (>=3.6.4) ; python_version < "3.8"
-Provides-Extra: docs
-Requires-Dist: sphinx (>=3.5) ; extra == 'docs'
-Requires-Dist: jaraco.packaging (>=9) ; extra == 'docs'
-Requires-Dist: rst.linker (>=1.9) ; extra == 'docs'
-Requires-Dist: furo ; extra == 'docs'
-Requires-Dist: sphinx-lint ; extra == 'docs'
-Requires-Dist: jaraco.tidelift (>=1.4) ; extra == 'docs'
+Requires-Dist: zipp>=3.20
+Provides-Extra: test
+Requires-Dist: pytest!=8.1.*,>=6; extra == "test"
+Requires-Dist: packaging; extra == "test"
+Requires-Dist: pyfakefs; extra == "test"
+Requires-Dist: flufl.flake8; extra == "test"
+Requires-Dist: pytest-perf>=0.9.2; extra == "test"
+Requires-Dist: jaraco.test>=5.4; extra == "test"
+Provides-Extra: doc
+Requires-Dist: sphinx>=3.5; extra == "doc"
+Requires-Dist: jaraco.packaging>=9.3; extra == "doc"
+Requires-Dist: rst.linker>=1.9; extra == "doc"
+Requires-Dist: furo; extra == "doc"
+Requires-Dist: sphinx-lint; extra == "doc"
+Requires-Dist: jaraco.tidelift>=1.4; extra == "doc"
 Provides-Extra: perf
-Requires-Dist: ipython ; extra == 'perf'
-Provides-Extra: testing
-Requires-Dist: pytest (>=6) ; extra == 'testing'
-Requires-Dist: pytest-checkdocs (>=2.4) ; extra == 'testing'
-Requires-Dist: flake8 (<5) ; extra == 'testing'
-Requires-Dist: pytest-cov ; extra == 'testing'
-Requires-Dist: pytest-enabler (>=1.3) ; extra == 'testing'
-Requires-Dist: packaging ; extra == 'testing'
-Requires-Dist: pyfakefs ; extra == 'testing'
-Requires-Dist: flufl.flake8 ; extra == 'testing'
-Requires-Dist: pytest-perf (>=0.9.2) ; extra == 'testing'
-Requires-Dist: pytest-black (>=0.3.7) ; (platform_python_implementation != "PyPy") and extra == 'testing'
-Requires-Dist: pytest-mypy (>=0.9.1) ; (platform_python_implementation != "PyPy") and extra == 'testing'
-Requires-Dist: pytest-flake8 ; (python_version < "3.12") and extra == 'testing'
-Requires-Dist: importlib-resources (>=1.3) ; (python_version < "3.9") and extra == 'testing'
+Requires-Dist: ipython; extra == "perf"
+Provides-Extra: check
+Requires-Dist: pytest-checkdocs>=2.4; extra == "check"
+Requires-Dist: pytest-ruff>=0.2.1; sys_platform != "cygwin" and extra == "check"
+Provides-Extra: cover
+Requires-Dist: pytest-cov; extra == "cover"
+Provides-Extra: enabler
+Requires-Dist: pytest-enabler>=3.4; extra == "enabler"
+Provides-Extra: type
+Requires-Dist: pytest-mypy>=1.0.1; extra == "type"
+Requires-Dist: mypy<1.19; platform_python_implementation == "PyPy" and extra == "type"
+Dynamic: license-file
 
 .. image:: https://img.shields.io/pypi/v/importlib_metadata.svg
    :target: https://pypi.org/project/importlib_metadata
 
 .. image:: https://img.shields.io/pypi/pyversions/importlib_metadata.svg
 
-.. image:: https://github.com/python/importlib_metadata/workflows/tests/badge.svg
+.. image:: https://github.com/python/importlib_metadata/actions/workflows/main.yml/badge.svg
    :target: https://github.com/python/importlib_metadata/actions?query=workflow%3A%22tests%22
    :alt: tests
 
-.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
-   :target: https://github.com/psf/black
-   :alt: Code style: Black
+.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json
+    :target: https://github.com/astral-sh/ruff
+    :alt: Ruff
 
 .. image:: https://readthedocs.org/projects/importlib-metadata/badge/?version=latest
    :target: https://importlib-metadata.readthedocs.io/en/latest/?badge=latest
 
-.. image:: https://img.shields.io/badge/skeleton-2022-informational
+.. image:: https://img.shields.io/badge/skeleton-2025-informational
    :target: https://blog.jaraco.com/skeleton
 
 .. image:: https://tidelift.com/badges/package/pypi/importlib-metadata
@@ -79,7 +82,9 @@ were contributed to different versions in the standard library:
 
    * - importlib_metadata
      - stdlib
-   * - 5.0
+   * - 7.0
+     - 3.13
+   * - 6.5
      - 3.12
    * - 4.13
      - 3.11
@@ -92,7 +97,7 @@ were contributed to different versions in the standard library:
 Usage
 =====
 
-See the `online documentation `_
+See the `online documentation `_
 for usage details.
 
 `Finder authors
@@ -116,7 +121,7 @@ Project details
  * Project home: https://github.com/python/importlib_metadata
  * Report bugs at: https://github.com/python/importlib_metadata/issues
  * Code hosting: https://github.com/python/importlib_metadata
- * Documentation: https://importlib_metadata.readthedocs.io/
+ * Documentation: https://importlib-metadata.readthedocs.io/
 
 For Enterprise
 ==============
@@ -126,10 +131,3 @@ Available as part of the Tidelift Subscription.
 This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
 
 `Learn more `_.
-
-Security Contact
-================
-
-To report a security vulnerability, please use the
-`Tidelift security contact `_.
-Tidelift will coordinate the fix and disclosure.
diff --git a/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/RECORD b/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/RECORD
new file mode 100644
index 0000000000..78aa761cab
--- /dev/null
+++ b/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/RECORD
@@ -0,0 +1,21 @@
+importlib_metadata-8.7.1.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+importlib_metadata-8.7.1.dist-info/METADATA,sha256=o-OLnuQyYonUhkcE8w4pnudp4jCc6fSnXw3hpQrQo1Y,4670
+importlib_metadata-8.7.1.dist-info/RECORD,,
+importlib_metadata-8.7.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+importlib_metadata-8.7.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
+importlib_metadata-8.7.1.dist-info/licenses/LICENSE,sha256=RYUC4S2Xu_ZEOGBqIARKqF6wX7CoqAe7NdvsJT_R_AQ,10278
+importlib_metadata-8.7.1.dist-info/top_level.txt,sha256=CO3fD9yylANiXkrMo4qHLV_mqXL2sC5JFKgt1yWAT-A,19
+importlib_metadata/__init__.py,sha256=u7Ew4-UkpzNY-ka6k-WRkDhQZS1akkLMfWs2eEnUmGo,37734
+importlib_metadata/_adapters.py,sha256=r5i8XLrKT6xmrpoREZhZrfczOYDmrVZeJBW5u0HzIGU,3797
+importlib_metadata/_collections.py,sha256=CxAhzlF3g1rwu_fMiB53JtRQiUFh0RgiMpoOvmK_ocg,760
+importlib_metadata/_compat.py,sha256=VC5ZDLlT-BcshauCShdFJvMNLntJJfZzNK1meGa-enw,1313
+importlib_metadata/_functools.py,sha256=0pA2OoiVK6wnsGq8HvVIzgdkvLiZ0nfnfw7IsndjoHk,3510
+importlib_metadata/_itertools.py,sha256=nMvp9SfHAQ_JYwK4L2i64lr3GRXGlYlikGTVzWbys_E,5351
+importlib_metadata/_meta.py,sha256=EtHyiJ5kGzWFDfKyQ2XQp6Vu113CeadKW1Vf6aGc1B4,1765
+importlib_metadata/_text.py,sha256=HCsFksZpJLeTP3NEk_ngrAeXVRRtTrtyh9eOABoRP4A,2166
+importlib_metadata/_typing.py,sha256=EQKhhsEgz_Sa-FnePI-faC72rNOOQwopjA1i5pG8FDU,367
+importlib_metadata/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+importlib_metadata/compat/py311.py,sha256=uqm-K-uohyj1042TH4a9Er_I5o7667DvulcD-gC_fSA,608
+importlib_metadata/compat/py39.py,sha256=J3W7PUVRPNYMmcvT12RF8ndBU9e8_T0Ac4U87Bsrq70,1187
+importlib_metadata/diagnose.py,sha256=nkSRMiowlmkhLYhKhvCg9glmt_11Cox-EmLzEbqYTa8,379
+importlib_metadata/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
diff --git a/pkg_resources/_vendor/platformdirs-2.6.2.dist-info/REQUESTED b/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/REQUESTED
similarity index 100%
rename from pkg_resources/_vendor/platformdirs-2.6.2.dist-info/REQUESTED
rename to setuptools/_vendor/importlib_metadata-8.7.1.dist-info/REQUESTED
diff --git a/pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/WHEEL b/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/WHEEL
similarity index 65%
rename from pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/WHEEL
rename to setuptools/_vendor/importlib_metadata-8.7.1.dist-info/WHEEL
index 57e3d840d5..e7fa31b6f3 100644
--- a/pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/WHEEL
+++ b/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/WHEEL
@@ -1,5 +1,5 @@
 Wheel-Version: 1.0
-Generator: bdist_wheel (0.38.4)
+Generator: setuptools (80.9.0)
 Root-Is-Purelib: true
 Tag: py3-none-any
 
diff --git a/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/licenses/LICENSE b/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000..5c1d8bbc02
--- /dev/null
+++ b/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/licenses/LICENSE
@@ -0,0 +1,73 @@
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
+
+"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
+
+     (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
+
+     (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
+
+     (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
+
+     (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
+
+     You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!)  The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
+
+Copyright 2025 [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/setuptools/_vendor/importlib_metadata-6.0.0.dist-info/top_level.txt b/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/top_level.txt
similarity index 100%
rename from setuptools/_vendor/importlib_metadata-6.0.0.dist-info/top_level.txt
rename to setuptools/_vendor/importlib_metadata-8.7.1.dist-info/top_level.txt
diff --git a/setuptools/_vendor/importlib_metadata/__init__.py b/setuptools/_vendor/importlib_metadata/__init__.py
index 8864214375..508b02e4fc 100644
--- a/setuptools/_vendor/importlib_metadata/__init__.py
+++ b/setuptools/_vendor/importlib_metadata/__init__.py
@@ -1,42 +1,52 @@
-import os
-import re
+"""
+APIs exposing metadata from third-party Python packages.
+
+This codebase is shared between importlib.metadata in the stdlib
+and importlib_metadata in PyPI. See
+https://github.com/python/importlib_metadata/wiki/Development-Methodology
+for more detail.
+"""
+
+from __future__ import annotations
+
 import abc
-import csv
-import sys
-from .. import zipp
+import collections
 import email
-import pathlib
-import operator
-import textwrap
-import warnings
 import functools
 import itertools
+import operator
+import os
+import pathlib
 import posixpath
-import collections
+import re
+import sys
+import textwrap
+import types
+from collections.abc import Iterable, Mapping
+from contextlib import suppress
+from importlib import import_module
+from importlib.abc import MetaPathFinder
+from itertools import starmap
+from typing import Any
 
-from . import _adapters, _meta, _py39compat
+from . import _meta
 from ._collections import FreezableDefaultDict, Pair
 from ._compat import (
     NullFinder,
     install,
-    pypy_partial,
 )
-from ._functools import method_cache, pass_none
-from ._itertools import always_iterable, unique_everseen
+from ._functools import method_cache, noop, pass_none, passthrough
+from ._itertools import always_iterable, bucket, unique_everseen
 from ._meta import PackageMetadata, SimplePath
-
-from contextlib import suppress
-from importlib import import_module
-from importlib.abc import MetaPathFinder
-from itertools import starmap
-from typing import List, Mapping, Optional
-
+from ._typing import md_none
+from .compat import py39, py311
 
 __all__ = [
     'Distribution',
     'DistributionFinder',
     'PackageMetadata',
     'PackageNotFoundError',
+    'SimplePath',
     'distribution',
     'distributions',
     'entry_points',
@@ -51,11 +61,11 @@
 class PackageNotFoundError(ModuleNotFoundError):
     """The package was not found."""
 
-    def __str__(self):
+    def __str__(self) -> str:
         return f"No package metadata was found for {self.name}"
 
     @property
-    def name(self):
+    def name(self) -> str:  # type: ignore[override] # make readonly
         (name,) = self.args
         return name
 
@@ -121,38 +131,17 @@ def read(text, filter_=None):
             yield Pair(name, value)
 
     @staticmethod
-    def valid(line):
+    def valid(line: str):
         return line and not line.startswith('#')
 
 
-class DeprecatedTuple:
-    """
-    Provide subscript item access for backward compatibility.
+class _EntryPointMatch(types.SimpleNamespace):
+    module: str
+    attr: str
+    extras: str
 
-    >>> recwarn = getfixture('recwarn')
-    >>> ep = EntryPoint(name='name', value='value', group='group')
-    >>> ep[:]
-    ('name', 'value', 'group')
-    >>> ep[0]
-    'name'
-    >>> len(recwarn)
-    1
-    """
 
-    # Do not remove prior to 2023-05-01 or Python 3.13
-    _warn = functools.partial(
-        warnings.warn,
-        "EntryPoint tuple interface is deprecated. Access members by name.",
-        DeprecationWarning,
-        stacklevel=pypy_partial(2),
-    )
-
-    def __getitem__(self, item):
-        self._warn()
-        return self._key()[item]
-
-
-class EntryPoint(DeprecatedTuple):
+class EntryPoint:
     """An entry point as defined by Python packaging conventions.
 
     See `the packaging docs on entry points
@@ -167,6 +156,30 @@ class EntryPoint(DeprecatedTuple):
     'attr'
     >>> ep.extras
     ['extra1', 'extra2']
+
+    If the value package or module are not valid identifiers, a
+    ValueError is raised on access.
+
+    >>> EntryPoint(name=None, group=None, value='invalid-name').module
+    Traceback (most recent call last):
+    ...
+    ValueError: ('Invalid object reference...invalid-name...
+    >>> EntryPoint(name=None, group=None, value='invalid-name').attr
+    Traceback (most recent call last):
+    ...
+    ValueError: ('Invalid object reference...invalid-name...
+    >>> EntryPoint(name=None, group=None, value='invalid-name').extras
+    Traceback (most recent call last):
+    ...
+    ValueError: ('Invalid object reference...invalid-name...
+
+    The same thing happens on construction.
+
+    >>> EntryPoint(name=None, group=None, value='invalid-name')
+    Traceback (most recent call last):
+    ...
+    ValueError: ('Invalid object reference...invalid-name...
+
     """
 
     pattern = re.compile(
@@ -194,35 +207,44 @@ class EntryPoint(DeprecatedTuple):
     value: str
     group: str
 
-    dist: Optional['Distribution'] = None
+    dist: Distribution | None = None
 
-    def __init__(self, name, value, group):
+    def __init__(self, name: str, value: str, group: str) -> None:
         vars(self).update(name=name, value=value, group=group)
+        self.module
 
-    def load(self):
+    def load(self) -> Any:
         """Load the entry point from its definition. If only a module
         is indicated by the value, return that module. Otherwise,
         return the named object.
         """
-        match = self.pattern.match(self.value)
-        module = import_module(match.group('module'))
-        attrs = filter(None, (match.group('attr') or '').split('.'))
+        module = import_module(self.module)
+        attrs = filter(None, (self.attr or '').split('.'))
         return functools.reduce(getattr, attrs, module)
 
     @property
-    def module(self):
-        match = self.pattern.match(self.value)
-        return match.group('module')
+    def module(self) -> str:
+        return self._match.module
 
     @property
-    def attr(self):
-        match = self.pattern.match(self.value)
-        return match.group('attr')
+    def attr(self) -> str:
+        return self._match.attr
 
     @property
-    def extras(self):
+    def extras(self) -> list[str]:
+        return re.findall(r'\w+', self._match.extras or '')
+
+    @functools.cached_property
+    def _match(self) -> _EntryPointMatch:
         match = self.pattern.match(self.value)
-        return re.findall(r'\w+', match.group('extras') or '')
+        if not match:
+            raise ValueError(
+                'Invalid object reference. '
+                'See https://packaging.python.org'
+                '/en/latest/specifications/entry-points/#data-model',
+                self.value,
+            )
+        return _EntryPointMatch(**match.groupdict())
 
     def _for(self, dist):
         vars(self).update(dist=dist)
@@ -248,9 +270,26 @@ def matches(self, **params):
         >>> ep.matches(attr='bong')
         True
         """
+        self._disallow_dist(params)
         attrs = (getattr(self, param) for param in params)
         return all(map(operator.eq, params.values(), attrs))
 
+    @staticmethod
+    def _disallow_dist(params):
+        """
+        Querying by dist is not allowed (dist objects are not comparable).
+        >>> EntryPoint(name='fan', value='fav', group='fag').matches(dist='foo')
+        Traceback (most recent call last):
+        ...
+        ValueError: "dist" is not suitable for matching...
+        """
+        if "dist" in params:
+            raise ValueError(
+                '"dist" is not suitable for matching. '
+                "Instead, use Distribution.entry_points.select() on a "
+                "located distribution."
+            )
+
     def _key(self):
         return self.name, self.value, self.group
 
@@ -269,7 +308,7 @@ def __repr__(self):
             f'group={self.group!r})'
         )
 
-    def __hash__(self):
+    def __hash__(self) -> int:
         return hash(self._key())
 
 
@@ -280,7 +319,7 @@ class EntryPoints(tuple):
 
     __slots__ = ()
 
-    def __getitem__(self, name):  # -> EntryPoint:
+    def __getitem__(self, name: str) -> EntryPoint:  # type: ignore[override] # Work with str instead of int
         """
         Get the EntryPoint in self matching name.
         """
@@ -289,22 +328,29 @@ def __getitem__(self, name):  # -> EntryPoint:
         except StopIteration:
             raise KeyError(name)
 
-    def select(self, **params):
+    def __repr__(self):
+        """
+        Repr with classname and tuple constructor to
+        signal that we deviate from regular tuple behavior.
+        """
+        return '%s(%r)' % (self.__class__.__name__, tuple(self))
+
+    def select(self, **params) -> EntryPoints:
         """
         Select entry points from self that match the
         given parameters (typically group and/or name).
         """
-        return EntryPoints(ep for ep in self if _py39compat.ep_matches(ep, **params))
+        return EntryPoints(ep for ep in self if py39.ep_matches(ep, **params))
 
     @property
-    def names(self):
+    def names(self) -> set[str]:
         """
         Return the set of all names of all entry points.
         """
         return {ep.name for ep in self}
 
     @property
-    def groups(self):
+    def groups(self) -> set[str]:
         """
         Return the set of all groups of all entry points.
         """
@@ -325,47 +371,83 @@ def _from_text(text):
 class PackagePath(pathlib.PurePosixPath):
     """A reference to a path in a package"""
 
-    def read_text(self, encoding='utf-8'):
-        with self.locate().open(encoding=encoding) as stream:
-            return stream.read()
+    hash: FileHash | None
+    size: int
+    dist: Distribution
+
+    def read_text(self, encoding: str = 'utf-8') -> str:
+        return self.locate().read_text(encoding=encoding)
 
-    def read_binary(self):
-        with self.locate().open('rb') as stream:
-            return stream.read()
+    def read_binary(self) -> bytes:
+        return self.locate().read_bytes()
 
-    def locate(self):
+    def locate(self) -> SimplePath:
         """Return a path-like object for this path"""
         return self.dist.locate_file(self)
 
 
 class FileHash:
-    def __init__(self, spec):
+    def __init__(self, spec: str) -> None:
         self.mode, _, self.value = spec.partition('=')
 
-    def __repr__(self):
+    def __repr__(self) -> str:
         return f''
 
 
 class Distribution(metaclass=abc.ABCMeta):
-    """A Python distribution package."""
+    """
+    An abstract Python distribution package.
+
+    Custom providers may derive from this class and define
+    the abstract methods to provide a concrete implementation
+    for their environment. Some providers may opt to override
+    the default implementation of some properties to bypass
+    the file-reading mechanism.
+    """
 
     @abc.abstractmethod
-    def read_text(self, filename):
+    def read_text(self, filename) -> str | None:
         """Attempt to load metadata file given by the name.
 
+        Python distribution metadata is organized by blobs of text
+        typically represented as "files" in the metadata directory
+        (e.g. package-1.0.dist-info). These files include things
+        like:
+
+        - METADATA: The distribution metadata including fields
+          like Name and Version and Description.
+        - entry_points.txt: A series of entry points as defined in
+          `the entry points spec `_.
+        - RECORD: A record of files according to
+          `this recording spec `_.
+
+        A package may provide any set of files, including those
+        not listed here or none at all.
+
         :param filename: The name of the file in the distribution info.
         :return: The text if found, otherwise None.
         """
 
     @abc.abstractmethod
-    def locate_file(self, path):
+    def locate_file(self, path: str | os.PathLike[str]) -> SimplePath:
         """
-        Given a path to a file in this distribution, return a path
+        Given a path to a file in this distribution, return a SimplePath
         to it.
+
+        This method is used by callers of ``Distribution.files()`` to
+        locate files within the distribution. If it's possible for a
+        Distribution to represent files in the distribution as
+        ``SimplePath`` objects, it should implement this method
+        to resolve such objects.
+
+        Some Distribution providers may elect not to resolve SimplePath
+        objects within the distribution by raising a
+        NotImplementedError, but consumers of such a Distribution would
+        be unable to invoke ``Distribution.files()``.
         """
 
     @classmethod
-    def from_name(cls, name: str):
+    def from_name(cls, name: str) -> Distribution:
         """Return the Distribution for the given package name.
 
         :param name: The name of the distribution package to search for.
@@ -378,21 +460,23 @@ def from_name(cls, name: str):
         if not name:
             raise ValueError("A distribution name is required.")
         try:
-            return next(cls.discover(name=name))
+            return next(iter(cls._prefer_valid(cls.discover(name=name))))
         except StopIteration:
             raise PackageNotFoundError(name)
 
     @classmethod
-    def discover(cls, **kwargs):
+    def discover(
+        cls, *, context: DistributionFinder.Context | None = None, **kwargs
+    ) -> Iterable[Distribution]:
         """Return an iterable of Distribution objects for all packages.
 
         Pass a ``context`` or pass keyword arguments for constructing
         a context.
 
         :context: A ``DistributionFinder.Context`` object.
-        :return: Iterable of Distribution objects for all packages.
+        :return: Iterable of Distribution objects for packages matching
+          the context.
         """
-        context = kwargs.pop('context', None)
         if context and kwargs:
             raise ValueError("cannot accept context and kwargs")
         context = context or DistributionFinder.Context(**kwargs)
@@ -401,8 +485,18 @@ def discover(cls, **kwargs):
         )
 
     @staticmethod
-    def at(path):
-        """Return a Distribution for the indicated metadata path
+    def _prefer_valid(dists: Iterable[Distribution]) -> Iterable[Distribution]:
+        """
+        Prefer (move to the front) distributions that have metadata.
+
+        Ref python/importlib_resources#489.
+        """
+        buckets = bucket(dists, lambda dist: bool(dist.metadata))
+        return itertools.chain(buckets[True], buckets[False])
+
+    @staticmethod
+    def at(path: str | os.PathLike[str]) -> Distribution:
+        """Return a Distribution for the indicated metadata path.
 
         :param path: a string or path-like object
         :return: a concrete Distribution instance for the path
@@ -411,19 +505,24 @@ def at(path):
 
     @staticmethod
     def _discover_resolvers():
-        """Search the meta_path for resolvers."""
+        """Search the meta_path for resolvers (MetadataPathFinders)."""
         declared = (
             getattr(finder, 'find_distributions', None) for finder in sys.meta_path
         )
         return filter(None, declared)
 
     @property
-    def metadata(self) -> _meta.PackageMetadata:
+    def metadata(self) -> _meta.PackageMetadata | None:
         """Return the parsed metadata for this Distribution.
 
         The returned object will have keys that name the various bits of
-        metadata.  See PEP 566 for details.
+        metadata per the
+        `Core metadata specifications `_.
+
+        Custom providers may provide the METADATA file or override this
+        property.
         """
+
         text = (
             self.read_text('METADATA')
             or self.read_text('PKG-INFO')
@@ -432,12 +531,20 @@ def metadata(self) -> _meta.PackageMetadata:
             # (which points to the egg-info file) attribute unchanged.
             or self.read_text('')
         )
+        return self._assemble_message(text)
+
+    @staticmethod
+    @pass_none
+    def _assemble_message(text: str) -> _meta.PackageMetadata:
+        # deferred for performance (python/cpython#109829)
+        from . import _adapters
+
         return _adapters.Message(email.message_from_string(text))
 
     @property
-    def name(self):
+    def name(self) -> str:
         """Return the 'Name' metadata for the distribution package."""
-        return self.metadata['Name']
+        return md_none(self.metadata)['Name']
 
     @property
     def _normalized_name(self):
@@ -445,24 +552,34 @@ def _normalized_name(self):
         return Prepared.normalize(self.name)
 
     @property
-    def version(self):
+    def version(self) -> str:
         """Return the 'Version' metadata for the distribution package."""
-        return self.metadata['Version']
+        return md_none(self.metadata)['Version']
 
     @property
-    def entry_points(self):
+    def entry_points(self) -> EntryPoints:
+        """
+        Return EntryPoints for this distribution.
+
+        Custom providers may provide the ``entry_points.txt`` file
+        or override this property.
+        """
         return EntryPoints._from_text_for(self.read_text('entry_points.txt'), self)
 
     @property
-    def files(self):
+    def files(self) -> list[PackagePath] | None:
         """Files in this distribution.
 
         :return: List of PackagePath for this distribution or None
 
         Result is `None` if the metadata file that enumerates files
-        (i.e. RECORD for dist-info or SOURCES.txt for egg-info) is
-        missing.
+        (i.e. RECORD for dist-info, or installed-files.txt or
+        SOURCES.txt for egg-info) is missing.
         Result may be empty if the metadata exists but is empty.
+
+        Custom providers are recommended to provide a "RECORD" file (in
+        ``read_text``) or override this property to allow for callers to be
+        able to resolve filenames provided by the package.
         """
 
         def make_file(name, hash=None, size_str=None):
@@ -474,27 +591,76 @@ def make_file(name, hash=None, size_str=None):
 
         @pass_none
         def make_files(lines):
-            return list(starmap(make_file, csv.reader(lines)))
+            # Delay csv import, since Distribution.files is not as widely used
+            # as other parts of importlib.metadata
+            import csv
 
-        return make_files(self._read_files_distinfo() or self._read_files_egginfo())
+            return starmap(make_file, csv.reader(lines))
+
+        @pass_none
+        def skip_missing_files(package_paths):
+            return list(filter(lambda path: path.locate().exists(), package_paths))
+
+        return skip_missing_files(
+            make_files(
+                self._read_files_distinfo()
+                or self._read_files_egginfo_installed()
+                or self._read_files_egginfo_sources()
+            )
+        )
 
     def _read_files_distinfo(self):
         """
-        Read the lines of RECORD
+        Read the lines of RECORD.
         """
         text = self.read_text('RECORD')
         return text and text.splitlines()
 
-    def _read_files_egginfo(self):
+    def _read_files_egginfo_installed(self):
         """
-        SOURCES.txt might contain literal commas, so wrap each line
-        in quotes.
+        Read installed-files.txt and return lines in a similar
+        CSV-parsable format as RECORD: each file must be placed
+        relative to the site-packages directory and must also be
+        quoted (since file names can contain literal commas).
+
+        This file is written when the package is installed by pip,
+        but it might not be written for other installation methods.
+        Assume the file is accurate if it exists.
+        """
+        text = self.read_text('installed-files.txt')
+        # Prepend the .egg-info/ subdir to the lines in this file.
+        # But this subdir is only available from PathDistribution's
+        # self._path.
+        subdir = getattr(self, '_path', None)
+        if not text or not subdir:
+            return
+
+        paths = (
+            py311
+            .relative_fix((subdir / name).resolve())
+            .relative_to(self.locate_file('').resolve(), walk_up=True)
+            .as_posix()
+            for name in text.splitlines()
+        )
+        return map('"{}"'.format, paths)
+
+    def _read_files_egginfo_sources(self):
+        """
+        Read SOURCES.txt and return lines in a similar CSV-parsable
+        format as RECORD: each file name must be quoted (since it
+        might contain literal commas).
+
+        Note that SOURCES.txt is not a reliable source for what
+        files are installed by a package. This file is generated
+        for a source archive, and the files that are present
+        there (e.g. setup.py) may not correctly reflect the files
+        that are present after the package has been installed.
         """
         text = self.read_text('SOURCES.txt')
         return text and map('"{}"'.format, text.splitlines())
 
     @property
-    def requires(self):
+    def requires(self) -> list[str] | None:
         """Generated requirements specified for this Distribution"""
         reqs = self._read_dist_info_reqs() or self._read_egg_info_reqs()
         return reqs and list(reqs)
@@ -545,10 +711,26 @@ def url_req_space(req):
             space = url_req_space(section.value)
             yield section.value + space + quoted_marker(section.name)
 
+    @property
+    def origin(self):
+        return self._load_json('direct_url.json')
+
+    def _load_json(self, filename):
+        # Deferred for performance (python/importlib_metadata#503)
+        import json
+
+        return pass_none(json.loads)(
+            self.read_text(filename),
+            object_hook=lambda data: types.SimpleNamespace(**data),
+        )
+
 
 class DistributionFinder(MetaPathFinder):
     """
     A MetaPathFinder capable of discovering installed distributions.
+
+    Custom providers should implement this interface in order to
+    supply metadata.
     """
 
     class Context:
@@ -561,6 +743,17 @@ class Context:
         Each DistributionFinder may expect any parameters
         and should attempt to honor the canonical
         parameters defined below when appropriate.
+
+        This mechanism gives a custom provider a means to
+        solicit additional details from the caller beyond
+        "name" and "path" when searching distributions.
+        For example, imagine a provider that exposes suites
+        of packages in either a "public" or "private" ``realm``.
+        A caller may wish to query only for distributions in
+        a particular realm and could call
+        ``distributions(realm="private")`` to signal to the
+        custom provider to only include distributions from that
+        realm.
         """
 
         name = None
@@ -573,7 +766,7 @@ def __init__(self, **kwargs):
             vars(self).update(kwargs)
 
         @property
-        def path(self):
+        def path(self) -> list[str]:
             """
             The sequence of directory path that a distribution finder
             should search.
@@ -584,7 +777,7 @@ def path(self):
             return vars(self).get('path', sys.path)
 
     @abc.abstractmethod
-    def find_distributions(self, context=Context()):
+    def find_distributions(self, context=Context()) -> Iterable[Distribution]:
         """
         Find distributions.
 
@@ -594,16 +787,38 @@ def find_distributions(self, context=Context()):
         """
 
 
+@passthrough
+def _clear_after_fork(cached):
+    """Ensure ``func`` clears cached state after ``fork`` when supported.
+
+    ``FastPath`` caches zip-backed ``pathlib.Path`` objects that retain a
+    reference to the parent's open ``ZipFile`` handle. Re-using a cached
+    instance in a forked child can therefore resurrect invalid file pointers
+    and trigger ``BadZipFile``/``OSError`` failures (python/importlib_metadata#520).
+    Registering ``cache_clear`` with ``os.register_at_fork`` keeps each process
+    on its own cache.
+    """
+    getattr(os, 'register_at_fork', noop)(after_in_child=cached.cache_clear)
+
+
 class FastPath:
     """
-    Micro-optimized class for searching a path for
-    children.
+    Micro-optimized class for searching a root for children.
+
+    Root is a path on the file system that may contain metadata
+    directories either as natural directories or within a zip file.
 
     >>> FastPath('').children()
     ['...']
+
+    FastPath objects are cached and recycled for any given root.
+
+    >>> FastPath('foobar') is FastPath('foobar')
+    True
     """
 
-    @functools.lru_cache()  # type: ignore
+    @_clear_after_fork  # type: ignore[misc]
+    @functools.lru_cache()
     def __new__(cls, root):
         return super().__new__(cls)
 
@@ -621,7 +836,10 @@ def children(self):
         return []
 
     def zip_children(self):
-        zip_path = zipp.Path(self.root)
+        # deferred for performance (python/importlib_metadata#502)
+        from zipp.compat.overlay import zipfile
+
+        zip_path = zipfile.Path(self.root)
         names = zip_path.root.namelist()
         self.joinpath = zip_path.joinpath
 
@@ -642,7 +860,19 @@ def lookup(self, mtime):
 
 
 class Lookup:
+    """
+    A micro-optimized class for searching a (fast) path for metadata.
+    """
+
     def __init__(self, path: FastPath):
+        """
+        Calculate all of the children representing metadata.
+
+        From the children in the path, calculate early all of the
+        children that appear to represent metadata (infos) or legacy
+        metadata (eggs).
+        """
+
         base = os.path.basename(path.root).lower()
         base_is_egg = base.endswith(".egg")
         self.infos = FreezableDefaultDict(list)
@@ -663,7 +893,10 @@ def __init__(self, path: FastPath):
         self.infos.freeze()
         self.eggs.freeze()
 
-    def search(self, prepared):
+    def search(self, prepared: Prepared):
+        """
+        Yield all infos and eggs matching the Prepared query.
+        """
         infos = (
             self.infos[prepared.normalized]
             if prepared
@@ -679,13 +912,28 @@ def search(self, prepared):
 
 class Prepared:
     """
-    A prepared search for metadata on a possibly-named package.
+    A prepared search query for metadata on a possibly-named package.
+
+    Pre-calculates the normalization to prevent repeated operations.
+
+    >>> none = Prepared(None)
+    >>> none.normalized
+    >>> none.legacy_normalized
+    >>> bool(none)
+    False
+    >>> sample = Prepared('Sample__Pkg-name.foo')
+    >>> sample.normalized
+    'sample_pkg_name_foo'
+    >>> sample.legacy_normalized
+    'sample__pkg_name.foo'
+    >>> bool(sample)
+    True
     """
 
     normalized = None
     legacy_normalized = None
 
-    def __init__(self, name):
+    def __init__(self, name: str | None):
         self.name = name
         if name is None:
             return
@@ -719,7 +967,10 @@ class MetadataPathFinder(NullFinder, DistributionFinder):
     of Python that do not have a PathFinder find_distributions().
     """
 
-    def find_distributions(self, context=DistributionFinder.Context()):
+    @classmethod
+    def find_distributions(
+        cls, context=DistributionFinder.Context()
+    ) -> Iterable[PathDistribution]:
         """
         Find distributions.
 
@@ -728,7 +979,7 @@ def find_distributions(self, context=DistributionFinder.Context()):
         (or all names if ``None`` indicated) along the paths in the list
         of directories ``context.path``.
         """
-        found = self._search_paths(context.name, context.path)
+        found = cls._search_paths(context.name, context.path)
         return map(PathDistribution, found)
 
     @classmethod
@@ -739,19 +990,20 @@ def _search_paths(cls, name, paths):
             path.search(prepared) for path in map(FastPath, paths)
         )
 
-    def invalidate_caches(cls):
+    @classmethod
+    def invalidate_caches(cls) -> None:
         FastPath.__new__.cache_clear()
 
 
 class PathDistribution(Distribution):
-    def __init__(self, path: SimplePath):
+    def __init__(self, path: SimplePath) -> None:
         """Construct a distribution.
 
         :param path: SimplePath indicating the metadata directory.
         """
         self._path = path
 
-    def read_text(self, filename):
+    def read_text(self, filename: str | os.PathLike[str]) -> str | None:
         with suppress(
             FileNotFoundError,
             IsADirectoryError,
@@ -761,9 +1013,11 @@ def read_text(self, filename):
         ):
             return self._path.joinpath(filename).read_text(encoding='utf-8')
 
+        return None
+
     read_text.__doc__ = Distribution.read_text.__doc__
 
-    def locate_file(self, path):
+    def locate_file(self, path: str | os.PathLike[str]) -> SimplePath:
         return self._path.parent / path
 
     @property
@@ -796,7 +1050,7 @@ def _name_from_stem(stem):
         return name
 
 
-def distribution(distribution_name):
+def distribution(distribution_name: str) -> Distribution:
     """Get the ``Distribution`` instance for the named package.
 
     :param distribution_name: The name of the distribution package as a string.
@@ -805,7 +1059,7 @@ def distribution(distribution_name):
     return Distribution.from_name(distribution_name)
 
 
-def distributions(**kwargs):
+def distributions(**kwargs) -> Iterable[Distribution]:
     """Get all ``Distribution`` instances in the current environment.
 
     :return: An iterable of ``Distribution`` instances.
@@ -813,7 +1067,7 @@ def distributions(**kwargs):
     return Distribution.discover(**kwargs)
 
 
-def metadata(distribution_name) -> _meta.PackageMetadata:
+def metadata(distribution_name: str) -> _meta.PackageMetadata | None:
     """Get the metadata for the named package.
 
     :param distribution_name: The name of the distribution package to query.
@@ -822,7 +1076,7 @@ def metadata(distribution_name) -> _meta.PackageMetadata:
     return Distribution.from_name(distribution_name).metadata
 
 
-def version(distribution_name):
+def version(distribution_name: str) -> str:
     """Get the version string for the named package.
 
     :param distribution_name: The name of the distribution package to query.
@@ -834,7 +1088,7 @@ def version(distribution_name):
 
 _unique = functools.partial(
     unique_everseen,
-    key=_py39compat.normalized_name,
+    key=py39.normalized_name,
 )
 """
 Wrapper for ``distributions`` to return unique distributions by name.
@@ -856,7 +1110,7 @@ def entry_points(**params) -> EntryPoints:
     return EntryPoints(eps).select(**params)
 
 
-def files(distribution_name):
+def files(distribution_name: str) -> list[PackagePath] | None:
     """Return a list of files for the named package.
 
     :param distribution_name: The name of the distribution package to query.
@@ -865,17 +1119,17 @@ def files(distribution_name):
     return distribution(distribution_name).files
 
 
-def requires(distribution_name):
+def requires(distribution_name: str) -> list[str] | None:
     """
     Return a list of requirements for the named package.
 
-    :return: An iterator of requirements, suitable for
+    :return: An iterable of requirements, suitable for
         packaging.requirement.Requirement.
     """
     return distribution(distribution_name).requires
 
 
-def packages_distributions() -> Mapping[str, List[str]]:
+def packages_distributions() -> Mapping[str, list[str]]:
     """
     Return a mapping of top-level packages to their
     distributions.
@@ -888,7 +1142,7 @@ def packages_distributions() -> Mapping[str, List[str]]:
     pkg_to_dist = collections.defaultdict(list)
     for dist in distributions():
         for pkg in _top_level_declared(dist) or _top_level_inferred(dist):
-            pkg_to_dist[pkg].append(dist.metadata['Name'])
+            pkg_to_dist[pkg].append(md_none(dist.metadata)['Name'])
     return dict(pkg_to_dist)
 
 
@@ -896,9 +1150,42 @@ def _top_level_declared(dist):
     return (dist.read_text('top_level.txt') or '').split()
 
 
+def _topmost(name: PackagePath) -> str | None:
+    """
+    Return the top-most parent as long as there is a parent.
+    """
+    top, *rest = name.parts
+    return top if rest else None
+
+
+def _get_toplevel_name(name: PackagePath) -> str:
+    """
+    Infer a possibly importable module name from a name presumed on
+    sys.path.
+
+    >>> _get_toplevel_name(PackagePath('foo.py'))
+    'foo'
+    >>> _get_toplevel_name(PackagePath('foo'))
+    'foo'
+    >>> _get_toplevel_name(PackagePath('foo.pyc'))
+    'foo'
+    >>> _get_toplevel_name(PackagePath('foo/__init__.py'))
+    'foo'
+    >>> _get_toplevel_name(PackagePath('foo.pth'))
+    'foo.pth'
+    >>> _get_toplevel_name(PackagePath('foo.dist-info'))
+    'foo.dist-info'
+    """
+    # Defer import of inspect for performance (python/cpython#118761)
+    import inspect
+
+    return _topmost(name) or inspect.getmodulename(name) or str(name)
+
+
 def _top_level_inferred(dist):
-    return {
-        f.parts[0] if len(f.parts) > 1 else f.with_suffix('').name
-        for f in always_iterable(dist.files)
-        if f.suffix == ".py"
-    }
+    opt_names = set(map(_get_toplevel_name, always_iterable(dist.files)))
+
+    def importable_name(name):
+        return '.' not in name
+
+    return filter(importable_name, opt_names)
diff --git a/setuptools/_vendor/importlib_metadata/_adapters.py b/setuptools/_vendor/importlib_metadata/_adapters.py
index e33cba5e44..dede395d79 100644
--- a/setuptools/_vendor/importlib_metadata/_adapters.py
+++ b/setuptools/_vendor/importlib_metadata/_adapters.py
@@ -1,23 +1,59 @@
-import functools
-import warnings
+import email.message
+import email.policy
 import re
 import textwrap
-import email.message
 
 from ._text import FoldedCase
-from ._compat import pypy_partial
 
 
-# Do not remove prior to 2024-01-01 or Python 3.14
-_warn = functools.partial(
-    warnings.warn,
-    "Implicit None on return values is deprecated and will raise KeyErrors.",
-    DeprecationWarning,
-    stacklevel=pypy_partial(2),
-)
+class RawPolicy(email.policy.EmailPolicy):
+    def fold(self, name, value):
+        folded = self.linesep.join(
+            textwrap
+            .indent(value, prefix=' ' * 8, predicate=lambda line: True)
+            .lstrip()
+            .splitlines()
+        )
+        return f'{name}: {folded}{self.linesep}'
 
 
 class Message(email.message.Message):
+    r"""
+    Specialized Message subclass to handle metadata naturally.
+
+    Reads values that may have newlines in them and converts the
+    payload to the Description.
+
+    >>> msg_text = textwrap.dedent('''
+    ...     Name: Foo
+    ...     Version: 3.0
+    ...     License: blah
+    ...             de-blah
+    ...     
+    ...     First line of description.
+    ...     Second line of description.
+    ...     
+    ...     Fourth line!
+    ...     ''').lstrip().replace('', '')
+    >>> msg = Message(email.message_from_string(msg_text))
+    >>> msg['Description']
+    'First line of description.\nSecond line of description.\n\nFourth line!\n'
+
+    Message should render even if values contain newlines.
+
+    >>> print(msg)
+    Name: Foo
+    Version: 3.0
+    License: blah
+            de-blah
+    Description: First line of description.
+            Second line of description.
+    
+            Fourth line!
+    
+    
+    """
+
     multiple_use_keys = set(
         map(
             FoldedCase,
@@ -53,26 +89,36 @@ def __iter__(self):
 
     def __getitem__(self, item):
         """
-        Warn users that a ``KeyError`` can be expected when a
-        mising key is supplied. Ref python/importlib_metadata#371.
+        Override parent behavior to typical dict behavior.
+
+        ``email.message.Message`` will emit None values for missing
+        keys. Typical mappings, including this ``Message``, will raise
+        a key error for missing keys.
+
+        Ref python/importlib_metadata#371.
         """
         res = super().__getitem__(item)
         if res is None:
-            _warn()
+            raise KeyError(item)
         return res
 
     def _repair_headers(self):
         def redent(value):
             "Correct for RFC822 indentation"
-            if not value or '\n' not in value:
+            indent = ' ' * 8
+            if not value or '\n' + indent not in value:
                 return value
-            return textwrap.dedent(' ' * 8 + value)
+            return textwrap.dedent(indent + value)
 
         headers = [(key, redent(value)) for key, value in vars(self)['_headers']]
         if self._payload:
             headers.append(('Description', self.get_payload()))
+            self.set_payload('')
         return headers
 
+    def as_string(self):
+        return super().as_string(policy=RawPolicy())
+
     @property
     def json(self):
         """
diff --git a/setuptools/_vendor/importlib_metadata/_collections.py b/setuptools/_vendor/importlib_metadata/_collections.py
index cf0954e1a3..fc5045d36b 100644
--- a/setuptools/_vendor/importlib_metadata/_collections.py
+++ b/setuptools/_vendor/importlib_metadata/_collections.py
@@ -1,4 +1,5 @@
 import collections
+import typing
 
 
 # from jaraco.collections 3.3
@@ -24,7 +25,10 @@ def freeze(self):
         self._frozen = lambda key: self.default_factory()
 
 
-class Pair(collections.namedtuple('Pair', 'name value')):
+class Pair(typing.NamedTuple):
+    name: str
+    value: str
+
     @classmethod
     def parse(cls, text):
         return cls(*map(str.strip, text.split("=", 1)))
diff --git a/setuptools/_vendor/importlib_metadata/_compat.py b/setuptools/_vendor/importlib_metadata/_compat.py
index 84f9eea4f3..01356d69b9 100644
--- a/setuptools/_vendor/importlib_metadata/_compat.py
+++ b/setuptools/_vendor/importlib_metadata/_compat.py
@@ -1,15 +1,7 @@
-import sys
 import platform
+import sys
 
-
-__all__ = ['install', 'NullFinder', 'Protocol']
-
-
-try:
-    from typing import Protocol
-except ImportError:  # pragma: no cover
-    # Python 3.7 compatibility
-    from ..typing_extensions import Protocol  # type: ignore
+__all__ = ['install', 'NullFinder']
 
 
 def install(cls):
@@ -45,7 +37,7 @@ def matches(finder):
 
 class NullFinder:
     """
-    A "Finder" (aka "MetaClassFinder") that never finds any modules,
+    A "Finder" (aka "MetaPathFinder") that never finds any modules,
     but may find distributions.
     """
 
@@ -53,14 +45,6 @@ class NullFinder:
     def find_spec(*args, **kwargs):
         return None
 
-    # In Python 2, the import system requires finders
-    # to have a find_module() method, but this usage
-    # is deprecated in Python 3 in favor of find_spec().
-    # For the purposes of this finder (i.e. being present
-    # on sys.meta_path but having no other import
-    # system functionality), the two methods are identical.
-    find_module = find_spec
-
 
 def pypy_partial(val):
     """
diff --git a/setuptools/_vendor/importlib_metadata/_functools.py b/setuptools/_vendor/importlib_metadata/_functools.py
index 71f66bd03c..b1fd04a84a 100644
--- a/setuptools/_vendor/importlib_metadata/_functools.py
+++ b/setuptools/_vendor/importlib_metadata/_functools.py
@@ -1,5 +1,6 @@
-import types
 import functools
+import types
+from typing import Callable, TypeVar
 
 
 # from jaraco.functools 3.3
@@ -102,3 +103,33 @@ def wrapper(param, *args, **kwargs):
             return func(param, *args, **kwargs)
 
     return wrapper
+
+
+# From jaraco.functools 4.4
+def noop(*args, **kwargs):
+    """
+    A no-operation function that does nothing.
+
+    >>> noop(1, 2, three=3)
+    """
+
+
+_T = TypeVar('_T')
+
+
+# From jaraco.functools 4.4
+def passthrough(func: Callable[..., object]) -> Callable[[_T], _T]:
+    """
+    Wrap the function to always return the first parameter.
+
+    >>> passthrough(print)('3')
+    3
+    '3'
+    """
+
+    @functools.wraps(func)
+    def wrapper(first: _T, *args, **kwargs) -> _T:
+        func(first, *args, **kwargs)
+        return first
+
+    return wrapper  # type: ignore[return-value]
diff --git a/setuptools/_vendor/importlib_metadata/_itertools.py b/setuptools/_vendor/importlib_metadata/_itertools.py
index d4ca9b9140..79d37198ce 100644
--- a/setuptools/_vendor/importlib_metadata/_itertools.py
+++ b/setuptools/_vendor/importlib_metadata/_itertools.py
@@ -1,3 +1,4 @@
+from collections import defaultdict, deque
 from itertools import filterfalse
 
 
@@ -71,3 +72,100 @@ def always_iterable(obj, base_type=(str, bytes)):
         return iter(obj)
     except TypeError:
         return iter((obj,))
+
+
+# Copied from more_itertools 10.3
+class bucket:
+    """Wrap *iterable* and return an object that buckets the iterable into
+    child iterables based on a *key* function.
+
+        >>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3']
+        >>> s = bucket(iterable, key=lambda x: x[0])  # Bucket by 1st character
+        >>> sorted(list(s))  # Get the keys
+        ['a', 'b', 'c']
+        >>> a_iterable = s['a']
+        >>> next(a_iterable)
+        'a1'
+        >>> next(a_iterable)
+        'a2'
+        >>> list(s['b'])
+        ['b1', 'b2', 'b3']
+
+    The original iterable will be advanced and its items will be cached until
+    they are used by the child iterables. This may require significant storage.
+
+    By default, attempting to select a bucket to which no items belong  will
+    exhaust the iterable and cache all values.
+    If you specify a *validator* function, selected buckets will instead be
+    checked against it.
+
+        >>> from itertools import count
+        >>> it = count(1, 2)  # Infinite sequence of odd numbers
+        >>> key = lambda x: x % 10  # Bucket by last digit
+        >>> validator = lambda x: x in {1, 3, 5, 7, 9}  # Odd digits only
+        >>> s = bucket(it, key=key, validator=validator)
+        >>> 2 in s
+        False
+        >>> list(s[2])
+        []
+
+    """
+
+    def __init__(self, iterable, key, validator=None):
+        self._it = iter(iterable)
+        self._key = key
+        self._cache = defaultdict(deque)
+        self._validator = validator or (lambda x: True)
+
+    def __contains__(self, value):
+        if not self._validator(value):
+            return False
+
+        try:
+            item = next(self[value])
+        except StopIteration:
+            return False
+        else:
+            self._cache[value].appendleft(item)
+
+        return True
+
+    def _get_values(self, value):
+        """
+        Helper to yield items from the parent iterator that match *value*.
+        Items that don't match are stored in the local cache as they
+        are encountered.
+        """
+        while True:
+            # If we've cached some items that match the target value, emit
+            # the first one and evict it from the cache.
+            if self._cache[value]:
+                yield self._cache[value].popleft()
+            # Otherwise we need to advance the parent iterator to search for
+            # a matching item, caching the rest.
+            else:
+                while True:
+                    try:
+                        item = next(self._it)
+                    except StopIteration:
+                        return
+                    item_value = self._key(item)
+                    if item_value == value:
+                        yield item
+                        break
+                    elif self._validator(item_value):
+                        self._cache[item_value].append(item)
+
+    def __iter__(self):
+        for item in self._it:
+            item_value = self._key(item)
+            if self._validator(item_value):
+                self._cache[item_value].append(item)
+
+        yield from self._cache.keys()
+
+    def __getitem__(self, value):
+        if not self._validator(value):
+            return iter(())
+
+        return self._get_values(value)
diff --git a/setuptools/_vendor/importlib_metadata/_meta.py b/setuptools/_vendor/importlib_metadata/_meta.py
index 259b15ba19..0c20eff3da 100644
--- a/setuptools/_vendor/importlib_metadata/_meta.py
+++ b/setuptools/_vendor/importlib_metadata/_meta.py
@@ -1,49 +1,71 @@
-from ._compat import Protocol
-from typing import Any, Dict, Iterator, List, TypeVar, Union
+from __future__ import annotations
 
+import os
+from collections.abc import Iterator
+from typing import (
+    Any,
+    Protocol,
+    TypeVar,
+    overload,
+)
 
 _T = TypeVar("_T")
 
 
 class PackageMetadata(Protocol):
-    def __len__(self) -> int:
-        ...  # pragma: no cover
+    def __len__(self) -> int: ...  # pragma: no cover
 
-    def __contains__(self, item: str) -> bool:
-        ...  # pragma: no cover
+    def __contains__(self, item: str) -> bool: ...  # pragma: no cover
 
-    def __getitem__(self, key: str) -> str:
-        ...  # pragma: no cover
+    def __getitem__(self, key: str) -> str: ...  # pragma: no cover
 
-    def __iter__(self) -> Iterator[str]:
-        ...  # pragma: no cover
+    def __iter__(self) -> Iterator[str]: ...  # pragma: no cover
 
-    def get_all(self, name: str, failobj: _T = ...) -> Union[List[Any], _T]:
+    @overload
+    def get(
+        self, name: str, failobj: None = None
+    ) -> str | None: ...  # pragma: no cover
+
+    @overload
+    def get(self, name: str, failobj: _T) -> str | _T: ...  # pragma: no cover
+
+    # overload per python/importlib_metadata#435
+    @overload
+    def get_all(
+        self, name: str, failobj: None = None
+    ) -> list[Any] | None: ...  # pragma: no cover
+
+    @overload
+    def get_all(self, name: str, failobj: _T) -> list[Any] | _T:
         """
         Return all values associated with a possibly multi-valued key.
         """
 
     @property
-    def json(self) -> Dict[str, Union[str, List[str]]]:
+    def json(self) -> dict[str, str | list[str]]:
         """
         A JSON-compatible form of the metadata.
         """
 
 
-class SimplePath(Protocol[_T]):
+class SimplePath(Protocol):
     """
-    A minimal subset of pathlib.Path required by PathDistribution.
+    A minimal subset of pathlib.Path required by Distribution.
     """
 
-    def joinpath(self) -> _T:
-        ...  # pragma: no cover
+    def joinpath(
+        self, other: str | os.PathLike[str]
+    ) -> SimplePath: ...  # pragma: no cover
 
-    def __truediv__(self, other: Union[str, _T]) -> _T:
-        ...  # pragma: no cover
+    def __truediv__(
+        self, other: str | os.PathLike[str]
+    ) -> SimplePath: ...  # pragma: no cover
 
     @property
-    def parent(self) -> _T:
-        ...  # pragma: no cover
+    def parent(self) -> SimplePath: ...  # pragma: no cover
+
+    def read_text(self, encoding=None) -> str: ...  # pragma: no cover
+
+    def read_bytes(self) -> bytes: ...  # pragma: no cover
 
-    def read_text(self) -> str:
-        ...  # pragma: no cover
+    def exists(self) -> bool: ...  # pragma: no cover
diff --git a/setuptools/_vendor/importlib_metadata/_typing.py b/setuptools/_vendor/importlib_metadata/_typing.py
new file mode 100644
index 0000000000..32b1d2b98a
--- /dev/null
+++ b/setuptools/_vendor/importlib_metadata/_typing.py
@@ -0,0 +1,15 @@
+import functools
+import typing
+
+from ._meta import PackageMetadata
+
+md_none = functools.partial(typing.cast, PackageMetadata)
+"""
+Suppress type errors for optional metadata.
+
+Although Distribution.metadata can return None when metadata is corrupt
+and thus None, allow callers to assume it's not None and crash if
+that's the case.
+
+# python/importlib_metadata#493
+"""
diff --git a/pkg_resources/_vendor/importlib_resources/tests/data01/__init__.py b/setuptools/_vendor/importlib_metadata/compat/__init__.py
similarity index 100%
rename from pkg_resources/_vendor/importlib_resources/tests/data01/__init__.py
rename to setuptools/_vendor/importlib_metadata/compat/__init__.py
diff --git a/setuptools/_vendor/importlib_metadata/compat/py311.py b/setuptools/_vendor/importlib_metadata/compat/py311.py
new file mode 100644
index 0000000000..3a5327436f
--- /dev/null
+++ b/setuptools/_vendor/importlib_metadata/compat/py311.py
@@ -0,0 +1,22 @@
+import os
+import pathlib
+import sys
+import types
+
+
+def wrap(path):  # pragma: no cover
+    """
+    Workaround for https://github.com/python/cpython/issues/84538
+    to add backward compatibility for walk_up=True.
+    An example affected package is dask-labextension, which uses
+    jupyter-packaging to install JupyterLab javascript files outside
+    of site-packages.
+    """
+
+    def relative_to(root, *, walk_up=False):
+        return pathlib.Path(os.path.relpath(path, root))
+
+    return types.SimpleNamespace(relative_to=relative_to)
+
+
+relative_fix = wrap if sys.version_info < (3, 12) else lambda x: x
diff --git a/setuptools/_vendor/importlib_metadata/_py39compat.py b/setuptools/_vendor/importlib_metadata/compat/py39.py
similarity index 60%
rename from setuptools/_vendor/importlib_metadata/_py39compat.py
rename to setuptools/_vendor/importlib_metadata/compat/py39.py
index cde4558fbb..3eb9c01ecb 100644
--- a/setuptools/_vendor/importlib_metadata/_py39compat.py
+++ b/setuptools/_vendor/importlib_metadata/compat/py39.py
@@ -1,25 +1,32 @@
 """
 Compatibility layer with Python 3.8/3.9
 """
-from typing import TYPE_CHECKING, Any, Optional
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
 
 if TYPE_CHECKING:  # pragma: no cover
     # Prevent circular imports on runtime.
-    from . import Distribution, EntryPoint
+    from .. import Distribution, EntryPoint
 else:
     Distribution = EntryPoint = Any
 
+from .._typing import md_none
+
 
-def normalized_name(dist: Distribution) -> Optional[str]:
+def normalized_name(dist: Distribution) -> str | None:
     """
     Honor name normalization for distributions that don't provide ``_normalized_name``.
     """
     try:
         return dist._normalized_name
     except AttributeError:
-        from . import Prepared  # -> delay to prevent circular imports.
+        from .. import Prepared  # -> delay to prevent circular imports.
 
-        return Prepared.normalize(getattr(dist, "name", None) or dist.metadata['Name'])
+        return Prepared.normalize(
+            getattr(dist, "name", None) or md_none(dist.metadata)['Name']
+        )
 
 
 def ep_matches(ep: EntryPoint, **params) -> bool:
@@ -29,7 +36,7 @@ def ep_matches(ep: EntryPoint, **params) -> bool:
     try:
         return ep.matches(**params)
     except AttributeError:
-        from . import EntryPoint  # -> delay to prevent circular imports.
+        from .. import EntryPoint  # -> delay to prevent circular imports.
 
         # Reconstruct the EntryPoint object to make sure it is compatible.
         return EntryPoint(ep.name, ep.value, ep.group).matches(**params)
diff --git a/setuptools/_vendor/importlib_metadata/diagnose.py b/setuptools/_vendor/importlib_metadata/diagnose.py
new file mode 100644
index 0000000000..e405471ac4
--- /dev/null
+++ b/setuptools/_vendor/importlib_metadata/diagnose.py
@@ -0,0 +1,21 @@
+import sys
+
+from . import Distribution
+
+
+def inspect(path):
+    print("Inspecting", path)
+    dists = list(Distribution.discover(path=[path]))
+    if not dists:
+        return
+    print("Found", len(dists), "packages:", end=' ')
+    print(', '.join(dist.name for dist in dists))
+
+
+def run():
+    for path in sys.path:
+        inspect(path)
+
+
+if __name__ == '__main__':
+    run()
diff --git a/setuptools/_vendor/importlib_resources-5.10.2.dist-info/INSTALLER b/setuptools/_vendor/importlib_resources-5.10.2.dist-info/INSTALLER
deleted file mode 100644
index a1b589e38a..0000000000
--- a/setuptools/_vendor/importlib_resources-5.10.2.dist-info/INSTALLER
+++ /dev/null
@@ -1 +0,0 @@
-pip
diff --git a/setuptools/_vendor/importlib_resources-5.10.2.dist-info/LICENSE b/setuptools/_vendor/importlib_resources-5.10.2.dist-info/LICENSE
deleted file mode 100644
index d645695673..0000000000
--- a/setuptools/_vendor/importlib_resources-5.10.2.dist-info/LICENSE
+++ /dev/null
@@ -1,202 +0,0 @@
-
-                                 Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
-
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
-
-   END OF TERMS AND CONDITIONS
-
-   APPENDIX: How to apply the Apache License to your work.
-
-      To apply the Apache License to your work, attach the following
-      boilerplate notice, with the fields enclosed by brackets "[]"
-      replaced with your own identifying information. (Don't include
-      the brackets!)  The text should be enclosed in the appropriate
-      comment syntax for the file format. We also recommend that a
-      file or class name and description of purpose be included on the
-      same "printed page" as the copyright notice for easier
-      identification within third-party archives.
-
-   Copyright [yyyy] [name of copyright owner]
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-   you may not use this file except in compliance with the License.
-   You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
diff --git a/setuptools/_vendor/importlib_resources-5.10.2.dist-info/METADATA b/setuptools/_vendor/importlib_resources-5.10.2.dist-info/METADATA
deleted file mode 100644
index a9995f09a3..0000000000
--- a/setuptools/_vendor/importlib_resources-5.10.2.dist-info/METADATA
+++ /dev/null
@@ -1,104 +0,0 @@
-Metadata-Version: 2.1
-Name: importlib-resources
-Version: 5.10.2
-Summary: Read resources from Python packages
-Home-page: https://github.com/python/importlib_resources
-Author: Barry Warsaw
-Author-email: barry@python.org
-Project-URL: Documentation, https://importlib-resources.readthedocs.io/
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: Apache Software License
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3 :: Only
-Requires-Python: >=3.7
-License-File: LICENSE
-Requires-Dist: zipp (>=3.1.0) ; python_version < "3.10"
-Provides-Extra: docs
-Requires-Dist: sphinx (>=3.5) ; extra == 'docs'
-Requires-Dist: jaraco.packaging (>=9) ; extra == 'docs'
-Requires-Dist: rst.linker (>=1.9) ; extra == 'docs'
-Requires-Dist: furo ; extra == 'docs'
-Requires-Dist: sphinx-lint ; extra == 'docs'
-Requires-Dist: jaraco.tidelift (>=1.4) ; extra == 'docs'
-Provides-Extra: testing
-Requires-Dist: pytest (>=6) ; extra == 'testing'
-Requires-Dist: pytest-checkdocs (>=2.4) ; extra == 'testing'
-Requires-Dist: flake8 (<5) ; extra == 'testing'
-Requires-Dist: pytest-cov ; extra == 'testing'
-Requires-Dist: pytest-enabler (>=1.3) ; extra == 'testing'
-Requires-Dist: pytest-black (>=0.3.7) ; (platform_python_implementation != "PyPy") and extra == 'testing'
-Requires-Dist: pytest-mypy (>=0.9.1) ; (platform_python_implementation != "PyPy") and extra == 'testing'
-Requires-Dist: pytest-flake8 ; (python_version < "3.12") and extra == 'testing'
-
-.. image:: https://img.shields.io/pypi/v/importlib_resources.svg
-   :target: https://pypi.org/project/importlib_resources
-
-.. image:: https://img.shields.io/pypi/pyversions/importlib_resources.svg
-
-.. image:: https://github.com/python/importlib_resources/workflows/tests/badge.svg
-   :target: https://github.com/python/importlib_resources/actions?query=workflow%3A%22tests%22
-   :alt: tests
-
-.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
-   :target: https://github.com/psf/black
-   :alt: Code style: Black
-
-.. image:: https://readthedocs.org/projects/importlib-resources/badge/?version=latest
-   :target: https://importlib-resources.readthedocs.io/en/latest/?badge=latest
-
-.. image:: https://img.shields.io/badge/skeleton-2022-informational
-   :target: https://blog.jaraco.com/skeleton
-
-.. image:: https://tidelift.com/badges/package/pypi/importlib-resources
-   :target: https://tidelift.com/subscription/pkg/pypi-importlib-resources?utm_source=pypi-importlib-resources&utm_medium=readme
-
-``importlib_resources`` is a backport of Python standard library
-`importlib.resources
-`_
-module for older Pythons.
-
-The key goal of this module is to replace parts of `pkg_resources
-`_ with a
-solution in Python's stdlib that relies on well-defined APIs.  This makes
-reading resources included in packages easier, with more stable and consistent
-semantics.
-
-Compatibility
-=============
-
-New features are introduced in this third-party library and later merged
-into CPython. The following table indicates which versions of this library
-were contributed to different versions in the standard library:
-
-.. list-table::
-   :header-rows: 1
-
-   * - importlib_resources
-     - stdlib
-   * - 5.9
-     - 3.12
-   * - 5.7
-     - 3.11
-   * - 5.0
-     - 3.10
-   * - 1.3
-     - 3.9
-   * - 0.5 (?)
-     - 3.7
-
-For Enterprise
-==============
-
-Available as part of the Tidelift Subscription.
-
-This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
-
-`Learn more `_.
-
-Security Contact
-================
-
-To report a security vulnerability, please use the
-`Tidelift security contact `_.
-Tidelift will coordinate the fix and disclosure.
diff --git a/setuptools/_vendor/importlib_resources-5.10.2.dist-info/RECORD b/setuptools/_vendor/importlib_resources-5.10.2.dist-info/RECORD
deleted file mode 100644
index 7d19852d4a..0000000000
--- a/setuptools/_vendor/importlib_resources-5.10.2.dist-info/RECORD
+++ /dev/null
@@ -1,77 +0,0 @@
-importlib_resources-5.10.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-importlib_resources-5.10.2.dist-info/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
-importlib_resources-5.10.2.dist-info/METADATA,sha256=Xo5ntATvDYUxdmW8tr8kxtfdiOC9889mOk-LE1LtZfI,4111
-importlib_resources-5.10.2.dist-info/RECORD,,
-importlib_resources-5.10.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-importlib_resources-5.10.2.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92
-importlib_resources-5.10.2.dist-info/top_level.txt,sha256=fHIjHU1GZwAjvcydpmUnUrTnbvdiWjG4OEVZK8by0TQ,20
-importlib_resources/__init__.py,sha256=evPm12kLgYqTm-pbzm60bOuumumT8IpBNWFp0uMyrzE,506
-importlib_resources/__pycache__/__init__.cpython-311.pyc,,
-importlib_resources/__pycache__/_adapters.cpython-311.pyc,,
-importlib_resources/__pycache__/_common.cpython-311.pyc,,
-importlib_resources/__pycache__/_compat.cpython-311.pyc,,
-importlib_resources/__pycache__/_itertools.cpython-311.pyc,,
-importlib_resources/__pycache__/_legacy.cpython-311.pyc,,
-importlib_resources/__pycache__/abc.cpython-311.pyc,,
-importlib_resources/__pycache__/readers.cpython-311.pyc,,
-importlib_resources/__pycache__/simple.cpython-311.pyc,,
-importlib_resources/_adapters.py,sha256=o51tP2hpVtohP33gSYyAkGNpLfYDBqxxYsadyiRZi1E,4504
-importlib_resources/_common.py,sha256=jSC4xfLdcMNbtbWHtpzbFkNa0W7kvf__nsYn14C_AEU,5457
-importlib_resources/_compat.py,sha256=dSadF6WPt8MwOqSm_NIOQPhw4x0iaMYTWxi-XS93p7M,2923
-importlib_resources/_itertools.py,sha256=WCdJ1Gs_kNFwKENyIG7TO0Y434IWCu0zjVVSsSbZwU8,884
-importlib_resources/_legacy.py,sha256=0TKdZixxLWA-xwtAZw4HcpqJmj4Xprx1Zkcty0gTRZY,3481
-importlib_resources/abc.py,sha256=Icr2IJ2QtH7vvAB9vC5WRJ9KBoaDyJa7KUs8McuROzo,5140
-importlib_resources/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-importlib_resources/readers.py,sha256=PZsi5qacr2Qn3KHw4qw3Gm1MzrBblPHoTdjqjH7EKWw,3581
-importlib_resources/simple.py,sha256=0__2TQBTQoqkajYmNPt1HxERcReAT6boVKJA328pr04,2576
-importlib_resources/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-importlib_resources/tests/__pycache__/__init__.cpython-311.pyc,,
-importlib_resources/tests/__pycache__/_compat.cpython-311.pyc,,
-importlib_resources/tests/__pycache__/_path.cpython-311.pyc,,
-importlib_resources/tests/__pycache__/test_compatibilty_files.cpython-311.pyc,,
-importlib_resources/tests/__pycache__/test_contents.cpython-311.pyc,,
-importlib_resources/tests/__pycache__/test_files.cpython-311.pyc,,
-importlib_resources/tests/__pycache__/test_open.cpython-311.pyc,,
-importlib_resources/tests/__pycache__/test_path.cpython-311.pyc,,
-importlib_resources/tests/__pycache__/test_read.cpython-311.pyc,,
-importlib_resources/tests/__pycache__/test_reader.cpython-311.pyc,,
-importlib_resources/tests/__pycache__/test_resource.cpython-311.pyc,,
-importlib_resources/tests/__pycache__/update-zips.cpython-311.pyc,,
-importlib_resources/tests/__pycache__/util.cpython-311.pyc,,
-importlib_resources/tests/_compat.py,sha256=YTSB0U1R9oADnh6GrQcOCgojxcF_N6H1LklymEWf9SQ,708
-importlib_resources/tests/_path.py,sha256=yZyWsQzJZQ1Z8ARAxWkjAdaVVsjlzyqxO0qjBUofJ8M,1039
-importlib_resources/tests/data01/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-importlib_resources/tests/data01/__pycache__/__init__.cpython-311.pyc,,
-importlib_resources/tests/data01/binary.file,sha256=BU7ewdAhH2JP7Qy8qdT5QAsOSRxDdCryxbCr6_DJkNg,4
-importlib_resources/tests/data01/subdirectory/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-importlib_resources/tests/data01/subdirectory/__pycache__/__init__.cpython-311.pyc,,
-importlib_resources/tests/data01/subdirectory/binary.file,sha256=BU7ewdAhH2JP7Qy8qdT5QAsOSRxDdCryxbCr6_DJkNg,4
-importlib_resources/tests/data01/utf-16.file,sha256=t5q9qhxX0rYqItBOM8D3ylwG-RHrnOYteTLtQr6sF7g,44
-importlib_resources/tests/data01/utf-8.file,sha256=kwWgYG4yQ-ZF2X_WA66EjYPmxJRn-w8aSOiS9e8tKYY,20
-importlib_resources/tests/data02/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-importlib_resources/tests/data02/__pycache__/__init__.cpython-311.pyc,,
-importlib_resources/tests/data02/one/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-importlib_resources/tests/data02/one/__pycache__/__init__.cpython-311.pyc,,
-importlib_resources/tests/data02/one/resource1.txt,sha256=10flKac7c-XXFzJ3t-AB5MJjlBy__dSZvPE_dOm2q6U,13
-importlib_resources/tests/data02/two/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-importlib_resources/tests/data02/two/__pycache__/__init__.cpython-311.pyc,,
-importlib_resources/tests/data02/two/resource2.txt,sha256=lt2jbN3TMn9QiFKM832X39bU_62UptDdUkoYzkvEbl0,13
-importlib_resources/tests/namespacedata01/binary.file,sha256=BU7ewdAhH2JP7Qy8qdT5QAsOSRxDdCryxbCr6_DJkNg,4
-importlib_resources/tests/namespacedata01/utf-16.file,sha256=t5q9qhxX0rYqItBOM8D3ylwG-RHrnOYteTLtQr6sF7g,44
-importlib_resources/tests/namespacedata01/utf-8.file,sha256=kwWgYG4yQ-ZF2X_WA66EjYPmxJRn-w8aSOiS9e8tKYY,20
-importlib_resources/tests/test_compatibilty_files.py,sha256=NWkbIsylI8Wz3Dwsxo1quT4ZI6ToXFA2mojCG6Dzuxw,3260
-importlib_resources/tests/test_contents.py,sha256=V1Xfk3lqTDdvUsZuV18Kndf0CT_tkM2oEIwk9Vv0rhg,968
-importlib_resources/tests/test_files.py,sha256=1Y8da-g0xOQLzuREDYUiRc_qhWlvFNeydW_mUH7l15w,3251
-importlib_resources/tests/test_open.py,sha256=pmEgdrSFdM83L6FxtR8U_RT9BfI3JZ4snGmM_ZZIegY,2565
-importlib_resources/tests/test_path.py,sha256=xvPteNA-UKavDhKgLgrQuXSxKWYH7Q4nSNDVfBX95Gs,2103
-importlib_resources/tests/test_read.py,sha256=EyYvpHJ_7F4LuX2EU_c5EerIBQfRhOFmiIR7LOc5Y5E,2408
-importlib_resources/tests/test_reader.py,sha256=nPhldbYPq3fXoQs0ZAub4atjhp2lgNyLNv2G1pg6Agw,4480
-importlib_resources/tests/test_resource.py,sha256=EMoarxTEHcrq8R41LQDsndIG8Idtm4I_LpN8DYpHtT0,8478
-importlib_resources/tests/update-zips.py,sha256=x-SrO5v87iLLUMXyefxDwAd3imAs_slI94sLWvJ6N40,1417
-importlib_resources/tests/util.py,sha256=ARAlxZ47wC-lgR7PGlmgBoi4HnhzcykD5Is2-TAwY0I,4873
-importlib_resources/tests/zipdata01/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-importlib_resources/tests/zipdata01/__pycache__/__init__.cpython-311.pyc,,
-importlib_resources/tests/zipdata01/ziptestdata.zip,sha256=z5Of4dsv3T0t-46B0MsVhxlhsPGMz28aUhJDWpj3_oY,876
-importlib_resources/tests/zipdata02/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-importlib_resources/tests/zipdata02/__pycache__/__init__.cpython-311.pyc,,
-importlib_resources/tests/zipdata02/ziptestdata.zip,sha256=ydI-_j-xgQ7tDxqBp9cjOqXBGxUp6ZBbwVJu6Xj-nrY,698
diff --git a/setuptools/_vendor/importlib_resources-5.10.2.dist-info/WHEEL b/setuptools/_vendor/importlib_resources-5.10.2.dist-info/WHEEL
deleted file mode 100644
index 57e3d840d5..0000000000
--- a/setuptools/_vendor/importlib_resources-5.10.2.dist-info/WHEEL
+++ /dev/null
@@ -1,5 +0,0 @@
-Wheel-Version: 1.0
-Generator: bdist_wheel (0.38.4)
-Root-Is-Purelib: true
-Tag: py3-none-any
-
diff --git a/setuptools/_vendor/importlib_resources-5.10.2.dist-info/top_level.txt b/setuptools/_vendor/importlib_resources-5.10.2.dist-info/top_level.txt
deleted file mode 100644
index 58ad1bd333..0000000000
--- a/setuptools/_vendor/importlib_resources-5.10.2.dist-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-importlib_resources
diff --git a/setuptools/_vendor/importlib_resources/__init__.py b/setuptools/_vendor/importlib_resources/__init__.py
deleted file mode 100644
index 34e3a9950c..0000000000
--- a/setuptools/_vendor/importlib_resources/__init__.py
+++ /dev/null
@@ -1,36 +0,0 @@
-"""Read resources contained within a package."""
-
-from ._common import (
-    as_file,
-    files,
-    Package,
-)
-
-from ._legacy import (
-    contents,
-    open_binary,
-    read_binary,
-    open_text,
-    read_text,
-    is_resource,
-    path,
-    Resource,
-)
-
-from .abc import ResourceReader
-
-
-__all__ = [
-    'Package',
-    'Resource',
-    'ResourceReader',
-    'as_file',
-    'contents',
-    'files',
-    'is_resource',
-    'open_binary',
-    'open_text',
-    'path',
-    'read_binary',
-    'read_text',
-]
diff --git a/setuptools/_vendor/importlib_resources/_adapters.py b/setuptools/_vendor/importlib_resources/_adapters.py
deleted file mode 100644
index ea363d86a5..0000000000
--- a/setuptools/_vendor/importlib_resources/_adapters.py
+++ /dev/null
@@ -1,170 +0,0 @@
-from contextlib import suppress
-from io import TextIOWrapper
-
-from . import abc
-
-
-class SpecLoaderAdapter:
-    """
-    Adapt a package spec to adapt the underlying loader.
-    """
-
-    def __init__(self, spec, adapter=lambda spec: spec.loader):
-        self.spec = spec
-        self.loader = adapter(spec)
-
-    def __getattr__(self, name):
-        return getattr(self.spec, name)
-
-
-class TraversableResourcesLoader:
-    """
-    Adapt a loader to provide TraversableResources.
-    """
-
-    def __init__(self, spec):
-        self.spec = spec
-
-    def get_resource_reader(self, name):
-        return CompatibilityFiles(self.spec)._native()
-
-
-def _io_wrapper(file, mode='r', *args, **kwargs):
-    if mode == 'r':
-        return TextIOWrapper(file, *args, **kwargs)
-    elif mode == 'rb':
-        return file
-    raise ValueError(
-        "Invalid mode value '{}', only 'r' and 'rb' are supported".format(mode)
-    )
-
-
-class CompatibilityFiles:
-    """
-    Adapter for an existing or non-existent resource reader
-    to provide a compatibility .files().
-    """
-
-    class SpecPath(abc.Traversable):
-        """
-        Path tied to a module spec.
-        Can be read and exposes the resource reader children.
-        """
-
-        def __init__(self, spec, reader):
-            self._spec = spec
-            self._reader = reader
-
-        def iterdir(self):
-            if not self._reader:
-                return iter(())
-            return iter(
-                CompatibilityFiles.ChildPath(self._reader, path)
-                for path in self._reader.contents()
-            )
-
-        def is_file(self):
-            return False
-
-        is_dir = is_file
-
-        def joinpath(self, other):
-            if not self._reader:
-                return CompatibilityFiles.OrphanPath(other)
-            return CompatibilityFiles.ChildPath(self._reader, other)
-
-        @property
-        def name(self):
-            return self._spec.name
-
-        def open(self, mode='r', *args, **kwargs):
-            return _io_wrapper(self._reader.open_resource(None), mode, *args, **kwargs)
-
-    class ChildPath(abc.Traversable):
-        """
-        Path tied to a resource reader child.
-        Can be read but doesn't expose any meaningful children.
-        """
-
-        def __init__(self, reader, name):
-            self._reader = reader
-            self._name = name
-
-        def iterdir(self):
-            return iter(())
-
-        def is_file(self):
-            return self._reader.is_resource(self.name)
-
-        def is_dir(self):
-            return not self.is_file()
-
-        def joinpath(self, other):
-            return CompatibilityFiles.OrphanPath(self.name, other)
-
-        @property
-        def name(self):
-            return self._name
-
-        def open(self, mode='r', *args, **kwargs):
-            return _io_wrapper(
-                self._reader.open_resource(self.name), mode, *args, **kwargs
-            )
-
-    class OrphanPath(abc.Traversable):
-        """
-        Orphan path, not tied to a module spec or resource reader.
-        Can't be read and doesn't expose any meaningful children.
-        """
-
-        def __init__(self, *path_parts):
-            if len(path_parts) < 1:
-                raise ValueError('Need at least one path part to construct a path')
-            self._path = path_parts
-
-        def iterdir(self):
-            return iter(())
-
-        def is_file(self):
-            return False
-
-        is_dir = is_file
-
-        def joinpath(self, other):
-            return CompatibilityFiles.OrphanPath(*self._path, other)
-
-        @property
-        def name(self):
-            return self._path[-1]
-
-        def open(self, mode='r', *args, **kwargs):
-            raise FileNotFoundError("Can't open orphan path")
-
-    def __init__(self, spec):
-        self.spec = spec
-
-    @property
-    def _reader(self):
-        with suppress(AttributeError):
-            return self.spec.loader.get_resource_reader(self.spec.name)
-
-    def _native(self):
-        """
-        Return the native reader if it supports files().
-        """
-        reader = self._reader
-        return reader if hasattr(reader, 'files') else self
-
-    def __getattr__(self, attr):
-        return getattr(self._reader, attr)
-
-    def files(self):
-        return CompatibilityFiles.SpecPath(self.spec, self._reader)
-
-
-def wrap_spec(package):
-    """
-    Construct a package spec with traversable compatibility
-    on the spec/loader/reader.
-    """
-    return SpecLoaderAdapter(package.__spec__, TraversableResourcesLoader)
diff --git a/setuptools/_vendor/importlib_resources/_common.py b/setuptools/_vendor/importlib_resources/_common.py
deleted file mode 100644
index 3c6de1cfb2..0000000000
--- a/setuptools/_vendor/importlib_resources/_common.py
+++ /dev/null
@@ -1,207 +0,0 @@
-import os
-import pathlib
-import tempfile
-import functools
-import contextlib
-import types
-import importlib
-import inspect
-import warnings
-import itertools
-
-from typing import Union, Optional, cast
-from .abc import ResourceReader, Traversable
-
-from ._compat import wrap_spec
-
-Package = Union[types.ModuleType, str]
-Anchor = Package
-
-
-def package_to_anchor(func):
-    """
-    Replace 'package' parameter as 'anchor' and warn about the change.
-
-    Other errors should fall through.
-
-    >>> files('a', 'b')
-    Traceback (most recent call last):
-    TypeError: files() takes from 0 to 1 positional arguments but 2 were given
-    """
-    undefined = object()
-
-    @functools.wraps(func)
-    def wrapper(anchor=undefined, package=undefined):
-        if package is not undefined:
-            if anchor is not undefined:
-                return func(anchor, package)
-            warnings.warn(
-                "First parameter to files is renamed to 'anchor'",
-                DeprecationWarning,
-                stacklevel=2,
-            )
-            return func(package)
-        elif anchor is undefined:
-            return func()
-        return func(anchor)
-
-    return wrapper
-
-
-@package_to_anchor
-def files(anchor: Optional[Anchor] = None) -> Traversable:
-    """
-    Get a Traversable resource for an anchor.
-    """
-    return from_package(resolve(anchor))
-
-
-def get_resource_reader(package: types.ModuleType) -> Optional[ResourceReader]:
-    """
-    Return the package's loader if it's a ResourceReader.
-    """
-    # We can't use
-    # a issubclass() check here because apparently abc.'s __subclasscheck__()
-    # hook wants to create a weak reference to the object, but
-    # zipimport.zipimporter does not support weak references, resulting in a
-    # TypeError.  That seems terrible.
-    spec = package.__spec__
-    reader = getattr(spec.loader, 'get_resource_reader', None)  # type: ignore
-    if reader is None:
-        return None
-    return reader(spec.name)  # type: ignore
-
-
-@functools.singledispatch
-def resolve(cand: Optional[Anchor]) -> types.ModuleType:
-    return cast(types.ModuleType, cand)
-
-
-@resolve.register
-def _(cand: str) -> types.ModuleType:
-    return importlib.import_module(cand)
-
-
-@resolve.register
-def _(cand: None) -> types.ModuleType:
-    return resolve(_infer_caller().f_globals['__name__'])
-
-
-def _infer_caller():
-    """
-    Walk the stack and find the frame of the first caller not in this module.
-    """
-
-    def is_this_file(frame_info):
-        return frame_info.filename == __file__
-
-    def is_wrapper(frame_info):
-        return frame_info.function == 'wrapper'
-
-    not_this_file = itertools.filterfalse(is_this_file, inspect.stack())
-    # also exclude 'wrapper' due to singledispatch in the call stack
-    callers = itertools.filterfalse(is_wrapper, not_this_file)
-    return next(callers).frame
-
-
-def from_package(package: types.ModuleType):
-    """
-    Return a Traversable object for the given package.
-
-    """
-    spec = wrap_spec(package)
-    reader = spec.loader.get_resource_reader(spec.name)
-    return reader.files()
-
-
-@contextlib.contextmanager
-def _tempfile(
-    reader,
-    suffix='',
-    # gh-93353: Keep a reference to call os.remove() in late Python
-    # finalization.
-    *,
-    _os_remove=os.remove,
-):
-    # Not using tempfile.NamedTemporaryFile as it leads to deeper 'try'
-    # blocks due to the need to close the temporary file to work on Windows
-    # properly.
-    fd, raw_path = tempfile.mkstemp(suffix=suffix)
-    try:
-        try:
-            os.write(fd, reader())
-        finally:
-            os.close(fd)
-        del reader
-        yield pathlib.Path(raw_path)
-    finally:
-        try:
-            _os_remove(raw_path)
-        except FileNotFoundError:
-            pass
-
-
-def _temp_file(path):
-    return _tempfile(path.read_bytes, suffix=path.name)
-
-
-def _is_present_dir(path: Traversable) -> bool:
-    """
-    Some Traversables implement ``is_dir()`` to raise an
-    exception (i.e. ``FileNotFoundError``) when the
-    directory doesn't exist. This function wraps that call
-    to always return a boolean and only return True
-    if there's a dir and it exists.
-    """
-    with contextlib.suppress(FileNotFoundError):
-        return path.is_dir()
-    return False
-
-
-@functools.singledispatch
-def as_file(path):
-    """
-    Given a Traversable object, return that object as a
-    path on the local file system in a context manager.
-    """
-    return _temp_dir(path) if _is_present_dir(path) else _temp_file(path)
-
-
-@as_file.register(pathlib.Path)
-@contextlib.contextmanager
-def _(path):
-    """
-    Degenerate behavior for pathlib.Path objects.
-    """
-    yield path
-
-
-@contextlib.contextmanager
-def _temp_path(dir: tempfile.TemporaryDirectory):
-    """
-    Wrap tempfile.TemporyDirectory to return a pathlib object.
-    """
-    with dir as result:
-        yield pathlib.Path(result)
-
-
-@contextlib.contextmanager
-def _temp_dir(path):
-    """
-    Given a traversable dir, recursively replicate the whole tree
-    to the file system in a context manager.
-    """
-    assert path.is_dir()
-    with _temp_path(tempfile.TemporaryDirectory()) as temp_dir:
-        yield _write_contents(temp_dir, path)
-
-
-def _write_contents(target, source):
-    child = target.joinpath(source.name)
-    if source.is_dir():
-        child.mkdir()
-        for item in source.iterdir():
-            _write_contents(child, item)
-    else:
-        child.write_bytes(source.read_bytes())
-    return child
diff --git a/setuptools/_vendor/importlib_resources/_compat.py b/setuptools/_vendor/importlib_resources/_compat.py
deleted file mode 100644
index 8b5b1d280f..0000000000
--- a/setuptools/_vendor/importlib_resources/_compat.py
+++ /dev/null
@@ -1,108 +0,0 @@
-# flake8: noqa
-
-import abc
-import os
-import sys
-import pathlib
-from contextlib import suppress
-from typing import Union
-
-
-if sys.version_info >= (3, 10):
-    from zipfile import Path as ZipPath  # type: ignore
-else:
-    from ..zipp import Path as ZipPath  # type: ignore
-
-
-try:
-    from typing import runtime_checkable  # type: ignore
-except ImportError:
-
-    def runtime_checkable(cls):  # type: ignore
-        return cls
-
-
-try:
-    from typing import Protocol  # type: ignore
-except ImportError:
-    Protocol = abc.ABC  # type: ignore
-
-
-class TraversableResourcesLoader:
-    """
-    Adapt loaders to provide TraversableResources and other
-    compatibility.
-
-    Used primarily for Python 3.9 and earlier where the native
-    loaders do not yet implement TraversableResources.
-    """
-
-    def __init__(self, spec):
-        self.spec = spec
-
-    @property
-    def path(self):
-        return self.spec.origin
-
-    def get_resource_reader(self, name):
-        from . import readers, _adapters
-
-        def _zip_reader(spec):
-            with suppress(AttributeError):
-                return readers.ZipReader(spec.loader, spec.name)
-
-        def _namespace_reader(spec):
-            with suppress(AttributeError, ValueError):
-                return readers.NamespaceReader(spec.submodule_search_locations)
-
-        def _available_reader(spec):
-            with suppress(AttributeError):
-                return spec.loader.get_resource_reader(spec.name)
-
-        def _native_reader(spec):
-            reader = _available_reader(spec)
-            return reader if hasattr(reader, 'files') else None
-
-        def _file_reader(spec):
-            try:
-                path = pathlib.Path(self.path)
-            except TypeError:
-                return None
-            if path.exists():
-                return readers.FileReader(self)
-
-        return (
-            # native reader if it supplies 'files'
-            _native_reader(self.spec)
-            or
-            # local ZipReader if a zip module
-            _zip_reader(self.spec)
-            or
-            # local NamespaceReader if a namespace module
-            _namespace_reader(self.spec)
-            or
-            # local FileReader
-            _file_reader(self.spec)
-            # fallback - adapt the spec ResourceReader to TraversableReader
-            or _adapters.CompatibilityFiles(self.spec)
-        )
-
-
-def wrap_spec(package):
-    """
-    Construct a package spec with traversable compatibility
-    on the spec/loader/reader.
-
-    Supersedes _adapters.wrap_spec to use TraversableResourcesLoader
-    from above for older Python compatibility (<3.10).
-    """
-    from . import _adapters
-
-    return _adapters.SpecLoaderAdapter(package.__spec__, TraversableResourcesLoader)
-
-
-if sys.version_info >= (3, 9):
-    StrPath = Union[str, os.PathLike[str]]
-else:
-    # PathLike is only subscriptable at runtime in 3.9+
-    StrPath = Union[str, "os.PathLike[str]"]
diff --git a/setuptools/_vendor/importlib_resources/_itertools.py b/setuptools/_vendor/importlib_resources/_itertools.py
deleted file mode 100644
index cce05582ff..0000000000
--- a/setuptools/_vendor/importlib_resources/_itertools.py
+++ /dev/null
@@ -1,35 +0,0 @@
-from itertools import filterfalse
-
-from typing import (
-    Callable,
-    Iterable,
-    Iterator,
-    Optional,
-    Set,
-    TypeVar,
-    Union,
-)
-
-# Type and type variable definitions
-_T = TypeVar('_T')
-_U = TypeVar('_U')
-
-
-def unique_everseen(
-    iterable: Iterable[_T], key: Optional[Callable[[_T], _U]] = None
-) -> Iterator[_T]:
-    "List unique elements, preserving order. Remember all elements ever seen."
-    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
-    # unique_everseen('ABBCcAD', str.lower) --> A B C D
-    seen: Set[Union[_T, _U]] = set()
-    seen_add = seen.add
-    if key is None:
-        for element in filterfalse(seen.__contains__, iterable):
-            seen_add(element)
-            yield element
-    else:
-        for element in iterable:
-            k = key(element)
-            if k not in seen:
-                seen_add(k)
-                yield element
diff --git a/setuptools/_vendor/importlib_resources/_legacy.py b/setuptools/_vendor/importlib_resources/_legacy.py
deleted file mode 100644
index b1ea8105da..0000000000
--- a/setuptools/_vendor/importlib_resources/_legacy.py
+++ /dev/null
@@ -1,120 +0,0 @@
-import functools
-import os
-import pathlib
-import types
-import warnings
-
-from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any
-
-from . import _common
-
-Package = Union[types.ModuleType, str]
-Resource = str
-
-
-def deprecated(func):
-    @functools.wraps(func)
-    def wrapper(*args, **kwargs):
-        warnings.warn(
-            f"{func.__name__} is deprecated. Use files() instead. "
-            "Refer to https://importlib-resources.readthedocs.io"
-            "/en/latest/using.html#migrating-from-legacy for migration advice.",
-            DeprecationWarning,
-            stacklevel=2,
-        )
-        return func(*args, **kwargs)
-
-    return wrapper
-
-
-def normalize_path(path: Any) -> str:
-    """Normalize a path by ensuring it is a string.
-
-    If the resulting string contains path separators, an exception is raised.
-    """
-    str_path = str(path)
-    parent, file_name = os.path.split(str_path)
-    if parent:
-        raise ValueError(f'{path!r} must be only a file name')
-    return file_name
-
-
-@deprecated
-def open_binary(package: Package, resource: Resource) -> BinaryIO:
-    """Return a file-like object opened for binary reading of the resource."""
-    return (_common.files(package) / normalize_path(resource)).open('rb')
-
-
-@deprecated
-def read_binary(package: Package, resource: Resource) -> bytes:
-    """Return the binary contents of the resource."""
-    return (_common.files(package) / normalize_path(resource)).read_bytes()
-
-
-@deprecated
-def open_text(
-    package: Package,
-    resource: Resource,
-    encoding: str = 'utf-8',
-    errors: str = 'strict',
-) -> TextIO:
-    """Return a file-like object opened for text reading of the resource."""
-    return (_common.files(package) / normalize_path(resource)).open(
-        'r', encoding=encoding, errors=errors
-    )
-
-
-@deprecated
-def read_text(
-    package: Package,
-    resource: Resource,
-    encoding: str = 'utf-8',
-    errors: str = 'strict',
-) -> str:
-    """Return the decoded string of the resource.
-
-    The decoding-related arguments have the same semantics as those of
-    bytes.decode().
-    """
-    with open_text(package, resource, encoding, errors) as fp:
-        return fp.read()
-
-
-@deprecated
-def contents(package: Package) -> Iterable[str]:
-    """Return an iterable of entries in `package`.
-
-    Note that not all entries are resources.  Specifically, directories are
-    not considered resources.  Use `is_resource()` on each entry returned here
-    to check if it is a resource or not.
-    """
-    return [path.name for path in _common.files(package).iterdir()]
-
-
-@deprecated
-def is_resource(package: Package, name: str) -> bool:
-    """True if `name` is a resource inside `package`.
-
-    Directories are *not* resources.
-    """
-    resource = normalize_path(name)
-    return any(
-        traversable.name == resource and traversable.is_file()
-        for traversable in _common.files(package).iterdir()
-    )
-
-
-@deprecated
-def path(
-    package: Package,
-    resource: Resource,
-) -> ContextManager[pathlib.Path]:
-    """A context manager providing a file path object to the resource.
-
-    If the resource does not already exist on its own on the file system,
-    a temporary file will be created. If the file was created, the file
-    will be deleted upon exiting the context manager (no exception is
-    raised if the file was deleted prior to the context manager
-    exiting).
-    """
-    return _common.as_file(_common.files(package) / normalize_path(resource))
diff --git a/setuptools/_vendor/importlib_resources/abc.py b/setuptools/_vendor/importlib_resources/abc.py
deleted file mode 100644
index 23b6aeafe4..0000000000
--- a/setuptools/_vendor/importlib_resources/abc.py
+++ /dev/null
@@ -1,170 +0,0 @@
-import abc
-import io
-import itertools
-import pathlib
-from typing import Any, BinaryIO, Iterable, Iterator, NoReturn, Text, Optional
-
-from ._compat import runtime_checkable, Protocol, StrPath
-
-
-__all__ = ["ResourceReader", "Traversable", "TraversableResources"]
-
-
-class ResourceReader(metaclass=abc.ABCMeta):
-    """Abstract base class for loaders to provide resource reading support."""
-
-    @abc.abstractmethod
-    def open_resource(self, resource: Text) -> BinaryIO:
-        """Return an opened, file-like object for binary reading.
-
-        The 'resource' argument is expected to represent only a file name.
-        If the resource cannot be found, FileNotFoundError is raised.
-        """
-        # This deliberately raises FileNotFoundError instead of
-        # NotImplementedError so that if this method is accidentally called,
-        # it'll still do the right thing.
-        raise FileNotFoundError
-
-    @abc.abstractmethod
-    def resource_path(self, resource: Text) -> Text:
-        """Return the file system path to the specified resource.
-
-        The 'resource' argument is expected to represent only a file name.
-        If the resource does not exist on the file system, raise
-        FileNotFoundError.
-        """
-        # This deliberately raises FileNotFoundError instead of
-        # NotImplementedError so that if this method is accidentally called,
-        # it'll still do the right thing.
-        raise FileNotFoundError
-
-    @abc.abstractmethod
-    def is_resource(self, path: Text) -> bool:
-        """Return True if the named 'path' is a resource.
-
-        Files are resources, directories are not.
-        """
-        raise FileNotFoundError
-
-    @abc.abstractmethod
-    def contents(self) -> Iterable[str]:
-        """Return an iterable of entries in `package`."""
-        raise FileNotFoundError
-
-
-class TraversalError(Exception):
-    pass
-
-
-@runtime_checkable
-class Traversable(Protocol):
-    """
-    An object with a subset of pathlib.Path methods suitable for
-    traversing directories and opening files.
-
-    Any exceptions that occur when accessing the backing resource
-    may propagate unaltered.
-    """
-
-    @abc.abstractmethod
-    def iterdir(self) -> Iterator["Traversable"]:
-        """
-        Yield Traversable objects in self
-        """
-
-    def read_bytes(self) -> bytes:
-        """
-        Read contents of self as bytes
-        """
-        with self.open('rb') as strm:
-            return strm.read()
-
-    def read_text(self, encoding: Optional[str] = None) -> str:
-        """
-        Read contents of self as text
-        """
-        with self.open(encoding=encoding) as strm:
-            return strm.read()
-
-    @abc.abstractmethod
-    def is_dir(self) -> bool:
-        """
-        Return True if self is a directory
-        """
-
-    @abc.abstractmethod
-    def is_file(self) -> bool:
-        """
-        Return True if self is a file
-        """
-
-    def joinpath(self, *descendants: StrPath) -> "Traversable":
-        """
-        Return Traversable resolved with any descendants applied.
-
-        Each descendant should be a path segment relative to self
-        and each may contain multiple levels separated by
-        ``posixpath.sep`` (``/``).
-        """
-        if not descendants:
-            return self
-        names = itertools.chain.from_iterable(
-            path.parts for path in map(pathlib.PurePosixPath, descendants)
-        )
-        target = next(names)
-        matches = (
-            traversable for traversable in self.iterdir() if traversable.name == target
-        )
-        try:
-            match = next(matches)
-        except StopIteration:
-            raise TraversalError(
-                "Target not found during traversal.", target, list(names)
-            )
-        return match.joinpath(*names)
-
-    def __truediv__(self, child: StrPath) -> "Traversable":
-        """
-        Return Traversable child in self
-        """
-        return self.joinpath(child)
-
-    @abc.abstractmethod
-    def open(self, mode='r', *args, **kwargs):
-        """
-        mode may be 'r' or 'rb' to open as text or binary. Return a handle
-        suitable for reading (same as pathlib.Path.open).
-
-        When opening as text, accepts encoding parameters such as those
-        accepted by io.TextIOWrapper.
-        """
-
-    @property
-    @abc.abstractmethod
-    def name(self) -> str:
-        """
-        The base name of this object without any parent references.
-        """
-
-
-class TraversableResources(ResourceReader):
-    """
-    The required interface for providing traversable
-    resources.
-    """
-
-    @abc.abstractmethod
-    def files(self) -> "Traversable":
-        """Return a Traversable object for the loaded package."""
-
-    def open_resource(self, resource: StrPath) -> io.BufferedReader:
-        return self.files().joinpath(resource).open('rb')
-
-    def resource_path(self, resource: Any) -> NoReturn:
-        raise FileNotFoundError(resource)
-
-    def is_resource(self, path: StrPath) -> bool:
-        return self.files().joinpath(path).is_file()
-
-    def contents(self) -> Iterator[str]:
-        return (item.name for item in self.files().iterdir())
diff --git a/setuptools/_vendor/importlib_resources/py.typed b/setuptools/_vendor/importlib_resources/py.typed
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/setuptools/_vendor/importlib_resources/readers.py b/setuptools/_vendor/importlib_resources/readers.py
deleted file mode 100644
index ab34db7409..0000000000
--- a/setuptools/_vendor/importlib_resources/readers.py
+++ /dev/null
@@ -1,120 +0,0 @@
-import collections
-import pathlib
-import operator
-
-from . import abc
-
-from ._itertools import unique_everseen
-from ._compat import ZipPath
-
-
-def remove_duplicates(items):
-    return iter(collections.OrderedDict.fromkeys(items))
-
-
-class FileReader(abc.TraversableResources):
-    def __init__(self, loader):
-        self.path = pathlib.Path(loader.path).parent
-
-    def resource_path(self, resource):
-        """
-        Return the file system path to prevent
-        `resources.path()` from creating a temporary
-        copy.
-        """
-        return str(self.path.joinpath(resource))
-
-    def files(self):
-        return self.path
-
-
-class ZipReader(abc.TraversableResources):
-    def __init__(self, loader, module):
-        _, _, name = module.rpartition('.')
-        self.prefix = loader.prefix.replace('\\', '/') + name + '/'
-        self.archive = loader.archive
-
-    def open_resource(self, resource):
-        try:
-            return super().open_resource(resource)
-        except KeyError as exc:
-            raise FileNotFoundError(exc.args[0])
-
-    def is_resource(self, path):
-        # workaround for `zipfile.Path.is_file` returning true
-        # for non-existent paths.
-        target = self.files().joinpath(path)
-        return target.is_file() and target.exists()
-
-    def files(self):
-        return ZipPath(self.archive, self.prefix)
-
-
-class MultiplexedPath(abc.Traversable):
-    """
-    Given a series of Traversable objects, implement a merged
-    version of the interface across all objects. Useful for
-    namespace packages which may be multihomed at a single
-    name.
-    """
-
-    def __init__(self, *paths):
-        self._paths = list(map(pathlib.Path, remove_duplicates(paths)))
-        if not self._paths:
-            message = 'MultiplexedPath must contain at least one path'
-            raise FileNotFoundError(message)
-        if not all(path.is_dir() for path in self._paths):
-            raise NotADirectoryError('MultiplexedPath only supports directories')
-
-    def iterdir(self):
-        files = (file for path in self._paths for file in path.iterdir())
-        return unique_everseen(files, key=operator.attrgetter('name'))
-
-    def read_bytes(self):
-        raise FileNotFoundError(f'{self} is not a file')
-
-    def read_text(self, *args, **kwargs):
-        raise FileNotFoundError(f'{self} is not a file')
-
-    def is_dir(self):
-        return True
-
-    def is_file(self):
-        return False
-
-    def joinpath(self, *descendants):
-        try:
-            return super().joinpath(*descendants)
-        except abc.TraversalError:
-            # One of the paths did not resolve (a directory does not exist).
-            # Just return something that will not exist.
-            return self._paths[0].joinpath(*descendants)
-
-    def open(self, *args, **kwargs):
-        raise FileNotFoundError(f'{self} is not a file')
-
-    @property
-    def name(self):
-        return self._paths[0].name
-
-    def __repr__(self):
-        paths = ', '.join(f"'{path}'" for path in self._paths)
-        return f'MultiplexedPath({paths})'
-
-
-class NamespaceReader(abc.TraversableResources):
-    def __init__(self, namespace_path):
-        if 'NamespacePath' not in str(namespace_path):
-            raise ValueError('Invalid path')
-        self.path = MultiplexedPath(*list(namespace_path))
-
-    def resource_path(self, resource):
-        """
-        Return the file system path to prevent
-        `resources.path()` from creating a temporary
-        copy.
-        """
-        return str(self.path.joinpath(resource))
-
-    def files(self):
-        return self.path
diff --git a/setuptools/_vendor/importlib_resources/simple.py b/setuptools/_vendor/importlib_resources/simple.py
deleted file mode 100644
index 7770c922c8..0000000000
--- a/setuptools/_vendor/importlib_resources/simple.py
+++ /dev/null
@@ -1,106 +0,0 @@
-"""
-Interface adapters for low-level readers.
-"""
-
-import abc
-import io
-import itertools
-from typing import BinaryIO, List
-
-from .abc import Traversable, TraversableResources
-
-
-class SimpleReader(abc.ABC):
-    """
-    The minimum, low-level interface required from a resource
-    provider.
-    """
-
-    @property
-    @abc.abstractmethod
-    def package(self) -> str:
-        """
-        The name of the package for which this reader loads resources.
-        """
-
-    @abc.abstractmethod
-    def children(self) -> List['SimpleReader']:
-        """
-        Obtain an iterable of SimpleReader for available
-        child containers (e.g. directories).
-        """
-
-    @abc.abstractmethod
-    def resources(self) -> List[str]:
-        """
-        Obtain available named resources for this virtual package.
-        """
-
-    @abc.abstractmethod
-    def open_binary(self, resource: str) -> BinaryIO:
-        """
-        Obtain a File-like for a named resource.
-        """
-
-    @property
-    def name(self):
-        return self.package.split('.')[-1]
-
-
-class ResourceContainer(Traversable):
-    """
-    Traversable container for a package's resources via its reader.
-    """
-
-    def __init__(self, reader: SimpleReader):
-        self.reader = reader
-
-    def is_dir(self):
-        return True
-
-    def is_file(self):
-        return False
-
-    def iterdir(self):
-        files = (ResourceHandle(self, name) for name in self.reader.resources)
-        dirs = map(ResourceContainer, self.reader.children())
-        return itertools.chain(files, dirs)
-
-    def open(self, *args, **kwargs):
-        raise IsADirectoryError()
-
-
-class ResourceHandle(Traversable):
-    """
-    Handle to a named resource in a ResourceReader.
-    """
-
-    def __init__(self, parent: ResourceContainer, name: str):
-        self.parent = parent
-        self.name = name  # type: ignore
-
-    def is_file(self):
-        return True
-
-    def is_dir(self):
-        return False
-
-    def open(self, mode='r', *args, **kwargs):
-        stream = self.parent.reader.open_binary(self.name)
-        if 'b' not in mode:
-            stream = io.TextIOWrapper(*args, **kwargs)
-        return stream
-
-    def joinpath(self, name):
-        raise RuntimeError("Cannot traverse into a resource")
-
-
-class TraversableReader(TraversableResources, SimpleReader):
-    """
-    A TraversableResources based on SimpleReader. Resource providers
-    may derive from this class to provide the TraversableResources
-    interface by supplying the SimpleReader interface.
-    """
-
-    def files(self):
-        return ResourceContainer(self)
diff --git a/setuptools/_vendor/importlib_resources/tests/__init__.py b/setuptools/_vendor/importlib_resources/tests/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/setuptools/_vendor/importlib_resources/tests/_compat.py b/setuptools/_vendor/importlib_resources/tests/_compat.py
deleted file mode 100644
index e7bf06dd4e..0000000000
--- a/setuptools/_vendor/importlib_resources/tests/_compat.py
+++ /dev/null
@@ -1,32 +0,0 @@
-import os
-
-
-try:
-    from test.support import import_helper  # type: ignore
-except ImportError:
-    # Python 3.9 and earlier
-    class import_helper:  # type: ignore
-        from test.support import (
-            modules_setup,
-            modules_cleanup,
-            DirsOnSysPath,
-            CleanImport,
-        )
-
-
-try:
-    from test.support import os_helper  # type: ignore
-except ImportError:
-    # Python 3.9 compat
-    class os_helper:  # type:ignore
-        from test.support import temp_dir
-
-
-try:
-    # Python 3.10
-    from test.support.os_helper import unlink
-except ImportError:
-    from test.support import unlink as _unlink
-
-    def unlink(target):
-        return _unlink(os.fspath(target))
diff --git a/setuptools/_vendor/importlib_resources/tests/_path.py b/setuptools/_vendor/importlib_resources/tests/_path.py
deleted file mode 100644
index c630e4d3d3..0000000000
--- a/setuptools/_vendor/importlib_resources/tests/_path.py
+++ /dev/null
@@ -1,50 +0,0 @@
-import pathlib
-import functools
-
-
-####
-# from jaraco.path 3.4
-
-
-def build(spec, prefix=pathlib.Path()):
-    """
-    Build a set of files/directories, as described by the spec.
-
-    Each key represents a pathname, and the value represents
-    the content. Content may be a nested directory.
-
-    >>> spec = {
-    ...     'README.txt': "A README file",
-    ...     "foo": {
-    ...         "__init__.py": "",
-    ...         "bar": {
-    ...             "__init__.py": "",
-    ...         },
-    ...         "baz.py": "# Some code",
-    ...     }
-    ... }
-    >>> tmpdir = getfixture('tmpdir')
-    >>> build(spec, tmpdir)
-    """
-    for name, contents in spec.items():
-        create(contents, pathlib.Path(prefix) / name)
-
-
-@functools.singledispatch
-def create(content, path):
-    path.mkdir(exist_ok=True)
-    build(content, prefix=path)  # type: ignore
-
-
-@create.register
-def _(content: bytes, path):
-    path.write_bytes(content)
-
-
-@create.register
-def _(content: str, path):
-    path.write_text(content)
-
-
-# end from jaraco.path
-####
diff --git a/setuptools/_vendor/importlib_resources/tests/data01/__init__.py b/setuptools/_vendor/importlib_resources/tests/data01/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/setuptools/_vendor/importlib_resources/tests/data01/binary.file b/setuptools/_vendor/importlib_resources/tests/data01/binary.file
deleted file mode 100644
index eaf36c1dac..0000000000
Binary files a/setuptools/_vendor/importlib_resources/tests/data01/binary.file and /dev/null differ
diff --git a/setuptools/_vendor/importlib_resources/tests/data01/subdirectory/__init__.py b/setuptools/_vendor/importlib_resources/tests/data01/subdirectory/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/setuptools/_vendor/importlib_resources/tests/data01/subdirectory/binary.file b/setuptools/_vendor/importlib_resources/tests/data01/subdirectory/binary.file
deleted file mode 100644
index eaf36c1dac..0000000000
Binary files a/setuptools/_vendor/importlib_resources/tests/data01/subdirectory/binary.file and /dev/null differ
diff --git a/setuptools/_vendor/importlib_resources/tests/data01/utf-16.file b/setuptools/_vendor/importlib_resources/tests/data01/utf-16.file
deleted file mode 100644
index 2cb772295e..0000000000
Binary files a/setuptools/_vendor/importlib_resources/tests/data01/utf-16.file and /dev/null differ
diff --git a/setuptools/_vendor/importlib_resources/tests/data01/utf-8.file b/setuptools/_vendor/importlib_resources/tests/data01/utf-8.file
deleted file mode 100644
index 1c0132ad90..0000000000
--- a/setuptools/_vendor/importlib_resources/tests/data01/utf-8.file
+++ /dev/null
@@ -1 +0,0 @@
-Hello, UTF-8 world!
diff --git a/setuptools/_vendor/importlib_resources/tests/data02/__init__.py b/setuptools/_vendor/importlib_resources/tests/data02/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/setuptools/_vendor/importlib_resources/tests/data02/one/__init__.py b/setuptools/_vendor/importlib_resources/tests/data02/one/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/setuptools/_vendor/importlib_resources/tests/data02/one/resource1.txt b/setuptools/_vendor/importlib_resources/tests/data02/one/resource1.txt
deleted file mode 100644
index 61a813e401..0000000000
--- a/setuptools/_vendor/importlib_resources/tests/data02/one/resource1.txt
+++ /dev/null
@@ -1 +0,0 @@
-one resource
diff --git a/setuptools/_vendor/importlib_resources/tests/data02/two/__init__.py b/setuptools/_vendor/importlib_resources/tests/data02/two/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/setuptools/_vendor/importlib_resources/tests/data02/two/resource2.txt b/setuptools/_vendor/importlib_resources/tests/data02/two/resource2.txt
deleted file mode 100644
index a80ce46ea3..0000000000
--- a/setuptools/_vendor/importlib_resources/tests/data02/two/resource2.txt
+++ /dev/null
@@ -1 +0,0 @@
-two resource
diff --git a/setuptools/_vendor/importlib_resources/tests/namespacedata01/binary.file b/setuptools/_vendor/importlib_resources/tests/namespacedata01/binary.file
deleted file mode 100644
index eaf36c1dac..0000000000
Binary files a/setuptools/_vendor/importlib_resources/tests/namespacedata01/binary.file and /dev/null differ
diff --git a/setuptools/_vendor/importlib_resources/tests/namespacedata01/utf-16.file b/setuptools/_vendor/importlib_resources/tests/namespacedata01/utf-16.file
deleted file mode 100644
index 2cb772295e..0000000000
Binary files a/setuptools/_vendor/importlib_resources/tests/namespacedata01/utf-16.file and /dev/null differ
diff --git a/setuptools/_vendor/importlib_resources/tests/namespacedata01/utf-8.file b/setuptools/_vendor/importlib_resources/tests/namespacedata01/utf-8.file
deleted file mode 100644
index 1c0132ad90..0000000000
--- a/setuptools/_vendor/importlib_resources/tests/namespacedata01/utf-8.file
+++ /dev/null
@@ -1 +0,0 @@
-Hello, UTF-8 world!
diff --git a/setuptools/_vendor/importlib_resources/tests/test_compatibilty_files.py b/setuptools/_vendor/importlib_resources/tests/test_compatibilty_files.py
deleted file mode 100644
index d92c7c56c9..0000000000
--- a/setuptools/_vendor/importlib_resources/tests/test_compatibilty_files.py
+++ /dev/null
@@ -1,102 +0,0 @@
-import io
-import unittest
-
-import importlib_resources as resources
-
-from importlib_resources._adapters import (
-    CompatibilityFiles,
-    wrap_spec,
-)
-
-from . import util
-
-
-class CompatibilityFilesTests(unittest.TestCase):
-    @property
-    def package(self):
-        bytes_data = io.BytesIO(b'Hello, world!')
-        return util.create_package(
-            file=bytes_data,
-            path='some_path',
-            contents=('a', 'b', 'c'),
-        )
-
-    @property
-    def files(self):
-        return resources.files(self.package)
-
-    def test_spec_path_iter(self):
-        self.assertEqual(
-            sorted(path.name for path in self.files.iterdir()),
-            ['a', 'b', 'c'],
-        )
-
-    def test_child_path_iter(self):
-        self.assertEqual(list((self.files / 'a').iterdir()), [])
-
-    def test_orphan_path_iter(self):
-        self.assertEqual(list((self.files / 'a' / 'a').iterdir()), [])
-        self.assertEqual(list((self.files / 'a' / 'a' / 'a').iterdir()), [])
-
-    def test_spec_path_is(self):
-        self.assertFalse(self.files.is_file())
-        self.assertFalse(self.files.is_dir())
-
-    def test_child_path_is(self):
-        self.assertTrue((self.files / 'a').is_file())
-        self.assertFalse((self.files / 'a').is_dir())
-
-    def test_orphan_path_is(self):
-        self.assertFalse((self.files / 'a' / 'a').is_file())
-        self.assertFalse((self.files / 'a' / 'a').is_dir())
-        self.assertFalse((self.files / 'a' / 'a' / 'a').is_file())
-        self.assertFalse((self.files / 'a' / 'a' / 'a').is_dir())
-
-    def test_spec_path_name(self):
-        self.assertEqual(self.files.name, 'testingpackage')
-
-    def test_child_path_name(self):
-        self.assertEqual((self.files / 'a').name, 'a')
-
-    def test_orphan_path_name(self):
-        self.assertEqual((self.files / 'a' / 'b').name, 'b')
-        self.assertEqual((self.files / 'a' / 'b' / 'c').name, 'c')
-
-    def test_spec_path_open(self):
-        self.assertEqual(self.files.read_bytes(), b'Hello, world!')
-        self.assertEqual(self.files.read_text(), 'Hello, world!')
-
-    def test_child_path_open(self):
-        self.assertEqual((self.files / 'a').read_bytes(), b'Hello, world!')
-        self.assertEqual((self.files / 'a').read_text(), 'Hello, world!')
-
-    def test_orphan_path_open(self):
-        with self.assertRaises(FileNotFoundError):
-            (self.files / 'a' / 'b').read_bytes()
-        with self.assertRaises(FileNotFoundError):
-            (self.files / 'a' / 'b' / 'c').read_bytes()
-
-    def test_open_invalid_mode(self):
-        with self.assertRaises(ValueError):
-            self.files.open('0')
-
-    def test_orphan_path_invalid(self):
-        with self.assertRaises(ValueError):
-            CompatibilityFiles.OrphanPath()
-
-    def test_wrap_spec(self):
-        spec = wrap_spec(self.package)
-        self.assertIsInstance(spec.loader.get_resource_reader(None), CompatibilityFiles)
-
-
-class CompatibilityFilesNoReaderTests(unittest.TestCase):
-    @property
-    def package(self):
-        return util.create_package_from_loader(None)
-
-    @property
-    def files(self):
-        return resources.files(self.package)
-
-    def test_spec_path_joinpath(self):
-        self.assertIsInstance(self.files / 'a', CompatibilityFiles.OrphanPath)
diff --git a/setuptools/_vendor/importlib_resources/tests/test_contents.py b/setuptools/_vendor/importlib_resources/tests/test_contents.py
deleted file mode 100644
index 525568e8c9..0000000000
--- a/setuptools/_vendor/importlib_resources/tests/test_contents.py
+++ /dev/null
@@ -1,43 +0,0 @@
-import unittest
-import importlib_resources as resources
-
-from . import data01
-from . import util
-
-
-class ContentsTests:
-    expected = {
-        '__init__.py',
-        'binary.file',
-        'subdirectory',
-        'utf-16.file',
-        'utf-8.file',
-    }
-
-    def test_contents(self):
-        contents = {path.name for path in resources.files(self.data).iterdir()}
-        assert self.expected <= contents
-
-
-class ContentsDiskTests(ContentsTests, unittest.TestCase):
-    def setUp(self):
-        self.data = data01
-
-
-class ContentsZipTests(ContentsTests, util.ZipSetup, unittest.TestCase):
-    pass
-
-
-class ContentsNamespaceTests(ContentsTests, unittest.TestCase):
-    expected = {
-        # no __init__ because of namespace design
-        # no subdirectory as incidental difference in fixture
-        'binary.file',
-        'utf-16.file',
-        'utf-8.file',
-    }
-
-    def setUp(self):
-        from . import namespacedata01
-
-        self.data = namespacedata01
diff --git a/setuptools/_vendor/importlib_resources/tests/test_files.py b/setuptools/_vendor/importlib_resources/tests/test_files.py
deleted file mode 100644
index d258fb5f0f..0000000000
--- a/setuptools/_vendor/importlib_resources/tests/test_files.py
+++ /dev/null
@@ -1,112 +0,0 @@
-import typing
-import textwrap
-import unittest
-import warnings
-import importlib
-import contextlib
-
-import importlib_resources as resources
-from ..abc import Traversable
-from . import data01
-from . import util
-from . import _path
-from ._compat import os_helper, import_helper
-
-
-@contextlib.contextmanager
-def suppress_known_deprecation():
-    with warnings.catch_warnings(record=True) as ctx:
-        warnings.simplefilter('default', category=DeprecationWarning)
-        yield ctx
-
-
-class FilesTests:
-    def test_read_bytes(self):
-        files = resources.files(self.data)
-        actual = files.joinpath('utf-8.file').read_bytes()
-        assert actual == b'Hello, UTF-8 world!\n'
-
-    def test_read_text(self):
-        files = resources.files(self.data)
-        actual = files.joinpath('utf-8.file').read_text(encoding='utf-8')
-        assert actual == 'Hello, UTF-8 world!\n'
-
-    @unittest.skipUnless(
-        hasattr(typing, 'runtime_checkable'),
-        "Only suitable when typing supports runtime_checkable",
-    )
-    def test_traversable(self):
-        assert isinstance(resources.files(self.data), Traversable)
-
-    def test_old_parameter(self):
-        """
-        Files used to take a 'package' parameter. Make sure anyone
-        passing by name is still supported.
-        """
-        with suppress_known_deprecation():
-            resources.files(package=self.data)
-
-
-class OpenDiskTests(FilesTests, unittest.TestCase):
-    def setUp(self):
-        self.data = data01
-
-
-class OpenZipTests(FilesTests, util.ZipSetup, unittest.TestCase):
-    pass
-
-
-class OpenNamespaceTests(FilesTests, unittest.TestCase):
-    def setUp(self):
-        from . import namespacedata01
-
-        self.data = namespacedata01
-
-
-class SiteDir:
-    def setUp(self):
-        self.fixtures = contextlib.ExitStack()
-        self.addCleanup(self.fixtures.close)
-        self.site_dir = self.fixtures.enter_context(os_helper.temp_dir())
-        self.fixtures.enter_context(import_helper.DirsOnSysPath(self.site_dir))
-        self.fixtures.enter_context(import_helper.CleanImport())
-
-
-class ModulesFilesTests(SiteDir, unittest.TestCase):
-    def test_module_resources(self):
-        """
-        A module can have resources found adjacent to the module.
-        """
-        spec = {
-            'mod.py': '',
-            'res.txt': 'resources are the best',
-        }
-        _path.build(spec, self.site_dir)
-        import mod
-
-        actual = resources.files(mod).joinpath('res.txt').read_text()
-        assert actual == spec['res.txt']
-
-
-class ImplicitContextFilesTests(SiteDir, unittest.TestCase):
-    def test_implicit_files(self):
-        """
-        Without any parameter, files() will infer the location as the caller.
-        """
-        spec = {
-            'somepkg': {
-                '__init__.py': textwrap.dedent(
-                    """
-                    import importlib_resources as res
-                    val = res.files().joinpath('res.txt').read_text()
-                    """
-                ),
-                'res.txt': 'resources are the best',
-            },
-        }
-        _path.build(spec, self.site_dir)
-        assert importlib.import_module('somepkg').val == 'resources are the best'
-
-
-if __name__ == '__main__':
-    unittest.main()
diff --git a/setuptools/_vendor/importlib_resources/tests/test_open.py b/setuptools/_vendor/importlib_resources/tests/test_open.py
deleted file mode 100644
index 87b42c3d39..0000000000
--- a/setuptools/_vendor/importlib_resources/tests/test_open.py
+++ /dev/null
@@ -1,81 +0,0 @@
-import unittest
-
-import importlib_resources as resources
-from . import data01
-from . import util
-
-
-class CommonBinaryTests(util.CommonTests, unittest.TestCase):
-    def execute(self, package, path):
-        target = resources.files(package).joinpath(path)
-        with target.open('rb'):
-            pass
-
-
-class CommonTextTests(util.CommonTests, unittest.TestCase):
-    def execute(self, package, path):
-        target = resources.files(package).joinpath(path)
-        with target.open():
-            pass
-
-
-class OpenTests:
-    def test_open_binary(self):
-        target = resources.files(self.data) / 'binary.file'
-        with target.open('rb') as fp:
-            result = fp.read()
-            self.assertEqual(result, b'\x00\x01\x02\x03')
-
-    def test_open_text_default_encoding(self):
-        target = resources.files(self.data) / 'utf-8.file'
-        with target.open() as fp:
-            result = fp.read()
-            self.assertEqual(result, 'Hello, UTF-8 world!\n')
-
-    def test_open_text_given_encoding(self):
-        target = resources.files(self.data) / 'utf-16.file'
-        with target.open(encoding='utf-16', errors='strict') as fp:
-            result = fp.read()
-        self.assertEqual(result, 'Hello, UTF-16 world!\n')
-
-    def test_open_text_with_errors(self):
-        # Raises UnicodeError without the 'errors' argument.
-        target = resources.files(self.data) / 'utf-16.file'
-        with target.open(encoding='utf-8', errors='strict') as fp:
-            self.assertRaises(UnicodeError, fp.read)
-        with target.open(encoding='utf-8', errors='ignore') as fp:
-            result = fp.read()
-        self.assertEqual(
-            result,
-            'H\x00e\x00l\x00l\x00o\x00,\x00 '
-            '\x00U\x00T\x00F\x00-\x001\x006\x00 '
-            '\x00w\x00o\x00r\x00l\x00d\x00!\x00\n\x00',
-        )
-
-    def test_open_binary_FileNotFoundError(self):
-        target = resources.files(self.data) / 'does-not-exist'
-        self.assertRaises(FileNotFoundError, target.open, 'rb')
-
-    def test_open_text_FileNotFoundError(self):
-        target = resources.files(self.data) / 'does-not-exist'
-        self.assertRaises(FileNotFoundError, target.open)
-
-
-class OpenDiskTests(OpenTests, unittest.TestCase):
-    def setUp(self):
-        self.data = data01
-
-
-class OpenDiskNamespaceTests(OpenTests, unittest.TestCase):
-    def setUp(self):
-        from . import namespacedata01
-
-        self.data = namespacedata01
-
-
-class OpenZipTests(OpenTests, util.ZipSetup, unittest.TestCase):
-    pass
-
-
-if __name__ == '__main__':
-    unittest.main()
diff --git a/setuptools/_vendor/importlib_resources/tests/test_path.py b/setuptools/_vendor/importlib_resources/tests/test_path.py
deleted file mode 100644
index 4f4d3943bb..0000000000
--- a/setuptools/_vendor/importlib_resources/tests/test_path.py
+++ /dev/null
@@ -1,64 +0,0 @@
-import io
-import unittest
-
-import importlib_resources as resources
-from . import data01
-from . import util
-
-
-class CommonTests(util.CommonTests, unittest.TestCase):
-    def execute(self, package, path):
-        with resources.as_file(resources.files(package).joinpath(path)):
-            pass
-
-
-class PathTests:
-    def test_reading(self):
-        # Path should be readable.
-        # Test also implicitly verifies the returned object is a pathlib.Path
-        # instance.
-        target = resources.files(self.data) / 'utf-8.file'
-        with resources.as_file(target) as path:
-            self.assertTrue(path.name.endswith("utf-8.file"), repr(path))
-            # pathlib.Path.read_text() was introduced in Python 3.5.
-            with path.open('r', encoding='utf-8') as file:
-                text = file.read()
-            self.assertEqual('Hello, UTF-8 world!\n', text)
-
-
-class PathDiskTests(PathTests, unittest.TestCase):
-    data = data01
-
-    def test_natural_path(self):
-        """
-        Guarantee the internal implementation detail that
-        file-system-backed resources do not get the tempdir
-        treatment.
-        """
-        target = resources.files(self.data) / 'utf-8.file'
-        with resources.as_file(target) as path:
-            assert 'data' in str(path)
-
-
-class PathMemoryTests(PathTests, unittest.TestCase):
-    def setUp(self):
-        file = io.BytesIO(b'Hello, UTF-8 world!\n')
-        self.addCleanup(file.close)
-        self.data = util.create_package(
-            file=file, path=FileNotFoundError("package exists only in memory")
-        )
-        self.data.__spec__.origin = None
-        self.data.__spec__.has_location = False
-
-
-class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase):
-    def test_remove_in_context_manager(self):
-        # It is not an error if the file that was temporarily stashed on the
-        # file system is removed inside the `with` stanza.
-        target = resources.files(self.data) / 'utf-8.file'
-        with resources.as_file(target) as path:
-            path.unlink()
-
-
-if __name__ == '__main__':
-    unittest.main()
diff --git a/setuptools/_vendor/importlib_resources/tests/test_read.py b/setuptools/_vendor/importlib_resources/tests/test_read.py
deleted file mode 100644
index 41dd6db5f3..0000000000
--- a/setuptools/_vendor/importlib_resources/tests/test_read.py
+++ /dev/null
@@ -1,76 +0,0 @@
-import unittest
-import importlib_resources as resources
-
-from . import data01
-from . import util
-from importlib import import_module
-
-
-class CommonBinaryTests(util.CommonTests, unittest.TestCase):
-    def execute(self, package, path):
-        resources.files(package).joinpath(path).read_bytes()
-
-
-class CommonTextTests(util.CommonTests, unittest.TestCase):
-    def execute(self, package, path):
-        resources.files(package).joinpath(path).read_text()
-
-
-class ReadTests:
-    def test_read_bytes(self):
-        result = resources.files(self.data).joinpath('binary.file').read_bytes()
-        self.assertEqual(result, b'\0\1\2\3')
-
-    def test_read_text_default_encoding(self):
-        result = resources.files(self.data).joinpath('utf-8.file').read_text()
-        self.assertEqual(result, 'Hello, UTF-8 world!\n')
-
-    def test_read_text_given_encoding(self):
-        result = (
-            resources.files(self.data)
-            .joinpath('utf-16.file')
-            .read_text(encoding='utf-16')
-        )
-        self.assertEqual(result, 'Hello, UTF-16 world!\n')
-
-    def test_read_text_with_errors(self):
-        # Raises UnicodeError without the 'errors' argument.
-        target = resources.files(self.data) / 'utf-16.file'
-        self.assertRaises(UnicodeError, target.read_text, encoding='utf-8')
-        result = target.read_text(encoding='utf-8', errors='ignore')
-        self.assertEqual(
-            result,
-            'H\x00e\x00l\x00l\x00o\x00,\x00 '
-            '\x00U\x00T\x00F\x00-\x001\x006\x00 '
-            '\x00w\x00o\x00r\x00l\x00d\x00!\x00\n\x00',
-        )
-
-
-class ReadDiskTests(ReadTests, unittest.TestCase):
-    data = data01
-
-
-class ReadZipTests(ReadTests, util.ZipSetup, unittest.TestCase):
-    def test_read_submodule_resource(self):
-        submodule = import_module('ziptestdata.subdirectory')
-        result = resources.files(submodule).joinpath('binary.file').read_bytes()
-        self.assertEqual(result, b'\0\1\2\3')
-
-    def test_read_submodule_resource_by_name(self):
-        result = (
-            resources.files('ziptestdata.subdirectory')
-            .joinpath('binary.file')
-            .read_bytes()
-        )
-        self.assertEqual(result, b'\0\1\2\3')
-
-
-class ReadNamespaceTests(ReadTests, unittest.TestCase):
-    def setUp(self):
-        from . import namespacedata01
-
-        self.data = namespacedata01
-
-
-if __name__ == '__main__':
-    unittest.main()
diff --git a/setuptools/_vendor/importlib_resources/tests/test_reader.py b/setuptools/_vendor/importlib_resources/tests/test_reader.py
deleted file mode 100644
index 1c8ebeeb13..0000000000
--- a/setuptools/_vendor/importlib_resources/tests/test_reader.py
+++ /dev/null
@@ -1,133 +0,0 @@
-import os.path
-import sys
-import pathlib
-import unittest
-
-from importlib import import_module
-from importlib_resources.readers import MultiplexedPath, NamespaceReader
-
-
-class MultiplexedPathTest(unittest.TestCase):
-    @classmethod
-    def setUpClass(cls):
-        path = pathlib.Path(__file__).parent / 'namespacedata01'
-        cls.folder = str(path)
-
-    def test_init_no_paths(self):
-        with self.assertRaises(FileNotFoundError):
-            MultiplexedPath()
-
-    def test_init_file(self):
-        with self.assertRaises(NotADirectoryError):
-            MultiplexedPath(os.path.join(self.folder, 'binary.file'))
-
-    def test_iterdir(self):
-        contents = {path.name for path in MultiplexedPath(self.folder).iterdir()}
-        try:
-            contents.remove('__pycache__')
-        except (KeyError, ValueError):
-            pass
-        self.assertEqual(contents, {'binary.file', 'utf-16.file', 'utf-8.file'})
-
-    def test_iterdir_duplicate(self):
-        data01 = os.path.abspath(os.path.join(__file__, '..', 'data01'))
-        contents = {
-            path.name for path in MultiplexedPath(self.folder, data01).iterdir()
-        }
-        for remove in ('__pycache__', '__init__.pyc'):
-            try:
-                contents.remove(remove)
-            except (KeyError, ValueError):
-                pass
-        self.assertEqual(
-            contents,
-            {'__init__.py', 'binary.file', 'subdirectory', 'utf-16.file', 'utf-8.file'},
-        )
-
-    def test_is_dir(self):
-        self.assertEqual(MultiplexedPath(self.folder).is_dir(), True)
-
-    def test_is_file(self):
-        self.assertEqual(MultiplexedPath(self.folder).is_file(), False)
-
-    def test_open_file(self):
-        path = MultiplexedPath(self.folder)
-        with self.assertRaises(FileNotFoundError):
-            path.read_bytes()
-        with self.assertRaises(FileNotFoundError):
-            path.read_text()
-        with self.assertRaises(FileNotFoundError):
-            path.open()
-
-    def test_join_path(self):
-        prefix = os.path.abspath(os.path.join(__file__, '..'))
-        data01 = os.path.join(prefix, 'data01')
-        path = MultiplexedPath(self.folder, data01)
-        self.assertEqual(
-            str(path.joinpath('binary.file'))[len(prefix) + 1 :],
-            os.path.join('namespacedata01', 'binary.file'),
-        )
-        self.assertEqual(
-            str(path.joinpath('subdirectory'))[len(prefix) + 1 :],
-            os.path.join('data01', 'subdirectory'),
-        )
-        self.assertEqual(
-            str(path.joinpath('imaginary'))[len(prefix) + 1 :],
-            os.path.join('namespacedata01', 'imaginary'),
-        )
-        self.assertEqual(path.joinpath(), path)
-
-    def test_join_path_compound(self):
-        path = MultiplexedPath(self.folder)
-        assert not path.joinpath('imaginary/foo.py').exists()
-
-    def test_repr(self):
-        self.assertEqual(
-            repr(MultiplexedPath(self.folder)),
-            f"MultiplexedPath('{self.folder}')",
-        )
-
-    def test_name(self):
-        self.assertEqual(
-            MultiplexedPath(self.folder).name,
-            os.path.basename(self.folder),
-        )
-
-
-class NamespaceReaderTest(unittest.TestCase):
-    site_dir = str(pathlib.Path(__file__).parent)
-
-    @classmethod
-    def setUpClass(cls):
-        sys.path.append(cls.site_dir)
-
-    @classmethod
-    def tearDownClass(cls):
-        sys.path.remove(cls.site_dir)
-
-    def test_init_error(self):
-        with self.assertRaises(ValueError):
-            NamespaceReader(['path1', 'path2'])
-
-    def test_resource_path(self):
-        namespacedata01 = import_module('namespacedata01')
-        reader = NamespaceReader(namespacedata01.__spec__.submodule_search_locations)
-
-        root = os.path.abspath(os.path.join(__file__, '..', 'namespacedata01'))
-        self.assertEqual(
-            reader.resource_path('binary.file'), os.path.join(root, 'binary.file')
-        )
-        self.assertEqual(
-            reader.resource_path('imaginary'), os.path.join(root, 'imaginary')
-        )
-
-    def test_files(self):
-        namespacedata01 = import_module('namespacedata01')
-        reader = NamespaceReader(namespacedata01.__spec__.submodule_search_locations)
-        root = os.path.abspath(os.path.join(__file__, '..', 'namespacedata01'))
-        self.assertIsInstance(reader.files(), MultiplexedPath)
-        self.assertEqual(repr(reader.files()), f"MultiplexedPath('{root}')")
-
-
-if __name__ == '__main__':
-    unittest.main()
diff --git a/setuptools/_vendor/importlib_resources/tests/test_resource.py b/setuptools/_vendor/importlib_resources/tests/test_resource.py
deleted file mode 100644
index 8239027167..0000000000
--- a/setuptools/_vendor/importlib_resources/tests/test_resource.py
+++ /dev/null
@@ -1,260 +0,0 @@
-import sys
-import unittest
-import importlib_resources as resources
-import uuid
-import pathlib
-
-from . import data01
-from . import zipdata01, zipdata02
-from . import util
-from importlib import import_module
-from ._compat import import_helper, unlink
-
-
-class ResourceTests:
-    # Subclasses are expected to set the `data` attribute.
-
-    def test_is_file_exists(self):
-        target = resources.files(self.data) / 'binary.file'
-        self.assertTrue(target.is_file())
-
-    def test_is_file_missing(self):
-        target = resources.files(self.data) / 'not-a-file'
-        self.assertFalse(target.is_file())
-
-    def test_is_dir(self):
-        target = resources.files(self.data) / 'subdirectory'
-        self.assertFalse(target.is_file())
-        self.assertTrue(target.is_dir())
-
-
-class ResourceDiskTests(ResourceTests, unittest.TestCase):
-    def setUp(self):
-        self.data = data01
-
-
-class ResourceZipTests(ResourceTests, util.ZipSetup, unittest.TestCase):
-    pass
-
-
-def names(traversable):
-    return {item.name for item in traversable.iterdir()}
-
-
-class ResourceLoaderTests(unittest.TestCase):
-    def test_resource_contents(self):
-        package = util.create_package(
-            file=data01, path=data01.__file__, contents=['A', 'B', 'C']
-        )
-        self.assertEqual(names(resources.files(package)), {'A', 'B', 'C'})
-
-    def test_is_file(self):
-        package = util.create_package(
-            file=data01, path=data01.__file__, contents=['A', 'B', 'C', 'D/E', 'D/F']
-        )
-        self.assertTrue(resources.files(package).joinpath('B').is_file())
-
-    def test_is_dir(self):
-        package = util.create_package(
-            file=data01, path=data01.__file__, contents=['A', 'B', 'C', 'D/E', 'D/F']
-        )
-        self.assertTrue(resources.files(package).joinpath('D').is_dir())
-
-    def test_resource_missing(self):
-        package = util.create_package(
-            file=data01, path=data01.__file__, contents=['A', 'B', 'C', 'D/E', 'D/F']
-        )
-        self.assertFalse(resources.files(package).joinpath('Z').is_file())
-
-
-class ResourceCornerCaseTests(unittest.TestCase):
-    def test_package_has_no_reader_fallback(self):
-        # Test odd ball packages which:
-        # 1. Do not have a ResourceReader as a loader
-        # 2. Are not on the file system
-        # 3. Are not in a zip file
-        module = util.create_package(
-            file=data01, path=data01.__file__, contents=['A', 'B', 'C']
-        )
-        # Give the module a dummy loader.
-        module.__loader__ = object()
-        # Give the module a dummy origin.
-        module.__file__ = '/path/which/shall/not/be/named'
-        module.__spec__.loader = module.__loader__
-        module.__spec__.origin = module.__file__
-        self.assertFalse(resources.files(module).joinpath('A').is_file())
-
-
-class ResourceFromZipsTest01(util.ZipSetupBase, unittest.TestCase):
-    ZIP_MODULE = zipdata01  # type: ignore
-
-    def test_is_submodule_resource(self):
-        submodule = import_module('ziptestdata.subdirectory')
-        self.assertTrue(resources.files(submodule).joinpath('binary.file').is_file())
-
-    def test_read_submodule_resource_by_name(self):
-        self.assertTrue(
-            resources.files('ziptestdata.subdirectory')
-            .joinpath('binary.file')
-            .is_file()
-        )
-
-    def test_submodule_contents(self):
-        submodule = import_module('ziptestdata.subdirectory')
-        self.assertEqual(
-            names(resources.files(submodule)), {'__init__.py', 'binary.file'}
-        )
-
-    def test_submodule_contents_by_name(self):
-        self.assertEqual(
-            names(resources.files('ziptestdata.subdirectory')),
-            {'__init__.py', 'binary.file'},
-        )
-
-    def test_as_file_directory(self):
-        with resources.as_file(resources.files('ziptestdata')) as data:
-            assert data.name == 'ziptestdata'
-            assert data.is_dir()
-            assert data.joinpath('subdirectory').is_dir()
-            assert len(list(data.iterdir()))
-        assert not data.parent.exists()
-
-
-class ResourceFromZipsTest02(util.ZipSetupBase, unittest.TestCase):
-    ZIP_MODULE = zipdata02  # type: ignore
-
-    def test_unrelated_contents(self):
-        """
-        Test thata zip with two unrelated subpackages return
-        distinct resources. Ref python/importlib_resources#44.
-        """
-        self.assertEqual(
-            names(resources.files('ziptestdata.one')),
-            {'__init__.py', 'resource1.txt'},
-        )
-        self.assertEqual(
-            names(resources.files('ziptestdata.two')),
-            {'__init__.py', 'resource2.txt'},
-        )
-
-
-class DeletingZipsTest(unittest.TestCase):
-    """Having accessed resources in a zip file should not keep an open
-    reference to the zip.
-    """
-
-    ZIP_MODULE = zipdata01
-
-    def setUp(self):
-        modules = import_helper.modules_setup()
-        self.addCleanup(import_helper.modules_cleanup, *modules)
-
-        data_path = pathlib.Path(self.ZIP_MODULE.__file__)
-        data_dir = data_path.parent
-        self.source_zip_path = data_dir / 'ziptestdata.zip'
-        self.zip_path = pathlib.Path(f'{uuid.uuid4()}.zip').absolute()
-        self.zip_path.write_bytes(self.source_zip_path.read_bytes())
-        sys.path.append(str(self.zip_path))
-        self.data = import_module('ziptestdata')
-
-    def tearDown(self):
-        try:
-            sys.path.remove(str(self.zip_path))
-        except ValueError:
-            pass
-
-        try:
-            del sys.path_importer_cache[str(self.zip_path)]
-            del sys.modules[self.data.__name__]
-        except KeyError:
-            pass
-
-        try:
-            unlink(self.zip_path)
-        except OSError:
-            # If the test fails, this will probably fail too
-            pass
-
-    def test_iterdir_does_not_keep_open(self):
-        c = [item.name for item in resources.files('ziptestdata').iterdir()]
-        self.zip_path.unlink()
-        del c
-
-    def test_is_file_does_not_keep_open(self):
-        c = resources.files('ziptestdata').joinpath('binary.file').is_file()
-        self.zip_path.unlink()
-        del c
-
-    def test_is_file_failure_does_not_keep_open(self):
-        c = resources.files('ziptestdata').joinpath('not-present').is_file()
-        self.zip_path.unlink()
-        del c
-
-    @unittest.skip("Desired but not supported.")
-    def test_as_file_does_not_keep_open(self):  # pragma: no cover
-        c = resources.as_file(resources.files('ziptestdata') / 'binary.file')
-        self.zip_path.unlink()
-        del c
-
-    def test_entered_path_does_not_keep_open(self):
-        # This is what certifi does on import to make its bundle
-        # available for the process duration.
-        c = resources.as_file(
-            resources.files('ziptestdata') / 'binary.file'
-        ).__enter__()
-        self.zip_path.unlink()
-        del c
-
-    def test_read_binary_does_not_keep_open(self):
-        c = resources.files('ziptestdata').joinpath('binary.file').read_bytes()
-        self.zip_path.unlink()
-        del c
-
-    def test_read_text_does_not_keep_open(self):
-        c = resources.files('ziptestdata').joinpath('utf-8.file').read_text()
-        self.zip_path.unlink()
-        del c
-
-
-class ResourceFromNamespaceTest01(unittest.TestCase):
-    site_dir = str(pathlib.Path(__file__).parent)
-
-    @classmethod
-    def setUpClass(cls):
-        sys.path.append(cls.site_dir)
-
-    @classmethod
-    def tearDownClass(cls):
-        sys.path.remove(cls.site_dir)
-
-    def test_is_submodule_resource(self):
-        self.assertTrue(
-            resources.files(import_module('namespacedata01'))
-            .joinpath('binary.file')
-            .is_file()
-        )
-
-    def test_read_submodule_resource_by_name(self):
-        self.assertTrue(
-            resources.files('namespacedata01').joinpath('binary.file').is_file()
-        )
-
-    def test_submodule_contents(self):
-        contents = names(resources.files(import_module('namespacedata01')))
-        try:
-            contents.remove('__pycache__')
-        except KeyError:
-            pass
-        self.assertEqual(contents, {'binary.file', 'utf-8.file', 'utf-16.file'})
-
-    def test_submodule_contents_by_name(self):
-        contents = names(resources.files('namespacedata01'))
-        try:
-            contents.remove('__pycache__')
-        except KeyError:
-            pass
-        self.assertEqual(contents, {'binary.file', 'utf-8.file', 'utf-16.file'})
-
-
-if __name__ == '__main__':
-    unittest.main()
diff --git a/setuptools/_vendor/importlib_resources/tests/update-zips.py b/setuptools/_vendor/importlib_resources/tests/update-zips.py
deleted file mode 100644
index 231334aa7e..0000000000
--- a/setuptools/_vendor/importlib_resources/tests/update-zips.py
+++ /dev/null
@@ -1,53 +0,0 @@
-"""
-Generate the zip test data files.
-
-Run to build the tests/zipdataNN/ziptestdata.zip files from
-files in tests/dataNN.
-
-Replaces the file with the working copy, but does commit anything
-to the source repo.
-"""
-
-import contextlib
-import os
-import pathlib
-import zipfile
-
-
-def main():
-    """
-    >>> from unittest import mock
-    >>> monkeypatch = getfixture('monkeypatch')
-    >>> monkeypatch.setattr(zipfile, 'ZipFile', mock.MagicMock())
-    >>> print(); main()  # print workaround for bpo-32509
-    
-    ...data01... -> ziptestdata/...
-    ...
-    ...data02... -> ziptestdata/...
-    ...
-    """
-    suffixes = '01', '02'
-    tuple(map(generate, suffixes))
-
-
-def generate(suffix):
-    root = pathlib.Path(__file__).parent.relative_to(os.getcwd())
-    zfpath = root / f'zipdata{suffix}/ziptestdata.zip'
-    with zipfile.ZipFile(zfpath, 'w') as zf:
-        for src, rel in walk(root / f'data{suffix}'):
-            dst = 'ziptestdata' / pathlib.PurePosixPath(rel.as_posix())
-            print(src, '->', dst)
-            zf.write(src, dst)
-
-
-def walk(datapath):
-    for dirpath, dirnames, filenames in os.walk(datapath):
-        with contextlib.suppress(ValueError):
-            dirnames.remove('__pycache__')
-        for filename in filenames:
-            res = pathlib.Path(dirpath) / filename
-            rel = res.relative_to(datapath)
-            yield res, rel
-
-
-__name__ == '__main__' and main()
diff --git a/setuptools/_vendor/importlib_resources/tests/util.py b/setuptools/_vendor/importlib_resources/tests/util.py
deleted file mode 100644
index b596c0ce4f..0000000000
--- a/setuptools/_vendor/importlib_resources/tests/util.py
+++ /dev/null
@@ -1,167 +0,0 @@
-import abc
-import importlib
-import io
-import sys
-import types
-import pathlib
-
-from . import data01
-from . import zipdata01
-from ..abc import ResourceReader
-from ._compat import import_helper
-
-
-from importlib.machinery import ModuleSpec
-
-
-class Reader(ResourceReader):
-    def __init__(self, **kwargs):
-        vars(self).update(kwargs)
-
-    def get_resource_reader(self, package):
-        return self
-
-    def open_resource(self, path):
-        self._path = path
-        if isinstance(self.file, Exception):
-            raise self.file
-        return self.file
-
-    def resource_path(self, path_):
-        self._path = path_
-        if isinstance(self.path, Exception):
-            raise self.path
-        return self.path
-
-    def is_resource(self, path_):
-        self._path = path_
-        if isinstance(self.path, Exception):
-            raise self.path
-
-        def part(entry):
-            return entry.split('/')
-
-        return any(
-            len(parts) == 1 and parts[0] == path_ for parts in map(part, self._contents)
-        )
-
-    def contents(self):
-        if isinstance(self.path, Exception):
-            raise self.path
-        yield from self._contents
-
-
-def create_package_from_loader(loader, is_package=True):
-    name = 'testingpackage'
-    module = types.ModuleType(name)
-    spec = ModuleSpec(name, loader, origin='does-not-exist', is_package=is_package)
-    module.__spec__ = spec
-    module.__loader__ = loader
-    return module
-
-
-def create_package(file=None, path=None, is_package=True, contents=()):
-    return create_package_from_loader(
-        Reader(file=file, path=path, _contents=contents),
-        is_package,
-    )
-
-
-class CommonTests(metaclass=abc.ABCMeta):
-    """
-    Tests shared by test_open, test_path, and test_read.
-    """
-
-    @abc.abstractmethod
-    def execute(self, package, path):
-        """
-        Call the pertinent legacy API function (e.g. open_text, path)
-        on package and path.
-        """
-
-    def test_package_name(self):
-        # Passing in the package name should succeed.
-        self.execute(data01.__name__, 'utf-8.file')
-
-    def test_package_object(self):
-        # Passing in the package itself should succeed.
-        self.execute(data01, 'utf-8.file')
-
-    def test_string_path(self):
-        # Passing in a string for the path should succeed.
-        path = 'utf-8.file'
-        self.execute(data01, path)
-
-    def test_pathlib_path(self):
-        # Passing in a pathlib.PurePath object for the path should succeed.
-        path = pathlib.PurePath('utf-8.file')
-        self.execute(data01, path)
-
-    def test_importing_module_as_side_effect(self):
-        # The anchor package can already be imported.
-        del sys.modules[data01.__name__]
-        self.execute(data01.__name__, 'utf-8.file')
-
-    def test_missing_path(self):
-        # Attempting to open or read or request the path for a
-        # non-existent path should succeed if open_resource
-        # can return a viable data stream.
-        bytes_data = io.BytesIO(b'Hello, world!')
-        package = create_package(file=bytes_data, path=FileNotFoundError())
-        self.execute(package, 'utf-8.file')
-        self.assertEqual(package.__loader__._path, 'utf-8.file')
-
-    def test_extant_path(self):
-        # Attempting to open or read or request the path when the
-        # path does exist should still succeed. Does not assert
-        # anything about the result.
-        bytes_data = io.BytesIO(b'Hello, world!')
-        # any path that exists
-        path = __file__
-        package = create_package(file=bytes_data, path=path)
-        self.execute(package, 'utf-8.file')
-        self.assertEqual(package.__loader__._path, 'utf-8.file')
-
-    def test_useless_loader(self):
-        package = create_package(file=FileNotFoundError(), path=FileNotFoundError())
-        with self.assertRaises(FileNotFoundError):
-            self.execute(package, 'utf-8.file')
-
-
-class ZipSetupBase:
-    ZIP_MODULE = None
-
-    @classmethod
-    def setUpClass(cls):
-        data_path = pathlib.Path(cls.ZIP_MODULE.__file__)
-        data_dir = data_path.parent
-        cls._zip_path = str(data_dir / 'ziptestdata.zip')
-        sys.path.append(cls._zip_path)
-        cls.data = importlib.import_module('ziptestdata')
-
-    @classmethod
-    def tearDownClass(cls):
-        try:
-            sys.path.remove(cls._zip_path)
-        except ValueError:
-            pass
-
-        try:
-            del sys.path_importer_cache[cls._zip_path]
-            del sys.modules[cls.data.__name__]
-        except KeyError:
-            pass
-
-        try:
-            del cls.data
-            del cls._zip_path
-        except AttributeError:
-            pass
-
-    def setUp(self):
-        modules = import_helper.modules_setup()
-        self.addCleanup(import_helper.modules_cleanup, *modules)
-
-
-class ZipSetup(ZipSetupBase):
-    ZIP_MODULE = zipdata01  # type: ignore
diff --git a/setuptools/_vendor/importlib_resources/tests/zipdata01/__init__.py b/setuptools/_vendor/importlib_resources/tests/zipdata01/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/setuptools/_vendor/importlib_resources/tests/zipdata01/ziptestdata.zip b/setuptools/_vendor/importlib_resources/tests/zipdata01/ziptestdata.zip
deleted file mode 100644
index 9a3bb0739f..0000000000
Binary files a/setuptools/_vendor/importlib_resources/tests/zipdata01/ziptestdata.zip and /dev/null differ
diff --git a/setuptools/_vendor/importlib_resources/tests/zipdata02/__init__.py b/setuptools/_vendor/importlib_resources/tests/zipdata02/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/setuptools/_vendor/importlib_resources/tests/zipdata02/ziptestdata.zip b/setuptools/_vendor/importlib_resources/tests/zipdata02/ziptestdata.zip
deleted file mode 100644
index d63ff512d2..0000000000
Binary files a/setuptools/_vendor/importlib_resources/tests/zipdata02/ziptestdata.zip and /dev/null differ
diff --git a/setuptools/_vendor/jaraco.context-4.3.0.dist-info/INSTALLER b/setuptools/_vendor/jaraco.context-4.3.0.dist-info/INSTALLER
deleted file mode 100644
index a1b589e38a..0000000000
--- a/setuptools/_vendor/jaraco.context-4.3.0.dist-info/INSTALLER
+++ /dev/null
@@ -1 +0,0 @@
-pip
diff --git a/setuptools/_vendor/jaraco.context-4.3.0.dist-info/LICENSE b/setuptools/_vendor/jaraco.context-4.3.0.dist-info/LICENSE
deleted file mode 100644
index 353924be0e..0000000000
--- a/setuptools/_vendor/jaraco.context-4.3.0.dist-info/LICENSE
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright Jason R. Coombs
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to
-deal in the Software without restriction, including without limitation the
-rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-sell copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-IN THE SOFTWARE.
diff --git a/setuptools/_vendor/jaraco.context-4.3.0.dist-info/METADATA b/setuptools/_vendor/jaraco.context-4.3.0.dist-info/METADATA
deleted file mode 100644
index 281137a035..0000000000
--- a/setuptools/_vendor/jaraco.context-4.3.0.dist-info/METADATA
+++ /dev/null
@@ -1,68 +0,0 @@
-Metadata-Version: 2.1
-Name: jaraco.context
-Version: 4.3.0
-Summary: Context managers by jaraco
-Home-page: https://github.com/jaraco/jaraco.context
-Author: Jason R. Coombs
-Author-email: jaraco@jaraco.com
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: MIT License
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3 :: Only
-Requires-Python: >=3.7
-License-File: LICENSE
-Provides-Extra: docs
-Requires-Dist: sphinx (>=3.5) ; extra == 'docs'
-Requires-Dist: jaraco.packaging (>=9) ; extra == 'docs'
-Requires-Dist: rst.linker (>=1.9) ; extra == 'docs'
-Requires-Dist: furo ; extra == 'docs'
-Requires-Dist: sphinx-lint ; extra == 'docs'
-Requires-Dist: jaraco.tidelift (>=1.4) ; extra == 'docs'
-Provides-Extra: testing
-Requires-Dist: pytest (>=6) ; extra == 'testing'
-Requires-Dist: pytest-checkdocs (>=2.4) ; extra == 'testing'
-Requires-Dist: flake8 (<5) ; extra == 'testing'
-Requires-Dist: pytest-cov ; extra == 'testing'
-Requires-Dist: pytest-enabler (>=1.3) ; extra == 'testing'
-Requires-Dist: pytest-black (>=0.3.7) ; (platform_python_implementation != "PyPy") and extra == 'testing'
-Requires-Dist: pytest-mypy (>=0.9.1) ; (platform_python_implementation != "PyPy") and extra == 'testing'
-Requires-Dist: pytest-flake8 ; (python_version < "3.12") and extra == 'testing'
-
-.. image:: https://img.shields.io/pypi/v/jaraco.context.svg
-   :target: https://pypi.org/project/jaraco.context
-
-.. image:: https://img.shields.io/pypi/pyversions/jaraco.context.svg
-
-.. image:: https://github.com/jaraco/jaraco.context/workflows/tests/badge.svg
-   :target: https://github.com/jaraco/jaraco.context/actions?query=workflow%3A%22tests%22
-   :alt: tests
-
-.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
-   :target: https://github.com/psf/black
-   :alt: Code style: Black
-
-.. image:: https://readthedocs.org/projects/jaracocontext/badge/?version=latest
-   :target: https://jaracocontext.readthedocs.io/en/latest/?badge=latest
-
-.. image:: https://img.shields.io/badge/skeleton-2023-informational
-   :target: https://blog.jaraco.com/skeleton
-
-.. image:: https://tidelift.com/badges/package/pypi/jaraco.context
-   :target: https://tidelift.com/subscription/pkg/pypi-jaraco.context?utm_source=pypi-jaraco.context&utm_medium=readme
-
-For Enterprise
-==============
-
-Available as part of the Tidelift Subscription.
-
-This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
-
-`Learn more `_.
-
-Security Contact
-================
-
-To report a security vulnerability, please use the
-`Tidelift security contact `_.
-Tidelift will coordinate the fix and disclosure.
diff --git a/setuptools/_vendor/jaraco.context-4.3.0.dist-info/RECORD b/setuptools/_vendor/jaraco.context-4.3.0.dist-info/RECORD
deleted file mode 100644
index 03122364a2..0000000000
--- a/setuptools/_vendor/jaraco.context-4.3.0.dist-info/RECORD
+++ /dev/null
@@ -1,8 +0,0 @@
-jaraco.context-4.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-jaraco.context-4.3.0.dist-info/LICENSE,sha256=2z8CRrH5J48VhFuZ_sR4uLUG63ZIeZNyL4xuJUKF-vg,1050
-jaraco.context-4.3.0.dist-info/METADATA,sha256=GqMykAm33E7Tt_t_MHc5O7GJN62Qwp6MEHX9WD-LPow,2958
-jaraco.context-4.3.0.dist-info/RECORD,,
-jaraco.context-4.3.0.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92
-jaraco.context-4.3.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7
-jaraco/__pycache__/context.cpython-311.pyc,,
-jaraco/context.py,sha256=vlyDzb_PvZ9H7R9bbTr_CMRnveW5Dc56eC7eyd_GfoA,7460
diff --git a/setuptools/_vendor/jaraco.context-4.3.0.dist-info/WHEEL b/setuptools/_vendor/jaraco.context-4.3.0.dist-info/WHEEL
deleted file mode 100644
index 57e3d840d5..0000000000
--- a/setuptools/_vendor/jaraco.context-4.3.0.dist-info/WHEEL
+++ /dev/null
@@ -1,5 +0,0 @@
-Wheel-Version: 1.0
-Generator: bdist_wheel (0.38.4)
-Root-Is-Purelib: true
-Tag: py3-none-any
-
diff --git a/setuptools/_vendor/jaraco.context-4.3.0.dist-info/top_level.txt b/setuptools/_vendor/jaraco.context-4.3.0.dist-info/top_level.txt
deleted file mode 100644
index f6205a5f19..0000000000
--- a/setuptools/_vendor/jaraco.context-4.3.0.dist-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-jaraco
diff --git a/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/INSTALLER b/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/INSTALLER
deleted file mode 100644
index a1b589e38a..0000000000
--- a/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/INSTALLER
+++ /dev/null
@@ -1 +0,0 @@
-pip
diff --git a/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/LICENSE b/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/LICENSE
deleted file mode 100644
index 353924be0e..0000000000
--- a/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/LICENSE
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright Jason R. Coombs
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to
-deal in the Software without restriction, including without limitation the
-rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-sell copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-IN THE SOFTWARE.
diff --git a/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/METADATA b/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/METADATA
deleted file mode 100644
index 23c6f5ef2b..0000000000
--- a/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/METADATA
+++ /dev/null
@@ -1,72 +0,0 @@
-Metadata-Version: 2.1
-Name: jaraco.functools
-Version: 3.6.0
-Summary: Functools like those found in stdlib
-Home-page: https://github.com/jaraco/jaraco.functools
-Author: Jason R. Coombs
-Author-email: jaraco@jaraco.com
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: MIT License
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3 :: Only
-Requires-Python: >=3.7
-License-File: LICENSE
-Requires-Dist: more-itertools
-Provides-Extra: docs
-Requires-Dist: sphinx (>=3.5) ; extra == 'docs'
-Requires-Dist: jaraco.packaging (>=9) ; extra == 'docs'
-Requires-Dist: rst.linker (>=1.9) ; extra == 'docs'
-Requires-Dist: furo ; extra == 'docs'
-Requires-Dist: sphinx-lint ; extra == 'docs'
-Requires-Dist: jaraco.tidelift (>=1.4) ; extra == 'docs'
-Provides-Extra: testing
-Requires-Dist: pytest (>=6) ; extra == 'testing'
-Requires-Dist: pytest-checkdocs (>=2.4) ; extra == 'testing'
-Requires-Dist: flake8 (<5) ; extra == 'testing'
-Requires-Dist: pytest-cov ; extra == 'testing'
-Requires-Dist: pytest-enabler (>=1.3) ; extra == 'testing'
-Requires-Dist: jaraco.classes ; extra == 'testing'
-Requires-Dist: pytest-black (>=0.3.7) ; (platform_python_implementation != "PyPy") and extra == 'testing'
-Requires-Dist: pytest-mypy (>=0.9.1) ; (platform_python_implementation != "PyPy") and extra == 'testing'
-Requires-Dist: pytest-flake8 ; (python_version < "3.12") and extra == 'testing'
-
-.. image:: https://img.shields.io/pypi/v/jaraco.functools.svg
-   :target: https://pypi.org/project/jaraco.functools
-
-.. image:: https://img.shields.io/pypi/pyversions/jaraco.functools.svg
-
-.. image:: https://github.com/jaraco/jaraco.functools/workflows/tests/badge.svg
-   :target: https://github.com/jaraco/jaraco.functools/actions?query=workflow%3A%22tests%22
-   :alt: tests
-
-.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
-   :target: https://github.com/psf/black
-   :alt: Code style: Black
-
-.. image:: https://readthedocs.org/projects/jaracofunctools/badge/?version=latest
-   :target: https://jaracofunctools.readthedocs.io/en/latest/?badge=latest
-
-.. image:: https://img.shields.io/badge/skeleton-2023-informational
-   :target: https://blog.jaraco.com/skeleton
-
-.. image:: https://tidelift.com/badges/package/pypi/jaraco.functools
-   :target: https://tidelift.com/subscription/pkg/pypi-jaraco.functools?utm_source=pypi-jaraco.functools&utm_medium=readme
-
-Additional functools in the spirit of stdlib's functools.
-
-For Enterprise
-==============
-
-Available as part of the Tidelift Subscription.
-
-This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
-
-`Learn more `_.
-
-Security Contact
-================
-
-To report a security vulnerability, please use the
-`Tidelift security contact `_.
-Tidelift will coordinate the fix and disclosure.
diff --git a/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/RECORD b/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/RECORD
deleted file mode 100644
index 70a3521307..0000000000
--- a/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/RECORD
+++ /dev/null
@@ -1,8 +0,0 @@
-jaraco.functools-3.6.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-jaraco.functools-3.6.0.dist-info/LICENSE,sha256=2z8CRrH5J48VhFuZ_sR4uLUG63ZIeZNyL4xuJUKF-vg,1050
-jaraco.functools-3.6.0.dist-info/METADATA,sha256=ImGoa1WEbhsibIb288yWqkDAvqLwlPzayjravRvW_Bs,3136
-jaraco.functools-3.6.0.dist-info/RECORD,,
-jaraco.functools-3.6.0.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92
-jaraco.functools-3.6.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7
-jaraco/__pycache__/functools.cpython-311.pyc,,
-jaraco/functools.py,sha256=GhSJGMVMcb0U4-axXaY_au30hT-ceW-HM1EbV1_9NzI,15035
diff --git a/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/WHEEL b/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/WHEEL
deleted file mode 100644
index 57e3d840d5..0000000000
--- a/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/WHEEL
+++ /dev/null
@@ -1,5 +0,0 @@
-Wheel-Version: 1.0
-Generator: bdist_wheel (0.38.4)
-Root-Is-Purelib: true
-Tag: py3-none-any
-
diff --git a/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/top_level.txt b/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/top_level.txt
deleted file mode 100644
index f6205a5f19..0000000000
--- a/setuptools/_vendor/jaraco.functools-3.6.0.dist-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-jaraco
diff --git a/setuptools/_vendor/jaraco.text-3.7.0.dist-info/INSTALLER b/setuptools/_vendor/jaraco.text-3.7.0.dist-info/INSTALLER
deleted file mode 100644
index a1b589e38a..0000000000
--- a/setuptools/_vendor/jaraco.text-3.7.0.dist-info/INSTALLER
+++ /dev/null
@@ -1 +0,0 @@
-pip
diff --git a/setuptools/_vendor/jaraco.text-3.7.0.dist-info/LICENSE b/setuptools/_vendor/jaraco.text-3.7.0.dist-info/LICENSE
deleted file mode 100644
index 353924be0e..0000000000
--- a/setuptools/_vendor/jaraco.text-3.7.0.dist-info/LICENSE
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright Jason R. Coombs
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to
-deal in the Software without restriction, including without limitation the
-rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-sell copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-IN THE SOFTWARE.
diff --git a/setuptools/_vendor/jaraco.text-3.7.0.dist-info/METADATA b/setuptools/_vendor/jaraco.text-3.7.0.dist-info/METADATA
deleted file mode 100644
index 615a50a4ae..0000000000
--- a/setuptools/_vendor/jaraco.text-3.7.0.dist-info/METADATA
+++ /dev/null
@@ -1,55 +0,0 @@
-Metadata-Version: 2.1
-Name: jaraco.text
-Version: 3.7.0
-Summary: Module for text manipulation
-Home-page: https://github.com/jaraco/jaraco.text
-Author: Jason R. Coombs
-Author-email: jaraco@jaraco.com
-License: UNKNOWN
-Platform: UNKNOWN
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: MIT License
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3 :: Only
-Requires-Python: >=3.6
-License-File: LICENSE
-Requires-Dist: jaraco.functools
-Requires-Dist: jaraco.context (>=4.1)
-Requires-Dist: importlib-resources ; python_version < "3.9"
-Provides-Extra: docs
-Requires-Dist: sphinx ; extra == 'docs'
-Requires-Dist: jaraco.packaging (>=8.2) ; extra == 'docs'
-Requires-Dist: rst.linker (>=1.9) ; extra == 'docs'
-Provides-Extra: testing
-Requires-Dist: pytest (>=6) ; extra == 'testing'
-Requires-Dist: pytest-checkdocs (>=2.4) ; extra == 'testing'
-Requires-Dist: pytest-flake8 ; extra == 'testing'
-Requires-Dist: pytest-cov ; extra == 'testing'
-Requires-Dist: pytest-enabler (>=1.0.1) ; extra == 'testing'
-Requires-Dist: pytest-black (>=0.3.7) ; (platform_python_implementation != "PyPy") and extra == 'testing'
-Requires-Dist: pytest-mypy ; (platform_python_implementation != "PyPy") and extra == 'testing'
-
-.. image:: https://img.shields.io/pypi/v/jaraco.text.svg
-   :target: `PyPI link`_
-
-.. image:: https://img.shields.io/pypi/pyversions/jaraco.text.svg
-   :target: `PyPI link`_
-
-.. _PyPI link: https://pypi.org/project/jaraco.text
-
-.. image:: https://github.com/jaraco/jaraco.text/workflows/tests/badge.svg
-   :target: https://github.com/jaraco/jaraco.text/actions?query=workflow%3A%22tests%22
-   :alt: tests
-
-.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
-   :target: https://github.com/psf/black
-   :alt: Code style: Black
-
-.. image:: https://readthedocs.org/projects/jaracotext/badge/?version=latest
-   :target: https://jaracotext.readthedocs.io/en/latest/?badge=latest
-
-.. image:: https://img.shields.io/badge/skeleton-2021-informational
-   :target: https://blog.jaraco.com/skeleton
-
-
diff --git a/setuptools/_vendor/jaraco.text-3.7.0.dist-info/RECORD b/setuptools/_vendor/jaraco.text-3.7.0.dist-info/RECORD
deleted file mode 100644
index dd471b0708..0000000000
--- a/setuptools/_vendor/jaraco.text-3.7.0.dist-info/RECORD
+++ /dev/null
@@ -1,10 +0,0 @@
-jaraco.text-3.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-jaraco.text-3.7.0.dist-info/LICENSE,sha256=2z8CRrH5J48VhFuZ_sR4uLUG63ZIeZNyL4xuJUKF-vg,1050
-jaraco.text-3.7.0.dist-info/METADATA,sha256=5mcR1dY0cJNrM-VIkAFkpjOgvgzmq6nM1GfD0gwTIhs,2136
-jaraco.text-3.7.0.dist-info/RECORD,,
-jaraco.text-3.7.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-jaraco.text-3.7.0.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
-jaraco.text-3.7.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7
-jaraco/text/Lorem ipsum.txt,sha256=N_7c_79zxOufBY9HZ3yzMgOkNv-TkOTTio4BydrSjgs,1335
-jaraco/text/__init__.py,sha256=I56MW2ZFwPrYXIxzqxMBe2A1t-T4uZBgEgAKe9-JoqM,15538
-jaraco/text/__pycache__/__init__.cpython-311.pyc,,
diff --git a/setuptools/_vendor/jaraco.text-3.7.0.dist-info/WHEEL b/setuptools/_vendor/jaraco.text-3.7.0.dist-info/WHEEL
deleted file mode 100644
index becc9a66ea..0000000000
--- a/setuptools/_vendor/jaraco.text-3.7.0.dist-info/WHEEL
+++ /dev/null
@@ -1,5 +0,0 @@
-Wheel-Version: 1.0
-Generator: bdist_wheel (0.37.1)
-Root-Is-Purelib: true
-Tag: py3-none-any
-
diff --git a/setuptools/_vendor/jaraco.text-3.7.0.dist-info/top_level.txt b/setuptools/_vendor/jaraco.text-3.7.0.dist-info/top_level.txt
deleted file mode 100644
index f6205a5f19..0000000000
--- a/setuptools/_vendor/jaraco.text-3.7.0.dist-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-jaraco
diff --git a/setuptools/_vendor/jaraco.text-4.0.0.dist-info/INSTALLER b/setuptools/_vendor/jaraco.text-4.0.0.dist-info/INSTALLER
new file mode 100644
index 0000000000..5c69047b2e
--- /dev/null
+++ b/setuptools/_vendor/jaraco.text-4.0.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/LICENSE b/setuptools/_vendor/jaraco.text-4.0.0.dist-info/LICENSE
similarity index 97%
rename from pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/LICENSE
rename to setuptools/_vendor/jaraco.text-4.0.0.dist-info/LICENSE
index 353924be0e..1bb5a44356 100644
--- a/pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/LICENSE
+++ b/setuptools/_vendor/jaraco.text-4.0.0.dist-info/LICENSE
@@ -1,5 +1,3 @@
-Copyright Jason R. Coombs
-
 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
diff --git a/setuptools/_vendor/jaraco.text-4.0.0.dist-info/METADATA b/setuptools/_vendor/jaraco.text-4.0.0.dist-info/METADATA
new file mode 100644
index 0000000000..797b9da733
--- /dev/null
+++ b/setuptools/_vendor/jaraco.text-4.0.0.dist-info/METADATA
@@ -0,0 +1,96 @@
+Metadata-Version: 2.1
+Name: jaraco.text
+Version: 4.0.0
+Summary: Module for text manipulation
+Author-email: "Jason R. Coombs" 
+Project-URL: Source, https://github.com/jaraco/jaraco.text
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Requires-Dist: jaraco.functools
+Requires-Dist: jaraco.context >=4.1
+Requires-Dist: autocommand
+Requires-Dist: more-itertools
+Requires-Dist: importlib-resources ; python_version < "3.9"
+Provides-Extra: doc
+Requires-Dist: sphinx >=3.5 ; extra == 'doc'
+Requires-Dist: jaraco.packaging >=9.3 ; extra == 'doc'
+Requires-Dist: rst.linker >=1.9 ; extra == 'doc'
+Requires-Dist: furo ; extra == 'doc'
+Requires-Dist: sphinx-lint ; extra == 'doc'
+Requires-Dist: jaraco.tidelift >=1.4 ; extra == 'doc'
+Provides-Extra: inflect
+Requires-Dist: inflect ; extra == 'inflect'
+Provides-Extra: test
+Requires-Dist: pytest !=8.1.*,>=6 ; extra == 'test'
+Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'test'
+Requires-Dist: pytest-cov ; extra == 'test'
+Requires-Dist: pytest-mypy ; extra == 'test'
+Requires-Dist: pytest-enabler >=2.2 ; extra == 'test'
+Requires-Dist: pathlib2 ; (python_version < "3.10") and extra == 'test'
+Requires-Dist: pytest-ruff >=0.2.1 ; (sys_platform != "cygwin") and extra == 'test'
+
+.. image:: https://img.shields.io/pypi/v/jaraco.text.svg
+   :target: https://pypi.org/project/jaraco.text
+
+.. image:: https://img.shields.io/pypi/pyversions/jaraco.text.svg
+
+.. image:: https://github.com/jaraco/jaraco.text/actions/workflows/main.yml/badge.svg
+   :target: https://github.com/jaraco/jaraco.text/actions?query=workflow%3A%22tests%22
+   :alt: tests
+
+.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json
+    :target: https://github.com/astral-sh/ruff
+    :alt: Ruff
+
+.. image:: https://readthedocs.org/projects/jaracotext/badge/?version=latest
+   :target: https://jaracotext.readthedocs.io/en/latest/?badge=latest
+
+.. image:: https://img.shields.io/badge/skeleton-2024-informational
+   :target: https://blog.jaraco.com/skeleton
+
+.. image:: https://tidelift.com/badges/package/pypi/jaraco.text
+   :target: https://tidelift.com/subscription/pkg/pypi-jaraco.text?utm_source=pypi-jaraco.text&utm_medium=readme
+
+
+This package provides handy routines for dealing with text, such as
+wrapping, substitution, trimming, stripping, prefix and suffix removal,
+line continuation, indentation, comment processing, identifier processing,
+values parsing, case insensitive comparison, and more. See the docs
+(linked in the badge above) for the detailed documentation and examples.
+
+Layouts
+=======
+
+One of the features of this package is the layouts module, which
+provides a simple example of translating keystrokes from one keyboard
+layout to another::
+
+    echo qwerty | python -m jaraco.text.to-dvorak
+    ',.pyf
+    echo  "',.pyf" | python -m jaraco.text.to-qwerty
+    qwerty
+
+Newline Reporting
+=================
+
+Need to know what newlines appear in a file?
+
+::
+
+    $ python -m jaraco.text.show-newlines README.rst
+    newline is '\n'
+
+For Enterprise
+==============
+
+Available as part of the Tidelift Subscription.
+
+This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
+
+`Learn more `_.
diff --git a/setuptools/_vendor/jaraco.text-4.0.0.dist-info/RECORD b/setuptools/_vendor/jaraco.text-4.0.0.dist-info/RECORD
new file mode 100644
index 0000000000..af65a9daa8
--- /dev/null
+++ b/setuptools/_vendor/jaraco.text-4.0.0.dist-info/RECORD
@@ -0,0 +1,14 @@
+jaraco.text-4.0.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+jaraco.text-4.0.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
+jaraco.text-4.0.0.dist-info/METADATA,sha256=XC_QkBLJVPE5sQYkl41TNaZUw0AUzQb29GbKaD28nFY,3731
+jaraco.text-4.0.0.dist-info/RECORD,,
+jaraco.text-4.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+jaraco.text-4.0.0.dist-info/WHEEL,sha256=Wyh-_nZ0DJYolHNn1_hMa4lM7uDedD_RGVwbmTjyItk,91
+jaraco.text-4.0.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7
+jaraco/text/Lorem ipsum.txt,sha256=N_7c_79zxOufBY9HZ3yzMgOkNv-TkOTTio4BydrSjgs,1335
+jaraco/text/__init__.py,sha256=lazNYXo8IhOR1bFigLAyGiiQao6jtO3KGWh8bZZPx3c,16762
+jaraco/text/layouts.py,sha256=HTC8aSTLZ7uXipyOXapRMC158juecjK6RVwitfmZ9_w,643
+jaraco/text/show-newlines.py,sha256=jT0vp4gLhG20hX2lTB-zKo_i3NgKzj79yRAdz4eMzIM,903
+jaraco/text/strip-prefix.py,sha256=NfVXV8JVNo6nqcuYASfMV7_y4Eo8zMQqlCOGvAnRIVw,412
+jaraco/text/to-dvorak.py,sha256=36nPPsiifwv6RfpAb--3zpgbIx8ohnnI1aR29IJTO9s,118
+jaraco/text/to-qwerty.py,sha256=IQoFY9v7vLTEybcput4KBYm_5GR35pmtgZ_xyrmdTgI,118
diff --git a/pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/REQUESTED b/setuptools/_vendor/jaraco.text-4.0.0.dist-info/REQUESTED
similarity index 100%
rename from pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/REQUESTED
rename to setuptools/_vendor/jaraco.text-4.0.0.dist-info/REQUESTED
diff --git a/pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/WHEEL b/setuptools/_vendor/jaraco.text-4.0.0.dist-info/WHEEL
similarity index 65%
rename from pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/WHEEL
rename to setuptools/_vendor/jaraco.text-4.0.0.dist-info/WHEEL
index becc9a66ea..ecaf39f3c3 100644
--- a/pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/WHEEL
+++ b/setuptools/_vendor/jaraco.text-4.0.0.dist-info/WHEEL
@@ -1,5 +1,5 @@
 Wheel-Version: 1.0
-Generator: bdist_wheel (0.37.1)
+Generator: setuptools (71.1.0)
 Root-Is-Purelib: true
 Tag: py3-none-any
 
diff --git a/pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/top_level.txt b/setuptools/_vendor/jaraco.text-4.0.0.dist-info/top_level.txt
similarity index 100%
rename from pkg_resources/_vendor/jaraco.context-4.3.0.dist-info/top_level.txt
rename to setuptools/_vendor/jaraco.text-4.0.0.dist-info/top_level.txt
diff --git a/setuptools/_vendor/jaraco/__init__.py b/setuptools/_vendor/jaraco/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/setuptools/_vendor/jaraco/context.py b/setuptools/_vendor/jaraco/context.py
deleted file mode 100644
index b0d1ef37cb..0000000000
--- a/setuptools/_vendor/jaraco/context.py
+++ /dev/null
@@ -1,288 +0,0 @@
-import os
-import subprocess
-import contextlib
-import functools
-import tempfile
-import shutil
-import operator
-import warnings
-
-
-@contextlib.contextmanager
-def pushd(dir):
-    """
-    >>> tmp_path = getfixture('tmp_path')
-    >>> with pushd(tmp_path):
-    ...     assert os.getcwd() == os.fspath(tmp_path)
-    >>> assert os.getcwd() != os.fspath(tmp_path)
-    """
-
-    orig = os.getcwd()
-    os.chdir(dir)
-    try:
-        yield dir
-    finally:
-        os.chdir(orig)
-
-
-@contextlib.contextmanager
-def tarball_context(url, target_dir=None, runner=None, pushd=pushd):
-    """
-    Get a tarball, extract it, change to that directory, yield, then
-    clean up.
-    `runner` is the function to invoke commands.
-    `pushd` is a context manager for changing the directory.
-    """
-    if target_dir is None:
-        target_dir = os.path.basename(url).replace('.tar.gz', '').replace('.tgz', '')
-    if runner is None:
-        runner = functools.partial(subprocess.check_call, shell=True)
-    else:
-        warnings.warn("runner parameter is deprecated", DeprecationWarning)
-    # In the tar command, use --strip-components=1 to strip the first path and
-    #  then
-    #  use -C to cause the files to be extracted to {target_dir}. This ensures
-    #  that we always know where the files were extracted.
-    runner('mkdir {target_dir}'.format(**vars()))
-    try:
-        getter = 'wget {url} -O -'
-        extract = 'tar x{compression} --strip-components=1 -C {target_dir}'
-        cmd = ' | '.join((getter, extract))
-        runner(cmd.format(compression=infer_compression(url), **vars()))
-        with pushd(target_dir):
-            yield target_dir
-    finally:
-        runner('rm -Rf {target_dir}'.format(**vars()))
-
-
-def infer_compression(url):
-    """
-    Given a URL or filename, infer the compression code for tar.
-
-    >>> infer_compression('http://foo/bar.tar.gz')
-    'z'
-    >>> infer_compression('http://foo/bar.tgz')
-    'z'
-    >>> infer_compression('file.bz')
-    'j'
-    >>> infer_compression('file.xz')
-    'J'
-    """
-    # cheat and just assume it's the last two characters
-    compression_indicator = url[-2:]
-    mapping = dict(gz='z', bz='j', xz='J')
-    # Assume 'z' (gzip) if no match
-    return mapping.get(compression_indicator, 'z')
-
-
-@contextlib.contextmanager
-def temp_dir(remover=shutil.rmtree):
-    """
-    Create a temporary directory context. Pass a custom remover
-    to override the removal behavior.
-
-    >>> import pathlib
-    >>> with temp_dir() as the_dir:
-    ...     assert os.path.isdir(the_dir)
-    ...     _ = pathlib.Path(the_dir).joinpath('somefile').write_text('contents')
-    >>> assert not os.path.exists(the_dir)
-    """
-    temp_dir = tempfile.mkdtemp()
-    try:
-        yield temp_dir
-    finally:
-        remover(temp_dir)
-
-
-@contextlib.contextmanager
-def repo_context(url, branch=None, quiet=True, dest_ctx=temp_dir):
-    """
-    Check out the repo indicated by url.
-
-    If dest_ctx is supplied, it should be a context manager
-    to yield the target directory for the check out.
-    """
-    exe = 'git' if 'git' in url else 'hg'
-    with dest_ctx() as repo_dir:
-        cmd = [exe, 'clone', url, repo_dir]
-        if branch:
-            cmd.extend(['--branch', branch])
-        devnull = open(os.path.devnull, 'w')
-        stdout = devnull if quiet else None
-        subprocess.check_call(cmd, stdout=stdout)
-        yield repo_dir
-
-
-@contextlib.contextmanager
-def null():
-    """
-    A null context suitable to stand in for a meaningful context.
-
-    >>> with null() as value:
-    ...     assert value is None
-    """
-    yield
-
-
-class ExceptionTrap:
-    """
-    A context manager that will catch certain exceptions and provide an
-    indication they occurred.
-
-    >>> with ExceptionTrap() as trap:
-    ...     raise Exception()
-    >>> bool(trap)
-    True
-
-    >>> with ExceptionTrap() as trap:
-    ...     pass
-    >>> bool(trap)
-    False
-
-    >>> with ExceptionTrap(ValueError) as trap:
-    ...     raise ValueError("1 + 1 is not 3")
-    >>> bool(trap)
-    True
-    >>> trap.value
-    ValueError('1 + 1 is not 3')
-    >>> trap.tb
-    
-
-    >>> with ExceptionTrap(ValueError) as trap:
-    ...     raise Exception()
-    Traceback (most recent call last):
-    ...
-    Exception
-
-    >>> bool(trap)
-    False
-    """
-
-    exc_info = None, None, None
-
-    def __init__(self, exceptions=(Exception,)):
-        self.exceptions = exceptions
-
-    def __enter__(self):
-        return self
-
-    @property
-    def type(self):
-        return self.exc_info[0]
-
-    @property
-    def value(self):
-        return self.exc_info[1]
-
-    @property
-    def tb(self):
-        return self.exc_info[2]
-
-    def __exit__(self, *exc_info):
-        type = exc_info[0]
-        matches = type and issubclass(type, self.exceptions)
-        if matches:
-            self.exc_info = exc_info
-        return matches
-
-    def __bool__(self):
-        return bool(self.type)
-
-    def raises(self, func, *, _test=bool):
-        """
-        Wrap func and replace the result with the truth
-        value of the trap (True if an exception occurred).
-
-        First, give the decorator an alias to support Python 3.8
-        Syntax.
-
-        >>> raises = ExceptionTrap(ValueError).raises
-
-        Now decorate a function that always fails.
-
-        >>> @raises
-        ... def fail():
-        ...     raise ValueError('failed')
-        >>> fail()
-        True
-        """
-
-        @functools.wraps(func)
-        def wrapper(*args, **kwargs):
-            with ExceptionTrap(self.exceptions) as trap:
-                func(*args, **kwargs)
-            return _test(trap)
-
-        return wrapper
-
-    def passes(self, func):
-        """
-        Wrap func and replace the result with the truth
-        value of the trap (True if no exception).
-
-        First, give the decorator an alias to support Python 3.8
-        Syntax.
-
-        >>> passes = ExceptionTrap(ValueError).passes
-
-        Now decorate a function that always fails.
-
-        >>> @passes
-        ... def fail():
-        ...     raise ValueError('failed')
-
-        >>> fail()
-        False
-        """
-        return self.raises(func, _test=operator.not_)
-
-
-class suppress(contextlib.suppress, contextlib.ContextDecorator):
-    """
-    A version of contextlib.suppress with decorator support.
-
-    >>> @suppress(KeyError)
-    ... def key_error():
-    ...     {}['']
-    >>> key_error()
-    """
-
-
-class on_interrupt(contextlib.ContextDecorator):
-    """
-    Replace a KeyboardInterrupt with SystemExit(1)
-
-    >>> def do_interrupt():
-    ...     raise KeyboardInterrupt()
-    >>> on_interrupt('error')(do_interrupt)()
-    Traceback (most recent call last):
-    ...
-    SystemExit: 1
-    >>> on_interrupt('error', code=255)(do_interrupt)()
-    Traceback (most recent call last):
-    ...
-    SystemExit: 255
-    >>> on_interrupt('suppress')(do_interrupt)()
-    >>> with __import__('pytest').raises(KeyboardInterrupt):
-    ...     on_interrupt('ignore')(do_interrupt)()
-    """
-
-    def __init__(
-        self,
-        action='error',
-        # py3.7 compat
-        # /,
-        code=1,
-    ):
-        self.action = action
-        self.code = code
-
-    def __enter__(self):
-        return self
-
-    def __exit__(self, exctype, excinst, exctb):
-        if exctype is not KeyboardInterrupt or self.action == 'ignore':
-            return
-        elif self.action == 'error':
-            raise SystemExit(self.code) from excinst
-        return self.action == 'suppress'
diff --git a/pkg_resources/_vendor/jaraco/context.py b/setuptools/_vendor/jaraco/context/__init__.py
similarity index 52%
rename from pkg_resources/_vendor/jaraco/context.py
rename to setuptools/_vendor/jaraco/context/__init__.py
index b0d1ef37cb..41ad609edd 100644
--- a/pkg_resources/_vendor/jaraco/context.py
+++ b/setuptools/_vendor/jaraco/context/__init__.py
@@ -1,15 +1,27 @@
-import os
-import subprocess
+from __future__ import annotations
+
 import contextlib
+import errno
 import functools
-import tempfile
-import shutil
 import operator
-import warnings
+import os
+import platform
+import shutil
+import stat
+import subprocess
+import sys
+import tempfile
+import urllib.request
+from collections.abc import Iterator
+
+if sys.version_info < (3, 12):
+    from backports import tarfile
+else:
+    import tarfile
 
 
 @contextlib.contextmanager
-def pushd(dir):
+def pushd(dir: str | os.PathLike) -> Iterator[str | os.PathLike]:
     """
     >>> tmp_path = getfixture('tmp_path')
     >>> with pushd(tmp_path):
@@ -26,53 +38,125 @@ def pushd(dir):
 
 
 @contextlib.contextmanager
-def tarball_context(url, target_dir=None, runner=None, pushd=pushd):
+def tarball(
+    url, target_dir: str | os.PathLike | None = None
+) -> Iterator[str | os.PathLike]:
     """
-    Get a tarball, extract it, change to that directory, yield, then
-    clean up.
-    `runner` is the function to invoke commands.
-    `pushd` is a context manager for changing the directory.
+    Get a URL to a tarball, download, extract, yield, then clean up.
+
+    Assumes everything in the tarball is prefixed with a common
+    directory. That common path is stripped and the contents
+    are extracted to ``target_dir``, similar to passing
+    ``-C {target} --strip-components 1`` to the ``tar`` command.
+
+    Uses the streaming protocol to extract the contents from a
+    stream in a single pass without loading the whole file into
+    memory.
+
+    >>> import urllib.request
+    >>> url = getfixture('tarfile_served')
+    >>> target = getfixture('tmp_path') / 'out'
+    >>> tb = tarball(url, target_dir=target)
+    >>> import pathlib
+    >>> with tb as extracted:
+    ...     contents = pathlib.Path(extracted, 'contents.txt').read_text(encoding='utf-8')
+    >>> assert not os.path.exists(extracted)
+
+    If the target is not specified, contents are extracted to a
+    directory relative to the current working directory named after
+    the name of the file as extracted from the URL.
+
+    >>> target = getfixture('tmp_path')
+    >>> with pushd(target), tarball(url):
+    ...     target.joinpath('served').is_dir()
+    True
     """
     if target_dir is None:
         target_dir = os.path.basename(url).replace('.tar.gz', '').replace('.tgz', '')
-    if runner is None:
-        runner = functools.partial(subprocess.check_call, shell=True)
-    else:
-        warnings.warn("runner parameter is deprecated", DeprecationWarning)
-    # In the tar command, use --strip-components=1 to strip the first path and
-    #  then
-    #  use -C to cause the files to be extracted to {target_dir}. This ensures
-    #  that we always know where the files were extracted.
-    runner('mkdir {target_dir}'.format(**vars()))
+    os.mkdir(target_dir)
     try:
-        getter = 'wget {url} -O -'
-        extract = 'tar x{compression} --strip-components=1 -C {target_dir}'
-        cmd = ' | '.join((getter, extract))
-        runner(cmd.format(compression=infer_compression(url), **vars()))
-        with pushd(target_dir):
-            yield target_dir
+        req = urllib.request.urlopen(url)
+        with tarfile.open(fileobj=req, mode='r|*') as tf:
+            tf.extractall(path=target_dir, filter=_default_filter)
+        yield target_dir
     finally:
-        runner('rm -Rf {target_dir}'.format(**vars()))
+        shutil.rmtree(target_dir)
+
+
+def _compose_tarfile_filters(*filters):
+    def compose_two(f1, f2):
+        return lambda member, path: f1(f2(member, path), path)
+
+    return functools.reduce(compose_two, filters, lambda member, path: member)
+
+
+def strip_first_component(
+    member: tarfile.TarInfo,
+    path,
+) -> tarfile.TarInfo:
+    _, member.name = member.name.split('/', 1)
+    return member
+
+
+_default_filter = _compose_tarfile_filters(tarfile.data_filter, strip_first_component)
+
 
+def _compose(*cmgrs):
+    """
+    Compose any number of dependent context managers into a single one.
+
+    The last, innermost context manager may take arbitrary arguments, but
+    each successive context manager should accept the result from the
+    previous as a single parameter.
+
+    Like :func:`jaraco.functools.compose`, behavior works from right to
+    left, so the context manager should be indicated from outermost to
+    innermost.
+
+    Example, to create a context manager to change to a temporary
+    directory:
 
-def infer_compression(url):
+    >>> temp_dir_as_cwd = _compose(pushd, temp_dir)
+    >>> with temp_dir_as_cwd() as dir:
+    ...     assert os.path.samefile(os.getcwd(), dir)
     """
-    Given a URL or filename, infer the compression code for tar.
-
-    >>> infer_compression('http://foo/bar.tar.gz')
-    'z'
-    >>> infer_compression('http://foo/bar.tgz')
-    'z'
-    >>> infer_compression('file.bz')
-    'j'
-    >>> infer_compression('file.xz')
-    'J'
+
+    def compose_two(inner, outer):
+        def composed(*args, **kwargs):
+            with inner(*args, **kwargs) as saved, outer(saved) as res:
+                yield res
+
+        return contextlib.contextmanager(composed)
+
+    return functools.reduce(compose_two, reversed(cmgrs))
+
+
+tarball_cwd = _compose(pushd, tarball)
+"""
+A tarball context with the current working directory pointing to the contents.
+"""
+
+
+def remove_readonly(func, path, exc_info):
+    """
+    Add support for removing read-only files on Windows.
     """
-    # cheat and just assume it's the last two characters
-    compression_indicator = url[-2:]
-    mapping = dict(gz='z', bz='j', xz='J')
-    # Assume 'z' (gzip) if no match
-    return mapping.get(compression_indicator, 'z')
+    _, exc, _ = exc_info
+    if func in (os.rmdir, os.remove, os.unlink) and exc.errno == errno.EACCES:
+        # change the file to be readable,writable,executable: 0777
+        os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
+        # retry
+        func(path)
+    else:
+        raise
+
+
+def robust_remover():
+    return (
+        functools.partial(shutil.rmtree, onerror=remove_readonly)
+        if platform.system() == 'Windows'
+        else shutil.rmtree
+    )
 
 
 @contextlib.contextmanager
@@ -84,7 +168,6 @@ def temp_dir(remover=shutil.rmtree):
     >>> import pathlib
     >>> with temp_dir() as the_dir:
     ...     assert os.path.isdir(the_dir)
-    ...     _ = pathlib.Path(the_dir).joinpath('somefile').write_text('contents')
     >>> assert not os.path.exists(the_dir)
     """
     temp_dir = tempfile.mkdtemp()
@@ -94,36 +177,36 @@ def temp_dir(remover=shutil.rmtree):
         remover(temp_dir)
 
 
+robust_temp_dir = functools.partial(temp_dir, remover=robust_remover())
+
+
 @contextlib.contextmanager
-def repo_context(url, branch=None, quiet=True, dest_ctx=temp_dir):
+def repo_context(
+    url, branch: str | None = None, quiet: bool = True, dest_ctx=robust_temp_dir
+):
     """
     Check out the repo indicated by url.
 
     If dest_ctx is supplied, it should be a context manager
     to yield the target directory for the check out.
+
+    >>> getfixture('ensure_git')
+    >>> getfixture('needs_internet')
+    >>> repo = repo_context('https://github.com/jaraco/jaraco.context')
+    >>> with repo as dest:
+    ...     listing = os.listdir(dest)
+    >>> 'README.rst' in listing
+    True
     """
     exe = 'git' if 'git' in url else 'hg'
     with dest_ctx() as repo_dir:
         cmd = [exe, 'clone', url, repo_dir]
-        if branch:
-            cmd.extend(['--branch', branch])
-        devnull = open(os.path.devnull, 'w')
-        stdout = devnull if quiet else None
-        subprocess.check_call(cmd, stdout=stdout)
+        cmd.extend(['--branch', branch] * bool(branch))
+        stream = subprocess.DEVNULL if quiet else None
+        subprocess.check_call(cmd, stdout=stream, stderr=stream)
         yield repo_dir
 
 
-@contextlib.contextmanager
-def null():
-    """
-    A null context suitable to stand in for a meaningful context.
-
-    >>> with null() as value:
-    ...     assert value is None
-    """
-    yield
-
-
 class ExceptionTrap:
     """
     A context manager that will catch certain exceptions and provide an
@@ -250,7 +333,9 @@ class suppress(contextlib.suppress, contextlib.ContextDecorator):
 
 class on_interrupt(contextlib.ContextDecorator):
     """
-    Replace a KeyboardInterrupt with SystemExit(1)
+    Replace a KeyboardInterrupt with SystemExit(1).
+
+    Useful in conjunction with console entry point functions.
 
     >>> def do_interrupt():
     ...     raise KeyboardInterrupt()
@@ -267,13 +352,7 @@ class on_interrupt(contextlib.ContextDecorator):
     ...     on_interrupt('ignore')(do_interrupt)()
     """
 
-    def __init__(
-        self,
-        action='error',
-        # py3.7 compat
-        # /,
-        code=1,
-    ):
+    def __init__(self, action='error', /, code=1):
         self.action = action
         self.code = code
 
diff --git a/pkg_resources/_vendor/importlib_resources/py.typed b/setuptools/_vendor/jaraco/context/py.typed
similarity index 100%
rename from pkg_resources/_vendor/importlib_resources/py.typed
rename to setuptools/_vendor/jaraco/context/py.typed
diff --git a/setuptools/_vendor/jaraco/functools.py b/setuptools/_vendor/jaraco/functools.py
deleted file mode 100644
index ebf7a36137..0000000000
--- a/setuptools/_vendor/jaraco/functools.py
+++ /dev/null
@@ -1,556 +0,0 @@
-import functools
-import time
-import inspect
-import collections
-import types
-import itertools
-import warnings
-
-import setuptools.extern.more_itertools
-
-from typing import Callable, TypeVar
-
-
-CallableT = TypeVar("CallableT", bound=Callable[..., object])
-
-
-def compose(*funcs):
-    """
-    Compose any number of unary functions into a single unary function.
-
-    >>> import textwrap
-    >>> expected = str.strip(textwrap.dedent(compose.__doc__))
-    >>> strip_and_dedent = compose(str.strip, textwrap.dedent)
-    >>> strip_and_dedent(compose.__doc__) == expected
-    True
-
-    Compose also allows the innermost function to take arbitrary arguments.
-
-    >>> round_three = lambda x: round(x, ndigits=3)
-    >>> f = compose(round_three, int.__truediv__)
-    >>> [f(3*x, x+1) for x in range(1,10)]
-    [1.5, 2.0, 2.25, 2.4, 2.5, 2.571, 2.625, 2.667, 2.7]
-    """
-
-    def compose_two(f1, f2):
-        return lambda *args, **kwargs: f1(f2(*args, **kwargs))
-
-    return functools.reduce(compose_two, funcs)
-
-
-def method_caller(method_name, *args, **kwargs):
-    """
-    Return a function that will call a named method on the
-    target object with optional positional and keyword
-    arguments.
-
-    >>> lower = method_caller('lower')
-    >>> lower('MyString')
-    'mystring'
-    """
-
-    def call_method(target):
-        func = getattr(target, method_name)
-        return func(*args, **kwargs)
-
-    return call_method
-
-
-def once(func):
-    """
-    Decorate func so it's only ever called the first time.
-
-    This decorator can ensure that an expensive or non-idempotent function
-    will not be expensive on subsequent calls and is idempotent.
-
-    >>> add_three = once(lambda a: a+3)
-    >>> add_three(3)
-    6
-    >>> add_three(9)
-    6
-    >>> add_three('12')
-    6
-
-    To reset the stored value, simply clear the property ``saved_result``.
-
-    >>> del add_three.saved_result
-    >>> add_three(9)
-    12
-    >>> add_three(8)
-    12
-
-    Or invoke 'reset()' on it.
-
-    >>> add_three.reset()
-    >>> add_three(-3)
-    0
-    >>> add_three(0)
-    0
-    """
-
-    @functools.wraps(func)
-    def wrapper(*args, **kwargs):
-        if not hasattr(wrapper, 'saved_result'):
-            wrapper.saved_result = func(*args, **kwargs)
-        return wrapper.saved_result
-
-    wrapper.reset = lambda: vars(wrapper).__delitem__('saved_result')
-    return wrapper
-
-
-def method_cache(
-    method: CallableT,
-    cache_wrapper: Callable[
-        [CallableT], CallableT
-    ] = functools.lru_cache(),  # type: ignore[assignment]
-) -> CallableT:
-    """
-    Wrap lru_cache to support storing the cache data in the object instances.
-
-    Abstracts the common paradigm where the method explicitly saves an
-    underscore-prefixed protected property on first call and returns that
-    subsequently.
-
-    >>> class MyClass:
-    ...     calls = 0
-    ...
-    ...     @method_cache
-    ...     def method(self, value):
-    ...         self.calls += 1
-    ...         return value
-
-    >>> a = MyClass()
-    >>> a.method(3)
-    3
-    >>> for x in range(75):
-    ...     res = a.method(x)
-    >>> a.calls
-    75
-
-    Note that the apparent behavior will be exactly like that of lru_cache
-    except that the cache is stored on each instance, so values in one
-    instance will not flush values from another, and when an instance is
-    deleted, so are the cached values for that instance.
-
-    >>> b = MyClass()
-    >>> for x in range(35):
-    ...     res = b.method(x)
-    >>> b.calls
-    35
-    >>> a.method(0)
-    0
-    >>> a.calls
-    75
-
-    Note that if method had been decorated with ``functools.lru_cache()``,
-    a.calls would have been 76 (due to the cached value of 0 having been
-    flushed by the 'b' instance).
-
-    Clear the cache with ``.cache_clear()``
-
-    >>> a.method.cache_clear()
-
-    Same for a method that hasn't yet been called.
-
-    >>> c = MyClass()
-    >>> c.method.cache_clear()
-
-    Another cache wrapper may be supplied:
-
-    >>> cache = functools.lru_cache(maxsize=2)
-    >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache)
-    >>> a = MyClass()
-    >>> a.method2()
-    3
-
-    Caution - do not subsequently wrap the method with another decorator, such
-    as ``@property``, which changes the semantics of the function.
-
-    See also
-    http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/
-    for another implementation and additional justification.
-    """
-
-    def wrapper(self: object, *args: object, **kwargs: object) -> object:
-        # it's the first call, replace the method with a cached, bound method
-        bound_method: CallableT = types.MethodType(  # type: ignore[assignment]
-            method, self
-        )
-        cached_method = cache_wrapper(bound_method)
-        setattr(self, method.__name__, cached_method)
-        return cached_method(*args, **kwargs)
-
-    # Support cache clear even before cache has been created.
-    wrapper.cache_clear = lambda: None  # type: ignore[attr-defined]
-
-    return (  # type: ignore[return-value]
-        _special_method_cache(method, cache_wrapper) or wrapper
-    )
-
-
-def _special_method_cache(method, cache_wrapper):
-    """
-    Because Python treats special methods differently, it's not
-    possible to use instance attributes to implement the cached
-    methods.
-
-    Instead, install the wrapper method under a different name
-    and return a simple proxy to that wrapper.
-
-    https://github.com/jaraco/jaraco.functools/issues/5
-    """
-    name = method.__name__
-    special_names = '__getattr__', '__getitem__'
-    if name not in special_names:
-        return
-
-    wrapper_name = '__cached' + name
-
-    def proxy(self, *args, **kwargs):
-        if wrapper_name not in vars(self):
-            bound = types.MethodType(method, self)
-            cache = cache_wrapper(bound)
-            setattr(self, wrapper_name, cache)
-        else:
-            cache = getattr(self, wrapper_name)
-        return cache(*args, **kwargs)
-
-    return proxy
-
-
-def apply(transform):
-    """
-    Decorate a function with a transform function that is
-    invoked on results returned from the decorated function.
-
-    >>> @apply(reversed)
-    ... def get_numbers(start):
-    ...     "doc for get_numbers"
-    ...     return range(start, start+3)
-    >>> list(get_numbers(4))
-    [6, 5, 4]
-    >>> get_numbers.__doc__
-    'doc for get_numbers'
-    """
-
-    def wrap(func):
-        return functools.wraps(func)(compose(transform, func))
-
-    return wrap
-
-
-def result_invoke(action):
-    r"""
-    Decorate a function with an action function that is
-    invoked on the results returned from the decorated
-    function (for its side-effect), then return the original
-    result.
-
-    >>> @result_invoke(print)
-    ... def add_two(a, b):
-    ...     return a + b
-    >>> x = add_two(2, 3)
-    5
-    >>> x
-    5
-    """
-
-    def wrap(func):
-        @functools.wraps(func)
-        def wrapper(*args, **kwargs):
-            result = func(*args, **kwargs)
-            action(result)
-            return result
-
-        return wrapper
-
-    return wrap
-
-
-def invoke(f, *args, **kwargs):
-    """
-    Call a function for its side effect after initialization.
-
-    The benefit of using the decorator instead of simply invoking a function
-    after defining it is that it makes explicit the author's intent for the
-    function to be called immediately. Whereas if one simply calls the
-    function immediately, it's less obvious if that was intentional or
-    incidental. It also avoids repeating the name - the two actions, defining
-    the function and calling it immediately are modeled separately, but linked
-    by the decorator construct.
-
-    The benefit of having a function construct (opposed to just invoking some
-    behavior inline) is to serve as a scope in which the behavior occurs. It
-    avoids polluting the global namespace with local variables, provides an
-    anchor on which to attach documentation (docstring), keeps the behavior
-    logically separated (instead of conceptually separated or not separated at
-    all), and provides potential to re-use the behavior for testing or other
-    purposes.
-
-    This function is named as a pithy way to communicate, "call this function
-    primarily for its side effect", or "while defining this function, also
-    take it aside and call it". It exists because there's no Python construct
-    for "define and call" (nor should there be, as decorators serve this need
-    just fine). The behavior happens immediately and synchronously.
-
-    >>> @invoke
-    ... def func(): print("called")
-    called
-    >>> func()
-    called
-
-    Use functools.partial to pass parameters to the initial call
-
-    >>> @functools.partial(invoke, name='bingo')
-    ... def func(name): print("called with", name)
-    called with bingo
-    """
-    f(*args, **kwargs)
-    return f
-
-
-def call_aside(*args, **kwargs):
-    """
-    Deprecated name for invoke.
-    """
-    warnings.warn("call_aside is deprecated, use invoke", DeprecationWarning)
-    return invoke(*args, **kwargs)
-
-
-class Throttler:
-    """
-    Rate-limit a function (or other callable)
-    """
-
-    def __init__(self, func, max_rate=float('Inf')):
-        if isinstance(func, Throttler):
-            func = func.func
-        self.func = func
-        self.max_rate = max_rate
-        self.reset()
-
-    def reset(self):
-        self.last_called = 0
-
-    def __call__(self, *args, **kwargs):
-        self._wait()
-        return self.func(*args, **kwargs)
-
-    def _wait(self):
-        "ensure at least 1/max_rate seconds from last call"
-        elapsed = time.time() - self.last_called
-        must_wait = 1 / self.max_rate - elapsed
-        time.sleep(max(0, must_wait))
-        self.last_called = time.time()
-
-    def __get__(self, obj, type=None):
-        return first_invoke(self._wait, functools.partial(self.func, obj))
-
-
-def first_invoke(func1, func2):
-    """
-    Return a function that when invoked will invoke func1 without
-    any parameters (for its side-effect) and then invoke func2
-    with whatever parameters were passed, returning its result.
-    """
-
-    def wrapper(*args, **kwargs):
-        func1()
-        return func2(*args, **kwargs)
-
-    return wrapper
-
-
-def retry_call(func, cleanup=lambda: None, retries=0, trap=()):
-    """
-    Given a callable func, trap the indicated exceptions
-    for up to 'retries' times, invoking cleanup on the
-    exception. On the final attempt, allow any exceptions
-    to propagate.
-    """
-    attempts = itertools.count() if retries == float('inf') else range(retries)
-    for attempt in attempts:
-        try:
-            return func()
-        except trap:
-            cleanup()
-
-    return func()
-
-
-def retry(*r_args, **r_kwargs):
-    """
-    Decorator wrapper for retry_call. Accepts arguments to retry_call
-    except func and then returns a decorator for the decorated function.
-
-    Ex:
-
-    >>> @retry(retries=3)
-    ... def my_func(a, b):
-    ...     "this is my funk"
-    ...     print(a, b)
-    >>> my_func.__doc__
-    'this is my funk'
-    """
-
-    def decorate(func):
-        @functools.wraps(func)
-        def wrapper(*f_args, **f_kwargs):
-            bound = functools.partial(func, *f_args, **f_kwargs)
-            return retry_call(bound, *r_args, **r_kwargs)
-
-        return wrapper
-
-    return decorate
-
-
-def print_yielded(func):
-    """
-    Convert a generator into a function that prints all yielded elements
-
-    >>> @print_yielded
-    ... def x():
-    ...     yield 3; yield None
-    >>> x()
-    3
-    None
-    """
-    print_all = functools.partial(map, print)
-    print_results = compose(more_itertools.consume, print_all, func)
-    return functools.wraps(func)(print_results)
-
-
-def pass_none(func):
-    """
-    Wrap func so it's not called if its first param is None
-
-    >>> print_text = pass_none(print)
-    >>> print_text('text')
-    text
-    >>> print_text(None)
-    """
-
-    @functools.wraps(func)
-    def wrapper(param, *args, **kwargs):
-        if param is not None:
-            return func(param, *args, **kwargs)
-
-    return wrapper
-
-
-def assign_params(func, namespace):
-    """
-    Assign parameters from namespace where func solicits.
-
-    >>> def func(x, y=3):
-    ...     print(x, y)
-    >>> assigned = assign_params(func, dict(x=2, z=4))
-    >>> assigned()
-    2 3
-
-    The usual errors are raised if a function doesn't receive
-    its required parameters:
-
-    >>> assigned = assign_params(func, dict(y=3, z=4))
-    >>> assigned()
-    Traceback (most recent call last):
-    TypeError: func() ...argument...
-
-    It even works on methods:
-
-    >>> class Handler:
-    ...     def meth(self, arg):
-    ...         print(arg)
-    >>> assign_params(Handler().meth, dict(arg='crystal', foo='clear'))()
-    crystal
-    """
-    sig = inspect.signature(func)
-    params = sig.parameters.keys()
-    call_ns = {k: namespace[k] for k in params if k in namespace}
-    return functools.partial(func, **call_ns)
-
-
-def save_method_args(method):
-    """
-    Wrap a method such that when it is called, the args and kwargs are
-    saved on the method.
-
-    >>> class MyClass:
-    ...     @save_method_args
-    ...     def method(self, a, b):
-    ...         print(a, b)
-    >>> my_ob = MyClass()
-    >>> my_ob.method(1, 2)
-    1 2
-    >>> my_ob._saved_method.args
-    (1, 2)
-    >>> my_ob._saved_method.kwargs
-    {}
-    >>> my_ob.method(a=3, b='foo')
-    3 foo
-    >>> my_ob._saved_method.args
-    ()
-    >>> my_ob._saved_method.kwargs == dict(a=3, b='foo')
-    True
-
-    The arguments are stored on the instance, allowing for
-    different instance to save different args.
-
-    >>> your_ob = MyClass()
-    >>> your_ob.method({str('x'): 3}, b=[4])
-    {'x': 3} [4]
-    >>> your_ob._saved_method.args
-    ({'x': 3},)
-    >>> my_ob._saved_method.args
-    ()
-    """
-    args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs')
-
-    @functools.wraps(method)
-    def wrapper(self, *args, **kwargs):
-        attr_name = '_saved_' + method.__name__
-        attr = args_and_kwargs(args, kwargs)
-        setattr(self, attr_name, attr)
-        return method(self, *args, **kwargs)
-
-    return wrapper
-
-
-def except_(*exceptions, replace=None, use=None):
-    """
-    Replace the indicated exceptions, if raised, with the indicated
-    literal replacement or evaluated expression (if present).
-
-    >>> safe_int = except_(ValueError)(int)
-    >>> safe_int('five')
-    >>> safe_int('5')
-    5
-
-    Specify a literal replacement with ``replace``.
-
-    >>> safe_int_r = except_(ValueError, replace=0)(int)
-    >>> safe_int_r('five')
-    0
-
-    Provide an expression to ``use`` to pass through particular parameters.
-
-    >>> safe_int_pt = except_(ValueError, use='args[0]')(int)
-    >>> safe_int_pt('five')
-    'five'
-
-    """
-
-    def decorate(func):
-        @functools.wraps(func)
-        def wrapper(*args, **kwargs):
-            try:
-                return func(*args, **kwargs)
-            except exceptions:
-                try:
-                    return eval(use)
-                except TypeError:
-                    return replace
-
-        return wrapper
-
-    return decorate
diff --git a/pkg_resources/_vendor/jaraco/functools.py b/setuptools/_vendor/jaraco/functools/__init__.py
similarity index 71%
rename from pkg_resources/_vendor/jaraco/functools.py
rename to setuptools/_vendor/jaraco/functools/__init__.py
index 67aeadc353..df32e2e924 100644
--- a/pkg_resources/_vendor/jaraco/functools.py
+++ b/setuptools/_vendor/jaraco/functools/__init__.py
@@ -1,23 +1,30 @@
+from __future__ import annotations
+
+import collections.abc
 import functools
-import time
 import inspect
-import collections
-import types
 import itertools
+import operator
+import time
+import types
 import warnings
-
-import pkg_resources.extern.more_itertools
-
 from typing import Callable, TypeVar
 
-
-CallableT = TypeVar("CallableT", bound=Callable[..., object])
+import more_itertools
 
 
 def compose(*funcs):
     """
     Compose any number of unary functions into a single unary function.
 
+    Comparable to
+    `function composition `_
+    in mathematics:
+
+    ``h = g ∘ f`` implies ``h(x) = g(f(x))``.
+
+    In Python, ``h = compose(g, f)``.
+
     >>> import textwrap
     >>> expected = str.strip(textwrap.dedent(compose.__doc__))
     >>> strip_and_dedent = compose(str.strip, textwrap.dedent)
@@ -38,24 +45,6 @@ def compose_two(f1, f2):
     return functools.reduce(compose_two, funcs)
 
 
-def method_caller(method_name, *args, **kwargs):
-    """
-    Return a function that will call a named method on the
-    target object with optional positional and keyword
-    arguments.
-
-    >>> lower = method_caller('lower')
-    >>> lower('MyString')
-    'mystring'
-    """
-
-    def call_method(target):
-        func = getattr(target, method_name)
-        return func(*args, **kwargs)
-
-    return call_method
-
-
 def once(func):
     """
     Decorate func so it's only ever called the first time.
@@ -98,12 +87,7 @@ def wrapper(*args, **kwargs):
     return wrapper
 
 
-def method_cache(
-    method: CallableT,
-    cache_wrapper: Callable[
-        [CallableT], CallableT
-    ] = functools.lru_cache(),  # type: ignore[assignment]
-) -> CallableT:
+def method_cache(method, cache_wrapper=functools.lru_cache()):
     """
     Wrap lru_cache to support storing the cache data in the object instances.
 
@@ -171,21 +155,17 @@ def method_cache(
     for another implementation and additional justification.
     """
 
-    def wrapper(self: object, *args: object, **kwargs: object) -> object:
+    def wrapper(self, *args, **kwargs):
         # it's the first call, replace the method with a cached, bound method
-        bound_method: CallableT = types.MethodType(  # type: ignore[assignment]
-            method, self
-        )
+        bound_method = types.MethodType(method, self)
         cached_method = cache_wrapper(bound_method)
         setattr(self, method.__name__, cached_method)
         return cached_method(*args, **kwargs)
 
     # Support cache clear even before cache has been created.
-    wrapper.cache_clear = lambda: None  # type: ignore[attr-defined]
+    wrapper.cache_clear = lambda: None
 
-    return (  # type: ignore[return-value]
-        _special_method_cache(method, cache_wrapper) or wrapper
-    )
+    return _special_method_cache(method, cache_wrapper) or wrapper
 
 
 def _special_method_cache(method, cache_wrapper):
@@ -201,12 +181,13 @@ def _special_method_cache(method, cache_wrapper):
     """
     name = method.__name__
     special_names = '__getattr__', '__getitem__'
+
     if name not in special_names:
-        return
+        return None
 
     wrapper_name = '__cached' + name
 
-    def proxy(self, *args, **kwargs):
+    def proxy(self, /, *args, **kwargs):
         if wrapper_name not in vars(self):
             bound = types.MethodType(method, self)
             cache = cache_wrapper(bound)
@@ -243,7 +224,7 @@ def result_invoke(action):
     r"""
     Decorate a function with an action function that is
     invoked on the results returned from the decorated
-    function (for its side-effect), then return the original
+    function (for its side effect), then return the original
     result.
 
     >>> @result_invoke(print)
@@ -267,7 +248,7 @@ def wrapper(*args, **kwargs):
     return wrap
 
 
-def invoke(f, *args, **kwargs):
+def invoke(f, /, *args, **kwargs):
     """
     Call a function for its side effect after initialization.
 
@@ -302,25 +283,35 @@ def invoke(f, *args, **kwargs):
     Use functools.partial to pass parameters to the initial call
 
     >>> @functools.partial(invoke, name='bingo')
-    ... def func(name): print("called with", name)
+    ... def func(name): print('called with', name)
     called with bingo
     """
     f(*args, **kwargs)
     return f
 
 
-def call_aside(*args, **kwargs):
+_T = TypeVar('_T')
+
+
+def passthrough(func: Callable[..., object]) -> Callable[[_T], _T]:
     """
-    Deprecated name for invoke.
+    Wrap the function to always return the first parameter.
+
+    >>> passthrough(print)('3')
+    3
+    '3'
     """
-    warnings.warn("call_aside is deprecated, use invoke", DeprecationWarning)
-    return invoke(*args, **kwargs)
+
+    @functools.wraps(func)
+    def wrapper(first: _T, *args, **kwargs) -> _T:
+        func(first, *args, **kwargs)
+        return first
+
+    return wrapper
 
 
 class Throttler:
-    """
-    Rate-limit a function (or other callable)
-    """
+    """Rate-limit a function (or other callable)."""
 
     def __init__(self, func, max_rate=float('Inf')):
         if isinstance(func, Throttler):
@@ -337,20 +328,20 @@ def __call__(self, *args, **kwargs):
         return self.func(*args, **kwargs)
 
     def _wait(self):
-        "ensure at least 1/max_rate seconds from last call"
+        """Ensure at least 1/max_rate seconds from last call."""
         elapsed = time.time() - self.last_called
         must_wait = 1 / self.max_rate - elapsed
         time.sleep(max(0, must_wait))
         self.last_called = time.time()
 
-    def __get__(self, obj, type=None):
+    def __get__(self, obj, owner=None):
         return first_invoke(self._wait, functools.partial(self.func, obj))
 
 
 def first_invoke(func1, func2):
     """
     Return a function that when invoked will invoke func1 without
-    any parameters (for its side-effect) and then invoke func2
+    any parameters (for its side effect) and then invoke func2
     with whatever parameters were passed, returning its result.
     """
 
@@ -361,6 +352,17 @@ def wrapper(*args, **kwargs):
     return wrapper
 
 
+method_caller = first_invoke(
+    lambda: warnings.warn(
+        '`jaraco.functools.method_caller` is deprecated, '
+        'use `operator.methodcaller` instead',
+        DeprecationWarning,
+        stacklevel=3,
+    ),
+    operator.methodcaller,
+)
+
+
 def retry_call(func, cleanup=lambda: None, retries=0, trap=()):
     """
     Given a callable func, trap the indicated exceptions
@@ -369,7 +371,7 @@ def retry_call(func, cleanup=lambda: None, retries=0, trap=()):
     to propagate.
     """
     attempts = itertools.count() if retries == float('inf') else range(retries)
-    for attempt in attempts:
+    for _ in attempts:
         try:
             return func()
         except trap:
@@ -406,7 +408,7 @@ def wrapper(*f_args, **f_kwargs):
 
 def print_yielded(func):
     """
-    Convert a generator into a function that prints all yielded elements
+    Convert a generator into a function that prints all yielded elements.
 
     >>> @print_yielded
     ... def x():
@@ -422,7 +424,7 @@ def print_yielded(func):
 
 def pass_none(func):
     """
-    Wrap func so it's not called if its first param is None
+    Wrap func so it's not called if its first param is None.
 
     >>> print_text = pass_none(print)
     >>> print_text('text')
@@ -431,13 +433,24 @@ def pass_none(func):
     """
 
     @functools.wraps(func)
-    def wrapper(param, *args, **kwargs):
+    def wrapper(param, /, *args, **kwargs):
         if param is not None:
             return func(param, *args, **kwargs)
+        return None
 
     return wrapper
 
 
+def none_as(value, replacement=None):
+    """
+    >>> none_as(None, 'foo')
+    'foo'
+    >>> none_as('bar', 'foo')
+    'bar'
+    """
+    return replacement if value is None else value
+
+
 def assign_params(func, namespace):
     """
     Assign parameters from namespace where func solicits.
@@ -504,10 +517,10 @@ def save_method_args(method):
     >>> my_ob._saved_method.args
     ()
     """
-    args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs')
+    args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs')  # noqa: PYI024 # Internal; stubs used for typing
 
     @functools.wraps(method)
-    def wrapper(self, *args, **kwargs):
+    def wrapper(self, /, *args, **kwargs):
         attr_name = '_saved_' + method.__name__
         attr = args_and_kwargs(args, kwargs)
         setattr(self, attr_name, attr)
@@ -554,3 +567,156 @@ def wrapper(*args, **kwargs):
         return wrapper
 
     return decorate
+
+
+def identity(x):
+    """
+    Return the argument.
+
+    >>> o = object()
+    >>> identity(o) is o
+    True
+    """
+    return x
+
+
+def bypass_when(check, *, _op=identity):
+    """
+    Decorate a function to return its parameter when ``check``.
+
+    >>> bypassed = []  # False
+
+    >>> @bypass_when(bypassed)
+    ... def double(x):
+    ...     return x * 2
+    >>> double(2)
+    4
+    >>> bypassed[:] = [object()]  # True
+    >>> double(2)
+    2
+    """
+
+    def decorate(func):
+        @functools.wraps(func)
+        def wrapper(param, /):
+            return param if _op(check) else func(param)
+
+        return wrapper
+
+    return decorate
+
+
+def bypass_unless(check):
+    """
+    Decorate a function to return its parameter unless ``check``.
+
+    >>> enabled = [object()]  # True
+
+    >>> @bypass_unless(enabled)
+    ... def double(x):
+    ...     return x * 2
+    >>> double(2)
+    4
+    >>> del enabled[:]  # False
+    >>> double(2)
+    2
+    """
+    return bypass_when(check, _op=operator.not_)
+
+
+@functools.singledispatch
+def _splat_inner(args, func):
+    """Splat args to func."""
+    return func(*args)
+
+
+@_splat_inner.register
+def _(args: collections.abc.Mapping, func):
+    """Splat kargs to func as kwargs."""
+    return func(**args)
+
+
+def splat(func):
+    """
+    Wrap func to expect its parameters to be passed positionally in a tuple.
+
+    Has a similar effect to that of ``itertools.starmap`` over
+    simple ``map``.
+
+    >>> pairs = [(-1, 1), (0, 2)]
+    >>> more_itertools.consume(itertools.starmap(print, pairs))
+    -1 1
+    0 2
+    >>> more_itertools.consume(map(splat(print), pairs))
+    -1 1
+    0 2
+
+    The approach generalizes to other iterators that don't have a "star"
+    equivalent, such as a "starfilter".
+
+    >>> list(filter(splat(operator.add), pairs))
+    [(0, 2)]
+
+    Splat also accepts a mapping argument.
+
+    >>> def is_nice(msg, code):
+    ...     return "smile" in msg or code == 0
+    >>> msgs = [
+    ...     dict(msg='smile!', code=20),
+    ...     dict(msg='error :(', code=1),
+    ...     dict(msg='unknown', code=0),
+    ... ]
+    >>> for msg in filter(splat(is_nice), msgs):
+    ...     print(msg)
+    {'msg': 'smile!', 'code': 20}
+    {'msg': 'unknown', 'code': 0}
+    """
+    return functools.wraps(func)(functools.partial(_splat_inner, func=func))
+
+
+_T = TypeVar('_T')
+
+
+def chainable(method: Callable[[_T, ...], None]) -> Callable[[_T, ...], _T]:
+    """
+    Wrap an instance method to always return self.
+
+
+    >>> class Dingus:
+    ...     @chainable
+    ...     def set_attr(self, name, val):
+    ...         setattr(self, name, val)
+    >>> d = Dingus().set_attr('a', 'eh!')
+    >>> d.a
+    'eh!'
+    >>> d2 = Dingus().set_attr('a', 'eh!').set_attr('b', 'bee!')
+    >>> d2.a + d2.b
+    'eh!bee!'
+
+    Enforces that the return value is null.
+
+    >>> class BorkedDingus:
+    ...     @chainable
+    ...     def set_attr(self, name, val):
+    ...         setattr(self, name, val)
+    ...         return len(name)
+    >>> BorkedDingus().set_attr('a', 'eh!')
+    Traceback (most recent call last):
+    ...
+    AssertionError
+    """
+
+    @functools.wraps(method)
+    def wrapper(self, *args, **kwargs):
+        assert method(self, *args, **kwargs) is None
+        return self
+
+    return wrapper
+
+
+def noop(*args, **kwargs):
+    """
+    A no-operation function that does nothing.
+
+    >>> noop(1, 2, three=3)
+    """
diff --git a/setuptools/_vendor/jaraco/functools/__init__.pyi b/setuptools/_vendor/jaraco/functools/__init__.pyi
new file mode 100644
index 0000000000..6f834bf06d
--- /dev/null
+++ b/setuptools/_vendor/jaraco/functools/__init__.pyi
@@ -0,0 +1,123 @@
+from collections.abc import Callable, Hashable, Iterator
+from functools import partial
+from operator import methodcaller
+from typing import (
+    Any,
+    Generic,
+    Protocol,
+    TypeVar,
+    overload,
+)
+
+from typing_extensions import Concatenate, ParamSpec, TypeVarTuple, Unpack
+
+_P = ParamSpec('_P')
+_R = TypeVar('_R')
+_T = TypeVar('_T')
+_Ts = TypeVarTuple('_Ts')
+_R1 = TypeVar('_R1')
+_R2 = TypeVar('_R2')
+_V = TypeVar('_V')
+_S = TypeVar('_S')
+_R_co = TypeVar('_R_co', covariant=True)
+
+class _OnceCallable(Protocol[_P, _R]):
+    saved_result: _R
+    reset: Callable[[], None]
+    def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R: ...
+
+class _ProxyMethodCacheWrapper(Protocol[_R_co]):
+    cache_clear: Callable[[], None]
+    def __call__(self, *args: Hashable, **kwargs: Hashable) -> _R_co: ...
+
+class _MethodCacheWrapper(Protocol[_R_co]):
+    def cache_clear(self) -> None: ...
+    def __call__(self, *args: Hashable, **kwargs: Hashable) -> _R_co: ...
+
+# `compose()` overloads below will cover most use cases.
+
+@overload
+def compose(
+    __func1: Callable[[_R], _T],
+    __func2: Callable[_P, _R],
+    /,
+) -> Callable[_P, _T]: ...
+@overload
+def compose(
+    __func1: Callable[[_R], _T],
+    __func2: Callable[[_R1], _R],
+    __func3: Callable[_P, _R1],
+    /,
+) -> Callable[_P, _T]: ...
+@overload
+def compose(
+    __func1: Callable[[_R], _T],
+    __func2: Callable[[_R2], _R],
+    __func3: Callable[[_R1], _R2],
+    __func4: Callable[_P, _R1],
+    /,
+) -> Callable[_P, _T]: ...
+def once(func: Callable[_P, _R]) -> _OnceCallable[_P, _R]: ...
+def method_cache(
+    method: Callable[..., _R],
+    cache_wrapper: Callable[[Callable[..., _R]], _MethodCacheWrapper[_R]] = ...,
+) -> _MethodCacheWrapper[_R] | _ProxyMethodCacheWrapper[_R]: ...
+def apply(
+    transform: Callable[[_R], _T],
+) -> Callable[[Callable[_P, _R]], Callable[_P, _T]]: ...
+def result_invoke(
+    action: Callable[[_R], Any],
+) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ...
+def invoke(
+    f: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs
+) -> Callable[_P, _R]: ...
+
+class Throttler(Generic[_R]):
+    last_called: float
+    func: Callable[..., _R]
+    max_rate: float
+    def __init__(
+        self, func: Callable[..., _R] | Throttler[_R], max_rate: float = ...
+    ) -> None: ...
+    def reset(self) -> None: ...
+    def __call__(self, *args: Any, **kwargs: Any) -> _R: ...
+    def __get__(self, obj: Any, owner: type[Any] | None = ...) -> Callable[..., _R]: ...
+
+def first_invoke(
+    func1: Callable[..., Any], func2: Callable[_P, _R]
+) -> Callable[_P, _R]: ...
+
+method_caller: Callable[..., methodcaller]
+
+def retry_call(
+    func: Callable[..., _R],
+    cleanup: Callable[..., None] = ...,
+    retries: float = ...,
+    trap: type[BaseException] | tuple[type[BaseException], ...] = ...,
+) -> _R: ...
+def retry(
+    cleanup: Callable[..., None] = ...,
+    retries: float = ...,
+    trap: type[BaseException] | tuple[type[BaseException], ...] = ...,
+) -> Callable[[Callable[..., _R]], Callable[..., _R]]: ...
+def print_yielded(func: Callable[_P, Iterator[Any]]) -> Callable[_P, None]: ...
+def pass_none(
+    func: Callable[Concatenate[_T, _P], _R],
+) -> Callable[Concatenate[_T, _P], _R]: ...
+def assign_params(
+    func: Callable[..., _R], namespace: dict[str, Any]
+) -> partial[_R]: ...
+def save_method_args(
+    method: Callable[Concatenate[_S, _P], _R],
+) -> Callable[Concatenate[_S, _P], _R]: ...
+def except_(
+    *exceptions: type[BaseException], replace: Any = ..., use: Any = ...
+) -> Callable[[Callable[_P, Any]], Callable[_P, Any]]: ...
+def identity(x: _T) -> _T: ...
+def bypass_when(
+    check: _V, *, _op: Callable[[_V], Any] = ...
+) -> Callable[[Callable[[_T], _R]], Callable[[_T], _T | _R]]: ...
+def bypass_unless(
+    check: Any,
+) -> Callable[[Callable[[_T], _R]], Callable[[_T], _T | _R]]: ...
+def splat(func: Callable[[Unpack[_Ts]], _R]) -> Callable[[tuple[Unpack[_Ts]]], _R]: ...
diff --git a/pkg_resources/_vendor/more_itertools/py.typed b/setuptools/_vendor/jaraco/functools/py.typed
similarity index 100%
rename from pkg_resources/_vendor/more_itertools/py.typed
rename to setuptools/_vendor/jaraco/functools/py.typed
diff --git a/setuptools/_vendor/jaraco/text/__init__.py b/setuptools/_vendor/jaraco/text/__init__.py
index a0306d5ff5..8567200ad7 100644
--- a/setuptools/_vendor/jaraco/text/__init__.py
+++ b/setuptools/_vendor/jaraco/text/__init__.py
@@ -1,15 +1,17 @@
-import re
+import functools
 import itertools
+import re
 import textwrap
-import functools
+
+from typing import Iterable
 
 try:
     from importlib.resources import files  # type: ignore
 except ImportError:  # pragma: nocover
-    from setuptools.extern.importlib_resources import files  # type: ignore
+    from importlib_resources import files  # type: ignore
 
-from setuptools.extern.jaraco.functools import compose, method_cache
-from setuptools.extern.jaraco.context import ExceptionTrap
+from jaraco.context import ExceptionTrap
+from jaraco.functools import compose, method_cache
 
 
 def substitution(old, new):
@@ -66,7 +68,7 @@ class FoldedCase(str):
     >>> s in ["Hello World"]
     True
 
-    You may test for set inclusion, but candidate and elements
+    Allows testing for set inclusion, but candidate and elements
     must both be folded.
 
     >>> FoldedCase("Hello World") in {s}
@@ -92,37 +94,40 @@ class FoldedCase(str):
 
     >>> FoldedCase('hello') > FoldedCase('Hello')
     False
+
+    >>> FoldedCase('ß') == FoldedCase('ss')
+    True
     """
 
     def __lt__(self, other):
-        return self.lower() < other.lower()
+        return self.casefold() < other.casefold()
 
     def __gt__(self, other):
-        return self.lower() > other.lower()
+        return self.casefold() > other.casefold()
 
     def __eq__(self, other):
-        return self.lower() == other.lower()
+        return self.casefold() == other.casefold()
 
     def __ne__(self, other):
-        return self.lower() != other.lower()
+        return self.casefold() != other.casefold()
 
     def __hash__(self):
-        return hash(self.lower())
+        return hash(self.casefold())
 
     def __contains__(self, other):
-        return super().lower().__contains__(other.lower())
+        return super().casefold().__contains__(other.casefold())
 
     def in_(self, other):
         "Does self appear in other?"
         return self in FoldedCase(other)
 
-    # cache lower since it's likely to be called frequently.
+    # cache casefold since it's likely to be called frequently.
     @method_cache
-    def lower(self):
-        return super().lower()
+    def casefold(self):
+        return super().casefold()
 
     def index(self, sub):
-        return self.lower().index(sub.lower())
+        return self.casefold().index(sub.casefold())
 
     def split(self, splitter=' ', maxsplit=0):
         pattern = re.compile(re.escape(splitter), re.I)
@@ -224,9 +229,12 @@ def unwrap(s):
     return '\n'.join(cleaned)
 
 
+lorem_ipsum: str = (
+    files(__name__).joinpath('Lorem ipsum.txt').read_text(encoding='utf-8')
+)
 
 
-class Splitter(object):
+class Splitter:
     """object that will split a string with the given arguments for each call
 
     >>> s = Splitter(',')
@@ -276,7 +284,7 @@ class WordSet(tuple):
     >>> WordSet.parse("myABCClass")
     ('my', 'ABC', 'Class')
 
-    The result is a WordSet, so you can get the form you need.
+    The result is a WordSet, providing access to other forms.
 
     >>> WordSet.parse("myABCClass").underscore_separated()
     'my_ABC_Class'
@@ -363,7 +371,7 @@ def trim(self, item):
         return self.trim_left(item).trim_right(item)
 
     def __getitem__(self, item):
-        result = super(WordSet, self).__getitem__(item)
+        result = super().__getitem__(item)
         if isinstance(item, slice):
             result = WordSet(result)
         return result
@@ -548,7 +556,14 @@ def yield_lines(iterable):
 
 @yield_lines.register(str)
 def _(text):
-    return filter(_nonblank, map(str.strip, text.splitlines()))
+    return clean(text.splitlines())
+
+
+def clean(lines: Iterable[str]):
+    """
+    Yield non-blank, non-comment elements from lines.
+    """
+    return filter(_nonblank, map(str.strip, lines))
 
 
 def drop_comment(line):
@@ -578,7 +593,7 @@ def join_continuation(lines):
     ['foobarbaz']
 
     Not sure why, but...
-    The character preceeding the backslash is also elided.
+    The character preceding the backslash is also elided.
 
     >>> list(join_continuation(['goo\\', 'dly']))
     ['godly']
@@ -597,3 +612,36 @@ def join_continuation(lines):
             except StopIteration:
                 return
         yield item
+
+
+def read_newlines(filename, limit=1024):
+    r"""
+    >>> tmp_path = getfixture('tmp_path')
+    >>> filename = tmp_path / 'out.txt'
+    >>> _ = filename.write_text('foo\n', newline='', encoding='utf-8')
+    >>> read_newlines(filename)
+    '\n'
+    >>> _ = filename.write_text('foo\r\n', newline='', encoding='utf-8')
+    >>> read_newlines(filename)
+    '\r\n'
+    >>> _ = filename.write_text('foo\r\nbar\nbing\r', newline='', encoding='utf-8')
+    >>> read_newlines(filename)
+    ('\r', '\n', '\r\n')
+    """
+    with open(filename, encoding='utf-8') as fp:
+        fp.read(limit)
+    return fp.newlines
+
+
+def lines_from(input):
+    """
+    Generate lines from a :class:`importlib.resources.abc.Traversable` path.
+
+    >>> lines = lines_from(files(__name__).joinpath('Lorem ipsum.txt'))
+    >>> next(lines)
+    'Lorem ipsum...'
+    >>> next(lines)
+    'Curabitur pretium...'
+    """
+    with input.open(encoding='utf-8') as stream:
+        yield from stream
diff --git a/setuptools/_vendor/jaraco/text/layouts.py b/setuptools/_vendor/jaraco/text/layouts.py
new file mode 100644
index 0000000000..9636f0f7b5
--- /dev/null
+++ b/setuptools/_vendor/jaraco/text/layouts.py
@@ -0,0 +1,25 @@
+qwerty = "-=qwertyuiop[]asdfghjkl;'zxcvbnm,./_+QWERTYUIOP{}ASDFGHJKL:\"ZXCVBNM<>?"
+dvorak = "[]',.pyfgcrl/=aoeuidhtns-;qjkxbmwvz{}\"<>PYFGCRL?+AOEUIDHTNS_:QJKXBMWVZ"
+
+
+to_dvorak = str.maketrans(qwerty, dvorak)
+to_qwerty = str.maketrans(dvorak, qwerty)
+
+
+def translate(input, translation):
+    """
+    >>> translate('dvorak', to_dvorak)
+    'ekrpat'
+    >>> translate('qwerty', to_qwerty)
+    'x,dokt'
+    """
+    return input.translate(translation)
+
+
+def _translate_stream(stream, translation):
+    """
+    >>> import io
+    >>> _translate_stream(io.StringIO('foo'), to_dvorak)
+    urr
+    """
+    print(translate(stream.read(), translation))
diff --git a/setuptools/_vendor/jaraco/text/show-newlines.py b/setuptools/_vendor/jaraco/text/show-newlines.py
new file mode 100644
index 0000000000..ef4cc54c9e
--- /dev/null
+++ b/setuptools/_vendor/jaraco/text/show-newlines.py
@@ -0,0 +1,32 @@
+import autocommand
+import inflect
+from more_itertools import always_iterable
+
+import jaraco.text
+
+
+def report_newlines(filename):
+    r"""
+    Report the newlines in the indicated file.
+
+    >>> tmp_path = getfixture('tmp_path')
+    >>> filename = tmp_path / 'out.txt'
+    >>> _ = filename.write_text('foo\nbar\n', newline='', encoding='utf-8')
+    >>> report_newlines(filename)
+    newline is '\n'
+    >>> filename = tmp_path / 'out.txt'
+    >>> _ = filename.write_text('foo\nbar\r\n', newline='', encoding='utf-8')
+    >>> report_newlines(filename)
+    newlines are ('\n', '\r\n')
+    """
+    newlines = jaraco.text.read_newlines(filename)
+    count = len(tuple(always_iterable(newlines)))
+    engine = inflect.engine()
+    print(
+        engine.plural_noun("newline", count),
+        engine.plural_verb("is", count),
+        repr(newlines),
+    )
+
+
+autocommand.autocommand(__name__)(report_newlines)
diff --git a/setuptools/_vendor/jaraco/text/strip-prefix.py b/setuptools/_vendor/jaraco/text/strip-prefix.py
new file mode 100644
index 0000000000..761717a9b9
--- /dev/null
+++ b/setuptools/_vendor/jaraco/text/strip-prefix.py
@@ -0,0 +1,21 @@
+import sys
+
+import autocommand
+
+from jaraco.text import Stripper
+
+
+def strip_prefix():
+    r"""
+    Strip any common prefix from stdin.
+
+    >>> import io, pytest
+    >>> getfixture('monkeypatch').setattr('sys.stdin', io.StringIO('abcdef\nabc123'))
+    >>> strip_prefix()
+    def
+    123
+    """
+    sys.stdout.writelines(Stripper.strip_prefix(sys.stdin).lines)
+
+
+autocommand.autocommand(__name__)(strip_prefix)
diff --git a/setuptools/_vendor/jaraco/text/to-dvorak.py b/setuptools/_vendor/jaraco/text/to-dvorak.py
new file mode 100644
index 0000000000..14c8981e44
--- /dev/null
+++ b/setuptools/_vendor/jaraco/text/to-dvorak.py
@@ -0,0 +1,5 @@
+import sys
+
+from . import layouts
+
+__name__ == '__main__' and layouts._translate_stream(sys.stdin, layouts.to_dvorak)
diff --git a/setuptools/_vendor/jaraco/text/to-qwerty.py b/setuptools/_vendor/jaraco/text/to-qwerty.py
new file mode 100644
index 0000000000..23596fda93
--- /dev/null
+++ b/setuptools/_vendor/jaraco/text/to-qwerty.py
@@ -0,0 +1,5 @@
+import sys
+
+from . import layouts
+
+__name__ == '__main__' and layouts._translate_stream(sys.stdin, layouts.to_qwerty)
diff --git a/setuptools/_vendor/jaraco_context-6.1.0.dist-info/INSTALLER b/setuptools/_vendor/jaraco_context-6.1.0.dist-info/INSTALLER
new file mode 100644
index 0000000000..5c69047b2e
--- /dev/null
+++ b/setuptools/_vendor/jaraco_context-6.1.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/setuptools/_vendor/jaraco_context-6.1.0.dist-info/METADATA b/setuptools/_vendor/jaraco_context-6.1.0.dist-info/METADATA
new file mode 100644
index 0000000000..8fb5e53da3
--- /dev/null
+++ b/setuptools/_vendor/jaraco_context-6.1.0.dist-info/METADATA
@@ -0,0 +1,82 @@
+Metadata-Version: 2.4
+Name: jaraco.context
+Version: 6.1.0
+Summary: Useful decorators and context managers
+Author-email: "Jason R. Coombs" 
+License-Expression: MIT
+Project-URL: Source, https://github.com/jaraco/jaraco.context
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Requires-Python: >=3.9
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Requires-Dist: backports.tarfile; python_version < "3.12"
+Provides-Extra: test
+Requires-Dist: pytest!=8.1.*,>=6; extra == "test"
+Requires-Dist: jaraco.test>=5.6.0; extra == "test"
+Requires-Dist: portend; extra == "test"
+Provides-Extra: doc
+Requires-Dist: sphinx>=3.5; extra == "doc"
+Requires-Dist: jaraco.packaging>=9.3; extra == "doc"
+Requires-Dist: rst.linker>=1.9; extra == "doc"
+Requires-Dist: furo; extra == "doc"
+Requires-Dist: sphinx-lint; extra == "doc"
+Requires-Dist: jaraco.tidelift>=1.4; extra == "doc"
+Provides-Extra: check
+Requires-Dist: pytest-checkdocs>=2.4; extra == "check"
+Requires-Dist: pytest-ruff>=0.2.1; sys_platform != "cygwin" and extra == "check"
+Provides-Extra: cover
+Requires-Dist: pytest-cov; extra == "cover"
+Provides-Extra: enabler
+Requires-Dist: pytest-enabler>=3.4; extra == "enabler"
+Provides-Extra: type
+Requires-Dist: pytest-mypy>=1.0.1; extra == "type"
+Requires-Dist: mypy<1.19; platform_python_implementation == "PyPy" and extra == "type"
+Dynamic: license-file
+
+.. image:: https://img.shields.io/pypi/v/jaraco.context.svg
+   :target: https://pypi.org/project/jaraco.context
+
+.. image:: https://img.shields.io/pypi/pyversions/jaraco.context.svg
+
+.. image:: https://github.com/jaraco/jaraco.context/actions/workflows/main.yml/badge.svg
+   :target: https://github.com/jaraco/jaraco.context/actions?query=workflow%3A%22tests%22
+   :alt: tests
+
+.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json
+    :target: https://github.com/astral-sh/ruff
+    :alt: Ruff
+
+.. image:: https://readthedocs.org/projects/jaracocontext/badge/?version=latest
+   :target: https://jaracocontext.readthedocs.io/en/latest/?badge=latest
+
+.. image:: https://img.shields.io/badge/skeleton-2025-informational
+   :target: https://blog.jaraco.com/skeleton
+
+.. image:: https://tidelift.com/badges/package/pypi/jaraco.context
+   :target: https://tidelift.com/subscription/pkg/pypi-jaraco.context?utm_source=pypi-jaraco.context&utm_medium=readme
+
+
+Highlights
+==========
+
+See the docs linked from the badge above for the full details, but here are some features that may be of interest.
+
+- ``ExceptionTrap`` provides a general-purpose wrapper for trapping exceptions and then acting on the outcome. Includes ``passes`` and ``raises`` decorators to replace the result of a wrapped function by a boolean indicating the outcome of the exception trap. See `this keyring commit `_ for an example of it in production.
+- ``suppress`` simply enables ``contextlib.suppress`` as a decorator.
+- ``on_interrupt`` is a decorator used by CLI entry points to affect the handling of a ``KeyboardInterrupt``. Inspired by `Lucretiel/autocommand#18 `_.
+- ``pushd`` is similar to pytest's ``monkeypatch.chdir`` or path's `default context `_, changes the current working directory for the duration of the context.
+- ``tarball`` will download a tarball, extract it, change directory, yield, then clean up after. Convenient when working with web assets.
+- ``null`` is there for those times when one code branch needs a context and the other doesn't; this null context provides symmetry across those branches.
+
+
+For Enterprise
+==============
+
+Available as part of the Tidelift Subscription.
+
+This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
+
+`Learn more `_.
diff --git a/setuptools/_vendor/jaraco_context-6.1.0.dist-info/RECORD b/setuptools/_vendor/jaraco_context-6.1.0.dist-info/RECORD
new file mode 100644
index 0000000000..e5169f6659
--- /dev/null
+++ b/setuptools/_vendor/jaraco_context-6.1.0.dist-info/RECORD
@@ -0,0 +1,9 @@
+jaraco/context/__init__.py,sha256=br1ydYGo1Xr_Pu1anuEdd-QrjUiz_EY5L_5E4C03L4w,9809
+jaraco/context/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+jaraco_context-6.1.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+jaraco_context-6.1.0.dist-info/METADATA,sha256=BDXr_FIFXFqZdO0gwXG2RUOD6vnbsVCIFLp62XxZ1xI,4270
+jaraco_context-6.1.0.dist-info/RECORD,,
+jaraco_context-6.1.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+jaraco_context-6.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
+jaraco_context-6.1.0.dist-info/licenses/LICENSE,sha256=l1WhhRlmbl8PTK49qtPXASvK5IpgCzEjfXXp_hNOZoM,1076
+jaraco_context-6.1.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7
diff --git a/pkg_resources/_vendor/zipp-3.7.0.dist-info/REQUESTED b/setuptools/_vendor/jaraco_context-6.1.0.dist-info/REQUESTED
similarity index 100%
rename from pkg_resources/_vendor/zipp-3.7.0.dist-info/REQUESTED
rename to setuptools/_vendor/jaraco_context-6.1.0.dist-info/REQUESTED
diff --git a/pkg_resources/_vendor/zipp-3.7.0.dist-info/WHEEL b/setuptools/_vendor/jaraco_context-6.1.0.dist-info/WHEEL
similarity index 65%
rename from pkg_resources/_vendor/zipp-3.7.0.dist-info/WHEEL
rename to setuptools/_vendor/jaraco_context-6.1.0.dist-info/WHEEL
index becc9a66ea..e7fa31b6f3 100644
--- a/pkg_resources/_vendor/zipp-3.7.0.dist-info/WHEEL
+++ b/setuptools/_vendor/jaraco_context-6.1.0.dist-info/WHEEL
@@ -1,5 +1,5 @@
 Wheel-Version: 1.0
-Generator: bdist_wheel (0.37.1)
+Generator: setuptools (80.9.0)
 Root-Is-Purelib: true
 Tag: py3-none-any
 
diff --git a/setuptools/_vendor/jaraco_context-6.1.0.dist-info/licenses/LICENSE b/setuptools/_vendor/jaraco_context-6.1.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000..c891f411dc
--- /dev/null
+++ b/setuptools/_vendor/jaraco_context-6.1.0.dist-info/licenses/LICENSE
@@ -0,0 +1,18 @@
+MIT License
+
+Copyright (c) 2026 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
+following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial
+portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
+LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
+EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/top_level.txt b/setuptools/_vendor/jaraco_context-6.1.0.dist-info/top_level.txt
similarity index 100%
rename from pkg_resources/_vendor/jaraco.functools-3.6.0.dist-info/top_level.txt
rename to setuptools/_vendor/jaraco_context-6.1.0.dist-info/top_level.txt
diff --git a/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/INSTALLER b/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/INSTALLER
new file mode 100644
index 0000000000..5c69047b2e
--- /dev/null
+++ b/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/METADATA b/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/METADATA
new file mode 100644
index 0000000000..f2150dd88b
--- /dev/null
+++ b/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/METADATA
@@ -0,0 +1,69 @@
+Metadata-Version: 2.4
+Name: jaraco.functools
+Version: 4.4.0
+Summary: Functools like those found in stdlib
+Author-email: "Jason R. Coombs" 
+License-Expression: MIT
+Project-URL: Source, https://github.com/jaraco/jaraco.functools
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Requires-Python: >=3.9
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Requires-Dist: more_itertools
+Provides-Extra: test
+Requires-Dist: pytest!=8.1.*,>=6; extra == "test"
+Requires-Dist: jaraco.classes; extra == "test"
+Provides-Extra: doc
+Requires-Dist: sphinx>=3.5; extra == "doc"
+Requires-Dist: jaraco.packaging>=9.3; extra == "doc"
+Requires-Dist: rst.linker>=1.9; extra == "doc"
+Requires-Dist: furo; extra == "doc"
+Requires-Dist: sphinx-lint; extra == "doc"
+Requires-Dist: jaraco.tidelift>=1.4; extra == "doc"
+Provides-Extra: check
+Requires-Dist: pytest-checkdocs>=2.4; extra == "check"
+Requires-Dist: pytest-ruff>=0.2.1; sys_platform != "cygwin" and extra == "check"
+Provides-Extra: cover
+Requires-Dist: pytest-cov; extra == "cover"
+Provides-Extra: enabler
+Requires-Dist: pytest-enabler>=3.4; extra == "enabler"
+Provides-Extra: type
+Requires-Dist: pytest-mypy>=1.0.1; extra == "type"
+Requires-Dist: mypy<1.19; platform_python_implementation == "PyPy" and extra == "type"
+Dynamic: license-file
+
+.. image:: https://img.shields.io/pypi/v/jaraco.functools.svg
+   :target: https://pypi.org/project/jaraco.functools
+
+.. image:: https://img.shields.io/pypi/pyversions/jaraco.functools.svg
+
+.. image:: https://github.com/jaraco/jaraco.functools/actions/workflows/main.yml/badge.svg
+   :target: https://github.com/jaraco/jaraco.functools/actions?query=workflow%3A%22tests%22
+   :alt: tests
+
+.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json
+    :target: https://github.com/astral-sh/ruff
+    :alt: Ruff
+
+.. image:: https://readthedocs.org/projects/jaracofunctools/badge/?version=latest
+   :target: https://jaracofunctools.readthedocs.io/en/latest/?badge=latest
+
+.. image:: https://img.shields.io/badge/skeleton-2025-informational
+   :target: https://blog.jaraco.com/skeleton
+
+.. image:: https://tidelift.com/badges/package/pypi/jaraco.functools
+   :target: https://tidelift.com/subscription/pkg/pypi-jaraco.functools?utm_source=pypi-jaraco.functools&utm_medium=readme
+
+Additional functools in the spirit of stdlib's functools.
+
+For Enterprise
+==============
+
+Available as part of the Tidelift Subscription.
+
+This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
+
+`Learn more `_.
diff --git a/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/RECORD b/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/RECORD
new file mode 100644
index 0000000000..3516c9f039
--- /dev/null
+++ b/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/RECORD
@@ -0,0 +1,10 @@
+jaraco/functools/__init__.py,sha256=ZJx9cMs2Nvk2xGUl8OjVGkpjdOaNlSzJrN4dGglgX2g,18599
+jaraco/functools/__init__.pyi,sha256=K4DcbnYIHE5QlMxqf9-cVp-WhycrhuTao4J7O7TMq4Y,3907
+jaraco/functools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+jaraco_functools-4.4.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+jaraco_functools-4.4.0.dist-info/METADATA,sha256=LnnajcNGmSSr46yLIqP-tWkqeb-fR7vIa2U11hhkGEk,2960
+jaraco_functools-4.4.0.dist-info/RECORD,,
+jaraco_functools-4.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+jaraco_functools-4.4.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
+jaraco_functools-4.4.0.dist-info/licenses/LICENSE,sha256=WlfLTbheKi3YjCkGKJCK3VfjRRRJ4KmnH9-zh3b9dZ0,1076
+jaraco_functools-4.4.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7
diff --git a/setuptools/_vendor/importlib_metadata-6.0.0.dist-info/REQUESTED b/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/REQUESTED
similarity index 100%
rename from setuptools/_vendor/importlib_metadata-6.0.0.dist-info/REQUESTED
rename to setuptools/_vendor/jaraco_functools-4.4.0.dist-info/REQUESTED
diff --git a/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/WHEEL b/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/WHEEL
new file mode 100644
index 0000000000..e7fa31b6f3
--- /dev/null
+++ b/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (80.9.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/licenses/LICENSE b/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000..f60bd57201
--- /dev/null
+++ b/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/licenses/LICENSE
@@ -0,0 +1,18 @@
+MIT License
+
+Copyright (c) 2025 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
+following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial
+portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
+LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
+EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/top_level.txt b/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/top_level.txt
similarity index 100%
rename from pkg_resources/_vendor/jaraco.text-3.7.0.dist-info/top_level.txt
rename to setuptools/_vendor/jaraco_functools-4.4.0.dist-info/top_level.txt
diff --git a/setuptools/_vendor/more_itertools-10.8.0.dist-info/INSTALLER b/setuptools/_vendor/more_itertools-10.8.0.dist-info/INSTALLER
new file mode 100644
index 0000000000..5c69047b2e
--- /dev/null
+++ b/setuptools/_vendor/more_itertools-10.8.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/pkg_resources/_vendor/more_itertools-9.1.0.dist-info/METADATA b/setuptools/_vendor/more_itertools-10.8.0.dist-info/METADATA
similarity index 78%
rename from pkg_resources/_vendor/more_itertools-9.1.0.dist-info/METADATA
rename to setuptools/_vendor/more_itertools-10.8.0.dist-info/METADATA
index bee8776239..bb7a3db109 100644
--- a/pkg_resources/_vendor/more_itertools-9.1.0.dist-info/METADATA
+++ b/setuptools/_vendor/more_itertools-10.8.0.dist-info/METADATA
@@ -1,25 +1,27 @@
-Metadata-Version: 2.1
+Metadata-Version: 2.4
 Name: more-itertools
-Version: 9.1.0
+Version: 10.8.0
 Summary: More routines for operating on iterables, beyond itertools
 Keywords: itertools,iterator,iteration,filter,peek,peekable,chunk,chunked
 Author-email: Erik Rose 
-Requires-Python: >=3.7
+Requires-Python: >=3.9
 Description-Content-Type: text/x-rst
+License-Expression: MIT
 Classifier: Development Status :: 5 - Production/Stable
 Classifier: Intended Audience :: Developers
 Classifier: Natural Language :: English
-Classifier: License :: OSI Approved :: MIT License
 Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3.7
-Classifier: Programming Language :: Python :: 3.8
 Classifier: Programming Language :: Python :: 3.9
 Classifier: Programming Language :: Python :: 3.10
 Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
 Classifier: Programming Language :: Python :: 3 :: Only
 Classifier: Programming Language :: Python :: Implementation :: CPython
 Classifier: Programming Language :: Python :: Implementation :: PyPy
 Classifier: Topic :: Software Development :: Libraries
+License-File: LICENSE
+Project-URL: Documentation, https://more-itertools.readthedocs.io/en/stable/
 Project-URL: Homepage, https://github.com/more-itertools/more-itertools
 
 ==============
@@ -51,7 +53,7 @@ Python iterables.
 |                        | `unzip `_,                                                                                   |
 |                        | `batched `_,                                                                               |
 |                        | `grouper `_,                                                                               |
-|                        | `partition `_                                                                            |
+|                        | `partition `_,                                                                           |
 |                        | `transpose `_                                                                            |
 +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
 | Lookahead and lookback | `spy `_,                                                                                       |
@@ -84,15 +86,15 @@ Python iterables.
 |                        | `interleave `_,                                                                         |
 |                        | `interleave_longest `_,                                                         |
 |                        | `interleave_evenly `_,                                                           |
+|                        | `interleave_randomly `_,                                                       |
 |                        | `zip_offset `_,                                                                         |
 |                        | `zip_equal `_,                                                                           |
 |                        | `zip_broadcast `_,                                                                   |
-|                        | `dotproduct `_,                                                                         |
-|                        | `convolve `_,                                                                             |
 |                        | `flatten `_,                                                                               |
 |                        | `roundrobin `_,                                                                         |
 |                        | `prepend `_,                                                                               |
-|                        | `value_chain `_                                                                        |
+|                        | `value_chain `_,                                                                       |
+|                        | `partial_product `_                                                                |
 +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
 | Summarizing            | `ilen `_,                                                                                     |
 |                        | `unique_to_each `_,                                                                 |
@@ -100,10 +102,13 @@ Python iterables.
 |                        | `consecutive_groups `_,                                                         |
 |                        | `run_length `_,                                                                         |
 |                        | `map_reduce `_,                                                                         |
+|                        | `join_mappings `_,                                                                   |
 |                        | `exactly_n `_,                                                                           |
 |                        | `is_sorted `_,                                                                           |
 |                        | `all_equal `_,                                                                           |
 |                        | `all_unique `_,                                                                         |
+|                        | `argmin `_,                                                                                 |
+|                        | `argmax `_,                                                                                 |
 |                        | `minmax `_,                                                                                 |
 |                        | `first_true `_,                                                                         |
 |                        | `quantify `_,                                                                             |
@@ -120,35 +125,68 @@ Python iterables.
 |                        | `rstrip `_,                                                                                 |
 |                        | `filter_except `_,                                                                   |
 |                        | `map_except `_,                                                                         |
+|                        | `filter_map `_,                                                                         |
+|                        | `iter_suppress `_,                                                                   |
 |                        | `nth_or_last `_,                                                                       |
+|                        | `extract `_,                                                                               |
 |                        | `unique_in_window `_,                                                             |
 |                        | `before_and_after `_,                                                             |
 |                        | `nth `_,                                                                                       |
 |                        | `take `_,                                                                                     |
 |                        | `tail `_,                                                                                     |
-|                        | `unique_everseen `_,                                                              |
+|                        | `unique_everseen `_,                                                               |
 |                        | `unique_justseen `_,                                                               |
+|                        | `unique `_,                                                                                 |
 |                        | `duplicates_everseen `_,                                                       |
 |                        | `duplicates_justseen `_,                                                       |
-|                        | `longest_common_prefix `_                                                    |
+|                        | `classify_unique `_,                                                               |
+|                        | `longest_common_prefix `_,                                                   |
+|                        | `takewhile_inclusive `_                                                        |
 +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| Combinatorics          | `distinct_permutations `_,                                                   |
-|                        | `distinct_combinations `_,                                                   |
-|                        | `circular_shifts `_,                                                               |
+| Math                   | `dft `_,                                                                                       |
+|                        | `idft `_,                                                                                     |
+|                        | `convolve `_,                                                                             |
+|                        | `dotproduct `_,                                                                         |
+|                        | `matmul `_,                                                                                 |
+|                        | `polynomial_from_roots `_,                                                   |
+|                        | `polynomial_derivative `_,                                                   |
+|                        | `polynomial_eval `_,                                                               |
+|                        | `sum_of_squares `_,                                                                 |
+|                        | `running_median `_,                                                                 |
+|                        | `totient `_                                                                                |
++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| Integer math           | `factor `_,                                                                                 |
+|                        | `is_prime `_,                                                                             |
+|                        | `multinomial `_,                                                                       |
+|                        | `nth_prime `_,                                                                           |
+|                        | `sieve `_                                                                                    |
++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| Combinatorics          | `circular_shifts `_,                                                               |
+|                        | `derangements `_,                                                                     |
+|                        | `gray_product  `_,                                                                    |
+|                        | `outer_product  `_,                                                                  |
 |                        | `partitions `_,                                                                         |
 |                        | `set_partitions `_,                                                                 |
-|                        | `product_index `_,                                                                   |
+|                        | `powerset `_,                                                                             |
+|                        | `powerset_of_sets `_                                                              |
+|                        +-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+|                        | `distinct_combinations `_,                                                   |
+|                        | `distinct_permutations `_                                                    |
+|                        +-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
 |                        | `combination_index `_,                                                           |
+|                        | `combination_with_replacement_index `_,                         |
 |                        | `permutation_index `_,                                                           |
-|                        | `gray_product  `_,                                                                    |
-|                        | `powerset `_,                                                                             |
-|                        | `random_product `_,                                                                 |
-|                        | `random_permutation `_,                                                         |
+|                        | `product_index `_                                                                    |
+|                        +-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+|                        | `nth_combination `_,                                                               |
+|                        | `nth_combination_with_replacement `_,                             |
+|                        | `nth_permutation `_,                                                               |
+|                        | `nth_product `_                                                                        |
+|                        +-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
 |                        | `random_combination `_,                                                         |
 |                        | `random_combination_with_replacement `_,                       |
-|                        | `nth_product `_,                                                                       |
-|                        | `nth_permutation `_,                                                               |
-|                        | `nth_combination `_                                                                |
+|                        | `random_permutation `_,                                                         |
+|                        | `random_product `_                                                                  |
 +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
 | Wrapping               | `always_iterable `_,                                                               |
 |                        | `always_reversible `_,                                                           |
@@ -163,6 +201,7 @@ Python iterables.
 |                        | `numeric_range `_,                                                                   |
 |                        | `side_effect `_,                                                                       |
 |                        | `iterate `_,                                                                               |
+|                        | `loops `_,                                                                                   |
 |                        | `difference `_,                                                                         |
 |                        | `make_decorator `_,                                                                 |
 |                        | `SequenceView `_,                                                                     |
@@ -172,10 +211,8 @@ Python iterables.
 |                        | `consume `_,                                                                               |
 |                        | `tabulate `_,                                                                             |
 |                        | `repeatfunc `_,                                                                         |
-|                        | `polynomial_from_roots `_,                                                   |
-|                        | `sieve `_                                                                                    |
-|                        | `factor `_                                                                                  |
-|                        | `matmul `_                                                                                  |
+|                        | `reshape `_,                                                                               |
+|                        | `doublestarmap `_                                                                    |
 +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
 
 
@@ -227,7 +264,7 @@ Blog posts about ``more-itertools``:
 
 * `Yo, I heard you like decorators `__
 * `Tour of Python Itertools `__ (`Alternate `__)
-* `Real-World Python More Itertools `_
+* `Real-World Python More Itertools `_
 
 
 Development
diff --git a/setuptools/_vendor/more_itertools-10.8.0.dist-info/RECORD b/setuptools/_vendor/more_itertools-10.8.0.dist-info/RECORD
new file mode 100644
index 0000000000..61ef7d6dd0
--- /dev/null
+++ b/setuptools/_vendor/more_itertools-10.8.0.dist-info/RECORD
@@ -0,0 +1,13 @@
+more_itertools-10.8.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+more_itertools-10.8.0.dist-info/METADATA,sha256=arNRUUWr5YsGfwh8hnYxz0z11lP-2BuWQu4SCGw5BLg,39413
+more_itertools-10.8.0.dist-info/RECORD,,
+more_itertools-10.8.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+more_itertools-10.8.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
+more_itertools-10.8.0.dist-info/licenses/LICENSE,sha256=CfHIyelBrz5YTVlkHqm4fYPAyw_QB-te85Gn4mQ8GkY,1053
+more_itertools/__init__.py,sha256=5F7E_zpoGcEBW_T_3WE0WYYt8j-gJodIuiBcOJxrOv8,149
+more_itertools/__init__.pyi,sha256=5B3eTzON1BBuOLob1vCflyEb2lSd6usXQQ-Cv-hXkeA,43
+more_itertools/more.py,sha256=mNPKKu5UI7lRL460vgm0QTCWFiGMVCMosSPxVSdibos,163690
+more_itertools/more.pyi,sha256=fpEgNX3O66wY5cnT-s5VYDKNUpAcaCyU3iP84It3OOM,27119
+more_itertools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+more_itertools/recipes.py,sha256=Ma-kuBNZDFhaQDbIJgRmnrG86WzaupbOyUV3v8je3xw,41811
+more_itertools/recipes.pyi,sha256=LNRwN-OL3nkMfQAqx-PPc1fBaetUObb_Z6mdePyzh1c,6226
diff --git a/setuptools/_vendor/importlib_resources-5.10.2.dist-info/REQUESTED b/setuptools/_vendor/more_itertools-10.8.0.dist-info/REQUESTED
similarity index 100%
rename from setuptools/_vendor/importlib_resources-5.10.2.dist-info/REQUESTED
rename to setuptools/_vendor/more_itertools-10.8.0.dist-info/REQUESTED
diff --git a/pkg_resources/_vendor/packaging-23.1.dist-info/WHEEL b/setuptools/_vendor/more_itertools-10.8.0.dist-info/WHEEL
similarity index 71%
rename from pkg_resources/_vendor/packaging-23.1.dist-info/WHEEL
rename to setuptools/_vendor/more_itertools-10.8.0.dist-info/WHEEL
index db4a255f3a..d8b9936dad 100644
--- a/pkg_resources/_vendor/packaging-23.1.dist-info/WHEEL
+++ b/setuptools/_vendor/more_itertools-10.8.0.dist-info/WHEEL
@@ -1,4 +1,4 @@
 Wheel-Version: 1.0
-Generator: flit 3.8.0
+Generator: flit 3.12.0
 Root-Is-Purelib: true
 Tag: py3-none-any
diff --git a/pkg_resources/_vendor/more_itertools-9.1.0.dist-info/LICENSE b/setuptools/_vendor/more_itertools-10.8.0.dist-info/licenses/LICENSE
similarity index 100%
rename from pkg_resources/_vendor/more_itertools-9.1.0.dist-info/LICENSE
rename to setuptools/_vendor/more_itertools-10.8.0.dist-info/licenses/LICENSE
diff --git a/setuptools/_vendor/more_itertools-8.8.0.dist-info/INSTALLER b/setuptools/_vendor/more_itertools-8.8.0.dist-info/INSTALLER
deleted file mode 100644
index a1b589e38a..0000000000
--- a/setuptools/_vendor/more_itertools-8.8.0.dist-info/INSTALLER
+++ /dev/null
@@ -1 +0,0 @@
-pip
diff --git a/setuptools/_vendor/more_itertools-8.8.0.dist-info/LICENSE b/setuptools/_vendor/more_itertools-8.8.0.dist-info/LICENSE
deleted file mode 100644
index 0a523bece3..0000000000
--- a/setuptools/_vendor/more_itertools-8.8.0.dist-info/LICENSE
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright (c) 2012 Erik Rose
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-of the Software, and to permit persons to whom the Software is furnished to do
-so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/setuptools/_vendor/more_itertools-8.8.0.dist-info/METADATA b/setuptools/_vendor/more_itertools-8.8.0.dist-info/METADATA
deleted file mode 100644
index bdaee6553f..0000000000
--- a/setuptools/_vendor/more_itertools-8.8.0.dist-info/METADATA
+++ /dev/null
@@ -1,462 +0,0 @@
-Metadata-Version: 2.1
-Name: more-itertools
-Version: 8.8.0
-Summary: More routines for operating on iterables, beyond itertools
-Home-page: https://github.com/more-itertools/more-itertools
-Author: Erik Rose
-Author-email: erikrose@grinchcentral.com
-License: MIT
-Keywords: itertools,iterator,iteration,filter,peek,peekable,collate,chunk,chunked
-Platform: UNKNOWN
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Intended Audience :: Developers
-Classifier: Natural Language :: English
-Classifier: License :: OSI Approved :: MIT License
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3.6
-Classifier: Programming Language :: Python :: 3.7
-Classifier: Programming Language :: Python :: 3.8
-Classifier: Programming Language :: Python :: 3.9
-Classifier: Programming Language :: Python :: 3 :: Only
-Classifier: Programming Language :: Python :: Implementation :: CPython
-Classifier: Programming Language :: Python :: Implementation :: PyPy
-Classifier: Topic :: Software Development :: Libraries
-Requires-Python: >=3.5
-Description-Content-Type: text/x-rst
-
-==============
-More Itertools
-==============
-
-.. image:: https://readthedocs.org/projects/more-itertools/badge/?version=latest
-  :target: https://more-itertools.readthedocs.io/en/stable/
-
-Python's ``itertools`` library is a gem - you can compose elegant solutions
-for a variety of problems with the functions it provides. In ``more-itertools``
-we collect additional building blocks, recipes, and routines for working with
-Python iterables.
-
-+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| Grouping               | `chunked `_,                                                                                                                        |
-|                        | `ichunked `_,                                                                                                                      |
-|                        | `sliced `_,                                                                                                                          |
-|                        | `distribute `_,                                                                                                                  |
-|                        | `divide `_,                                                                                                                          |
-|                        | `split_at `_,                                                                                                                      |
-|                        | `split_before `_,                                                                                                              |
-|                        | `split_after `_,                                                                                                                |
-|                        | `split_into `_,                                                                                                                  |
-|                        | `split_when `_,                                                                                                                  |
-|                        | `bucket `_,                                                                                                                          |
-|                        | `unzip `_,                                                                                                                            |
-|                        | `grouper `_,                                                                                                                        |
-|                        | `partition `_                                                                                                                     |
-+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| Lookahead and lookback | `spy `_,                                                                                                                                |
-|                        | `peekable `_,                                                                                                                      |
-|                        | `seekable `_                                                                                                                       |
-+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| Windowing              | `windowed `_,                                                                                                                      |
-|                        | `substrings `_,                                                                                                                  |
-|                        | `substrings_indexes `_,                                                                                                  |
-|                        | `stagger `_,                                                                                                                        |
-|                        | `windowed_complete `_,                                                                                                    |
-|                        | `pairwise `_                                                                                                                       |
-+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| Augmenting             | `count_cycle `_,                                                                                                                |
-|                        | `intersperse `_,                                                                                                                |
-|                        | `padded `_,                                                                                                                          |
-|                        | `mark_ends `_,                                                                                                                    |
-|                        | `repeat_last `_,                                                                                                                |
-|                        | `adjacent `_,                                                                                                                      |
-|                        | `groupby_transform `_,                                                                                                    |
-|                        | `padnone `_,                                                                                                                        |
-|                        | `ncycles `_                                                                                                                         |
-+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| Combining              | `collapse `_,                                                                                                                      |
-|                        | `sort_together `_,                                                                                                            |
-|                        | `interleave `_,                                                                                                                  |
-|                        | `interleave_longest `_,                                                                                                  |
-|                        | `zip_offset `_,                                                                                                                  |
-|                        | `zip_equal `_,                                                                                                                    |
-|                        | `dotproduct `_,                                                                                                                  |
-|                        | `convolve `_,                                                                                                                      |
-|                        | `flatten `_,                                                                                                                        |
-|                        | `roundrobin `_,                                                                                                                  |
-|                        | `prepend `_,                                                                                                                        |
-|                        | `value_chain `_                                                                                                                 |
-+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| Summarizing            | `ilen `_,                                                                                                                              |
-|                        | `unique_to_each `_,                                                                                                          |
-|                        | `sample `_,                                                                                                                          |
-|                        | `consecutive_groups `_,                                                                                                  |
-|                        | `run_length `_,                                                                                                                  |
-|                        | `map_reduce `_,                                                                                                                  |
-|                        | `exactly_n `_,                                                                                                                    |
-|                        | `is_sorted `_,                                                                                                                    |
-|                        | `all_equal `_,                                                                                                                    |
-|                        | `all_unique `_,                                                                                                                  |
-|                        | `first_true `_,                                                                                                                  |
-|                        | `quantify `_                                                                                                                       |
-+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| Selecting              | `islice_extended `_,                                                                                                        |
-|                        | `first `_,                                                                                                                            |
-|                        | `last `_,                                                                                                                              |
-|                        | `one `_,                                                                                                                                |
-|                        | `only `_,                                                                                                                              |
-|                        | `strip `_,                                                                                                                            |
-|                        | `lstrip `_,                                                                                                                          |
-|                        | `rstrip `_,                                                                                                                          |
-|                        | `filter_except `_                                                                                                             |
-|                        | `map_except `_                                                                                                                   |
-|                        | `nth_or_last `_,                                                                                                                |
-|                        | `nth `_,                                                                                                                                |
-|                        | `take `_,                                                                                                                              |
-|                        | `tail `_,                                                                                                                              |
-|                        | `unique_everseen `_,                                                                                                       |
-|                        | `unique_justseen `_                                                                                                         |
-+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| Combinatorics          | `distinct_permutations `_,                                                                                            |
-|                        | `distinct_combinations `_,                                                                                            |
-|                        | `circular_shifts `_,                                                                                                        |
-|                        | `partitions `_,                                                                                                                  |
-|                        | `set_partitions `_,                                                                                                          |
-|                        | `product_index `_,                                                                                                            |
-|                        | `combination_index `_,                                                                                                    |
-|                        | `permutation_index `_,                                                                                                    |
-|                        | `powerset `_,                                                                                                                      |
-|                        | `random_product `_,                                                                                                          |
-|                        | `random_permutation `_,                                                                                                  |
-|                        | `random_combination `_,                                                                                                  |
-|                        | `random_combination_with_replacement `_,                                                                |
-|                        | `nth_product `_                                                                                                                 |
-|                        | `nth_permutation `_                                                                                                         |
-|                        | `nth_combination `_                                                                                                         |
-+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| Wrapping               | `always_iterable `_,                                                                                                        |
-|                        | `always_reversible `_,                                                                                                    |
-|                        | `countable `_,                                                                                                                    |
-|                        | `consumer `_,                                                                                                                      |
-|                        | `with_iter `_,                                                                                                                    |
-|                        | `iter_except `_                                                                                                                 |
-+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| Others                 | `locate `_,                                                                                                                          |
-|                        | `rlocate `_,                                                                                                                        |
-|                        | `replace `_,                                                                                                                        |
-|                        | `numeric_range `_,                                                                                                            |
-|                        | `side_effect `_,                                                                                                                |
-|                        | `iterate `_,                                                                                                                        |
-|                        | `difference `_,                                                                                                                  |
-|                        | `make_decorator `_,                                                                                                          |
-|                        | `SequenceView `_,                                                                                                              |
-|                        | `time_limited `_,                                                                                                              |
-|                        | `consume `_,                                                                                                                        |
-|                        | `tabulate `_,                                                                                                                      |
-|                        | `repeatfunc `_                                                                                                                   |
-+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-
-
-Getting started
-===============
-
-To get started, install the library with `pip `_:
-
-.. code-block:: shell
-
-    pip install more-itertools
-
-The recipes from the `itertools docs `_
-are included in the top-level package:
-
-.. code-block:: python
-
-    >>> from more_itertools import flatten
-    >>> iterable = [(0, 1), (2, 3)]
-    >>> list(flatten(iterable))
-    [0, 1, 2, 3]
-
-Several new recipes are available as well:
-
-.. code-block:: python
-
-    >>> from more_itertools import chunked
-    >>> iterable = [0, 1, 2, 3, 4, 5, 6, 7, 8]
-    >>> list(chunked(iterable, 3))
-    [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
-
-    >>> from more_itertools import spy
-    >>> iterable = (x * x for x in range(1, 6))
-    >>> head, iterable = spy(iterable, n=3)
-    >>> list(head)
-    [1, 4, 9]
-    >>> list(iterable)
-    [1, 4, 9, 16, 25]
-
-
-
-For the full listing of functions, see the `API documentation `_.
-
-
-Links elsewhere
-===============
-
-Blog posts about ``more-itertools``:
-
-* `Yo, I heard you like decorators `__
-* `Tour of Python Itertools `__ (`Alternate `__)
-
-
-Development
-===========
-
-``more-itertools`` is maintained by `@erikrose `_
-and `@bbayles `_, with help from `many others `_.
-If you have a problem or suggestion, please file a bug or pull request in this
-repository. Thanks for contributing!
-
-
-Version History
-===============
-
-
-   :noindex:
-
-8.8.0
------
-
-* New functions
-    * countable (thanks to krzysieq)
-
-* Changes to existing functions
-    * split_before was updated to handle empy collections (thanks to TiunovNN)
-    * unique_everseen got a performance boost (thanks to Numerlor)
-    * The type hint for value_chain was corrected (thanks to vr2262)
-
-8.7.0
------
-
-* New functions
-    * convolve (from the Python itertools docs)
-    * product_index, combination_index, and permutation_index (thanks to N8Brooks)
-    * value_chain (thanks to jenstroeger)
-
-* Changes to existing functions
-    * distinct_combinations now uses a non-recursive algorithm (thanks to  knutdrand)
-    * pad_none is now the preferred name for padnone, though the latter remains available.
-    * pairwise will now use the Python standard library implementation on Python 3.10+
-    * sort_together now accepts a ``key`` argument (thanks to brianmaissy)
-    * seekable now has a ``peek`` method, and can indicate whether the iterator it's wrapping is exhausted (thanks to gsakkis)
-    * time_limited can now indicate whether its iterator has expired (thanks to roysmith)
-    * The implementation of unique_everseen was improved (thanks to plammens)
-
-* Other changes:
-    * Various documentation updates (thanks to cthoyt, Evantm, and cyphase)
-
-8.6.0
------
-
-* New itertools
-    * all_unique (thanks to brianmaissy)
-    * nth_product and nth_permutation (thanks to N8Brooks)
-
-* Changes to existing itertools
-    * chunked and sliced now accept a ``strict`` parameter (thanks to shlomif and jtwool)
-
-* Other changes
-    * Python 3.5 has reached its end of life and is no longer supported.
-    * Python 3.9 is officially supported.
-    * Various documentation fixes (thanks to timgates42)
-
-8.5.0
------
-
-* New itertools
-    * windowed_complete (thanks to MarcinKonowalczyk)
-
-* Changes to existing itertools:
-    * The is_sorted implementation was improved (thanks to cool-RR)
-    * The groupby_transform now accepts a ``reducefunc`` parameter.
-    * The last implementation was improved (thanks to brianmaissy)
-
-* Other changes
-    * Various documentation fixes (thanks to craigrosie, samuelstjean, PiCT0)
-    * The tests for distinct_combinations were improved (thanks to Minabsapi)
-    * Automated tests now run on GitHub Actions. All commits now check:
-        * That unit tests pass
-        * That the examples in docstrings work
-        * That test coverage remains high (using `coverage`)
-        * For linting errors (using `flake8`)
-        * For consistent style (using `black`)
-        * That the type stubs work (using `mypy`)
-        * That the docs build correctly (using `sphinx`)
-        * That packages build correctly (using `twine`)
-
-8.4.0
------
-
-* New itertools
-    * mark_ends (thanks to kalekundert)
-    * is_sorted
-
-* Changes to existing itertools:
-    * islice_extended can now be used with real slices (thanks to cool-RR)
-    * The implementations for filter_except and map_except were improved (thanks to SergBobrovsky)
-
-* Other changes
-    * Automated tests now enforce code style (using `black `__)
-    * The various signatures of islice_extended and numeric_range now appear in the docs (thanks to dsfulf)
-    * The test configuration for mypy was updated (thanks to blueyed)
-
-
-8.3.0
------
-
-* New itertools
-    * zip_equal (thanks to frankier and alexmojaki)
-
-* Changes to existing itertools:
-    * split_at, split_before, split_after, and split_when all got a ``maxsplit`` paramter (thanks to jferard and ilai-deutel)
-    * split_at now accepts a ``keep_separator`` parameter (thanks to jferard)
-    * distinct_permutations can now generate ``r``-length permutations (thanks to SergBobrovsky and ilai-deutel)
-    * The windowed implementation was improved  (thanks to SergBobrovsky)
-    * The spy implementation was improved (thanks to has2k1)
-
-* Other changes
-    * Type stubs are now tested with ``stubtest`` (thanks to ilai-deutel)
-    * Tests now run with ``python -m unittest`` instead of ``python setup.py test`` (thanks to jdufresne)
-
-8.2.0
------
-
-* Bug fixes
-    * The .pyi files for typing were updated. (thanks to blueyed and ilai-deutel)
-
-* Changes to existing itertools:
-    * numeric_range now behaves more like the built-in range. (thanks to jferard)
-    * bucket now allows for enumerating keys. (thanks to alexchandel)
-    * sliced now should now work for numpy arrays. (thanks to sswingle)
-    * seekable now has a ``maxlen`` parameter.
-
-8.1.0
------
-
-* Bug fixes
-    * partition works with ``pred=None`` again. (thanks to MSeifert04)
-
-* New itertools
-    * sample (thanks to tommyod)
-    * nth_or_last (thanks to d-ryzhikov)
-
-* Changes to existing itertools:
-    * The implementation for divide was improved. (thanks to jferard)
-
-8.0.2
------
-
-* Bug fixes
-    * The type stub files are now part of the wheel distribution (thanks to keisheiled)
-
-8.0.1
------
-
-* Bug fixes
-    * The type stub files now work for functions imported from the
-      root package (thanks to keisheiled)
-
-8.0.0
------
-
-* New itertools and other additions
-    * This library now ships type hints for use with mypy.
-      (thanks to ilai-deutel for the implementation, and to gabbard and fmagin for assistance)
-    * split_when (thanks to jferard)
-    * repeat_last (thanks to d-ryzhikov)
-
-* Changes to existing itertools:
-    * The implementation for set_partitions was improved. (thanks to jferard)
-    * partition was optimized for expensive predicates. (thanks to stevecj)
-    * unique_everseen and groupby_transform were re-factored. (thanks to SergBobrovsky)
-    * The implementation for difference was improved. (thanks to Jabbey92)
-
-* Other changes
-    * Python 3.4 has reached its end of life and is no longer supported.
-    * Python 3.8 is officially supported. (thanks to jdufresne)
-    * The ``collate`` function has been deprecated.
-      It raises a ``DeprecationWarning`` if used, and will be removed in a future release.
-    * one and only now provide more informative error messages. (thanks to gabbard)
-    * Unit tests were moved outside of the main package (thanks to jdufresne)
-    * Various documentation fixes (thanks to kriomant, gabbard, jdufresne)
-
-
-7.2.0
------
-
-* New itertools
-    * distinct_combinations
-    * set_partitions (thanks to kbarrett)
-    * filter_except
-    * map_except
-
-7.1.0
------
-
-* New itertools
-    * ichunked (thanks davebelais and youtux)
-    * only (thanks jaraco)
-
-* Changes to existing itertools:
-    * numeric_range now supports ranges specified by
-      ``datetime.datetime`` and ``datetime.timedelta`` objects (thanks to MSeifert04 for tests).
-    * difference now supports an *initial* keyword argument.
-
-
-* Other changes
-    * Various documentation fixes (thanks raimon49, pylang)
-
-7.0.0
------
-
-* New itertools:
-    * time_limited
-    * partitions (thanks to rominf and Saluev)
-    * substrings_indexes (thanks to rominf)
-
-* Changes to existing itertools:
-    * collapse now treats ``bytes`` objects the same as ``str`` objects. (thanks to Sweenpet)
-
-The major version update is due to the change in the default behavior of
-collapse. It now treats ``bytes`` objects the same as ``str`` objects.
-This aligns its behavior with always_iterable.
-
-.. code-block:: python
-
-    >>> from more_itertools import collapse
-    >>> iterable = [[1, 2], b'345', [6]]
-    >>> print(list(collapse(iterable)))
-    [1, 2, b'345', 6]
-
-6.0.0
------
-
-* Major changes:
-    * Python 2.7 is no longer supported. The 5.0.0 release will be the last
-      version targeting Python 2.7.
-    * All future releases will target the active versions of Python 3.
-      As of 2019, those are Python 3.4 and above.
-    * The ``six`` library is no longer a dependency.
-    * The accumulate function is no longer part of this library. You
-      may import a better version from the standard ``itertools`` module.
-
-* Changes to existing itertools:
-    * The order of the parameters in grouper have changed to match
-      the latest recipe in the itertools documentation. Use of the old order
-      will be supported in this release, but emit a  ``DeprecationWarning``.
-      The legacy behavior will be dropped in a future release. (thanks to jaraco)
-    * distinct_permutations was improved (thanks to jferard - see also `permutations with unique values `_ at StackOverflow.)
-    * An unused parameter was removed from substrings. (thanks to pylang)
-
-* Other changes:
-    * The docs for unique_everseen were improved. (thanks to jferard and MSeifert04)
-    * Several Python 2-isms were removed. (thanks to jaraco, MSeifert04, and hugovk)
-
-
diff --git a/setuptools/_vendor/more_itertools-8.8.0.dist-info/RECORD b/setuptools/_vendor/more_itertools-8.8.0.dist-info/RECORD
deleted file mode 100644
index c3cbb83382..0000000000
--- a/setuptools/_vendor/more_itertools-8.8.0.dist-info/RECORD
+++ /dev/null
@@ -1,17 +0,0 @@
-more_itertools-8.8.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-more_itertools-8.8.0.dist-info/LICENSE,sha256=CfHIyelBrz5YTVlkHqm4fYPAyw_QB-te85Gn4mQ8GkY,1053
-more_itertools-8.8.0.dist-info/METADATA,sha256=Gke9w7RnfiAvveik_iBBrzd0RjrDhsQ8uRYNBJdo4qQ,40482
-more_itertools-8.8.0.dist-info/RECORD,,
-more_itertools-8.8.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-more_itertools-8.8.0.dist-info/WHEEL,sha256=OqRkF0eY5GHssMorFjlbTIq072vpHpF60fIQA6lS9xA,92
-more_itertools-8.8.0.dist-info/top_level.txt,sha256=fAuqRXu9LPhxdB9ujJowcFOu1rZ8wzSpOW9_jlKis6M,15
-more_itertools/__init__.py,sha256=C7sXffHTXM3P-iaLPPfqfmDoxOflQMJLcM7ed9p3jak,82
-more_itertools/__init__.pyi,sha256=5B3eTzON1BBuOLob1vCflyEb2lSd6usXQQ-Cv-hXkeA,43
-more_itertools/__pycache__/__init__.cpython-311.pyc,,
-more_itertools/__pycache__/more.cpython-311.pyc,,
-more_itertools/__pycache__/recipes.cpython-311.pyc,,
-more_itertools/more.py,sha256=DlZa8v6JihVwfQ5zHidOA-xDE0orcQIUyxVnCaUoDKE,117968
-more_itertools/more.pyi,sha256=r32pH2raBC1zih3evK4fyvAXvrUamJqc6dgV7QCRL_M,14977
-more_itertools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-more_itertools/recipes.py,sha256=UkNkrsZyqiwgLHANBTmvMhCvaNSvSNYhyOpz_Jc55DY,16256
-more_itertools/recipes.pyi,sha256=9BpeKd5_qalYVSnuHfqPSCfoGgqnQY2Xu9pNwrDlHU8,3551
diff --git a/setuptools/_vendor/more_itertools-8.8.0.dist-info/WHEEL b/setuptools/_vendor/more_itertools-8.8.0.dist-info/WHEEL
deleted file mode 100644
index 385faab052..0000000000
--- a/setuptools/_vendor/more_itertools-8.8.0.dist-info/WHEEL
+++ /dev/null
@@ -1,5 +0,0 @@
-Wheel-Version: 1.0
-Generator: bdist_wheel (0.36.2)
-Root-Is-Purelib: true
-Tag: py3-none-any
-
diff --git a/setuptools/_vendor/more_itertools-8.8.0.dist-info/top_level.txt b/setuptools/_vendor/more_itertools-8.8.0.dist-info/top_level.txt
deleted file mode 100644
index a5035befb3..0000000000
--- a/setuptools/_vendor/more_itertools-8.8.0.dist-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-more_itertools
diff --git a/setuptools/_vendor/more_itertools/__init__.py b/setuptools/_vendor/more_itertools/__init__.py
index 19a169fc30..24216c5c1f 100644
--- a/setuptools/_vendor/more_itertools/__init__.py
+++ b/setuptools/_vendor/more_itertools/__init__.py
@@ -1,4 +1,6 @@
+"""More routines for operating on iterables, beyond itertools"""
+
 from .more import *  # noqa
 from .recipes import *  # noqa
 
-__version__ = '8.8.0'
+__version__ = '10.8.0'
diff --git a/setuptools/_vendor/more_itertools/more.py b/setuptools/_vendor/more_itertools/more.py
old mode 100644
new mode 100755
index e6fca4d47f..bf501956ae
--- a/setuptools/_vendor/more_itertools/more.py
+++ b/setuptools/_vendor/more_itertools/more.py
@@ -1,88 +1,145 @@
+import math
 import warnings
 
 from collections import Counter, defaultdict, deque, abc
 from collections.abc import Sequence
-from functools import partial, reduce, wraps
-from heapq import merge, heapify, heapreplace, heappop
+from contextlib import suppress
+from functools import cached_property, partial, reduce, wraps
+from heapq import heapify, heapreplace
 from itertools import (
     chain,
+    combinations,
     compress,
     count,
     cycle,
     dropwhile,
     groupby,
     islice,
+    permutations,
     repeat,
     starmap,
     takewhile,
     tee,
     zip_longest,
+    product,
 )
-from math import exp, factorial, floor, log
+from math import comb, e, exp, factorial, floor, fsum, log, log1p, perm, tau
+from math import ceil
 from queue import Empty, Queue
-from random import random, randrange, uniform
-from operator import itemgetter, mul, sub, gt, lt
+from random import random, randrange, shuffle, uniform
+from operator import (
+    attrgetter,
+    is_not,
+    itemgetter,
+    lt,
+    mul,
+    neg,
+    sub,
+    gt,
+)
 from sys import hexversion, maxsize
 from time import monotonic
 
 from .recipes import (
+    _marker,
+    _zip_equal,
+    UnequalIterablesError,
     consume,
+    first_true,
     flatten,
-    pairwise,
+    is_prime,
+    nth,
     powerset,
+    sieve,
     take,
     unique_everseen,
+    all_equal,
+    batched,
 )
 
 __all__ = [
     'AbortThread',
+    'SequenceView',
+    'UnequalIterablesError',
     'adjacent',
+    'all_unique',
     'always_iterable',
     'always_reversible',
+    'argmax',
+    'argmin',
     'bucket',
     'callback_iter',
     'chunked',
+    'chunked_even',
     'circular_shifts',
     'collapse',
-    'collate',
+    'combination_index',
+    'combination_with_replacement_index',
     'consecutive_groups',
+    'constrained_batches',
     'consumer',
-    'countable',
     'count_cycle',
-    'mark_ends',
+    'countable',
+    'derangements',
+    'dft',
     'difference',
     'distinct_combinations',
     'distinct_permutations',
     'distribute',
     'divide',
+    'doublestarmap',
+    'duplicates_everseen',
+    'duplicates_justseen',
+    'classify_unique',
     'exactly_n',
+    'extract',
     'filter_except',
+    'filter_map',
     'first',
+    'gray_product',
     'groupby_transform',
+    'ichunked',
+    'iequals',
+    'idft',
     'ilen',
-    'interleave_longest',
     'interleave',
+    'interleave_evenly',
+    'interleave_longest',
+    'interleave_randomly',
     'intersperse',
+    'is_sorted',
     'islice_extended',
     'iterate',
-    'ichunked',
-    'is_sorted',
+    'iter_suppress',
+    'join_mappings',
     'last',
     'locate',
+    'longest_common_prefix',
     'lstrip',
     'make_decorator',
     'map_except',
+    'map_if',
     'map_reduce',
+    'mark_ends',
+    'minmax',
     'nth_or_last',
     'nth_permutation',
+    'nth_prime',
     'nth_product',
+    'nth_combination_with_replacement',
     'numeric_range',
     'one',
     'only',
+    'outer_product',
     'padded',
+    'partial_product',
     'partitions',
-    'set_partitions',
     'peekable',
+    'permutation_index',
+    'powerset_of_sets',
+    'product_index',
+    'raise_',
+    'repeat_each',
     'repeat_last',
     'replace',
     'rlocate',
@@ -90,37 +147,64 @@
     'run_length',
     'sample',
     'seekable',
-    'SequenceView',
+    'set_partitions',
     'side_effect',
     'sliced',
     'sort_together',
-    'split_at',
     'split_after',
+    'split_at',
     'split_before',
-    'split_when',
     'split_into',
+    'split_when',
     'spy',
     'stagger',
     'strip',
+    'strictly_n',
     'substrings',
     'substrings_indexes',
+    'takewhile_inclusive',
     'time_limited',
+    'unique_in_window',
     'unique_to_each',
     'unzip',
+    'value_chain',
     'windowed',
+    'windowed_complete',
     'with_iter',
-    'UnequalIterablesError',
+    'zip_broadcast',
     'zip_equal',
     'zip_offset',
-    'windowed_complete',
-    'all_unique',
-    'value_chain',
-    'product_index',
-    'combination_index',
-    'permutation_index',
 ]
 
-_marker = object()
+# math.sumprod is available for Python 3.12+
+try:
+    from math import sumprod as _fsumprod
+
+except ImportError:  # pragma: no cover
+    # Extended precision algorithms from T. J. Dekker,
+    # "A Floating-Point Technique for Extending the Available Precision"
+    # https://csclub.uwaterloo.ca/~pbarfuss/dekker1971.pdf
+    # Formulas: (5.5) (5.6) and (5.8).  Code: mul12()
+
+    def dl_split(x: float):
+        "Split a float into two half-precision components."
+        t = x * 134217729.0  # Veltkamp constant = 2.0 ** 27 + 1
+        hi = t - (t - x)
+        lo = x - hi
+        return hi, lo
+
+    def dl_mul(x, y):
+        "Lossless multiplication."
+        xx_hi, xx_lo = dl_split(x)
+        yy_hi, yy_lo = dl_split(y)
+        p = xx_hi * yy_hi
+        q = xx_hi * yy_lo + xx_lo * yy_hi
+        z = p + q
+        zz = p - z + q + xx_lo * yy_lo
+        return z, zz
+
+    def _fsumprod(p, q):
+        return fsum(chain.from_iterable(map(dl_mul, p, q)))
 
 
 def chunked(iterable, n, strict=False):
@@ -144,6 +228,8 @@ def chunked(iterable, n, strict=False):
     """
     iterator = iter(partial(take, n, iter(iterable)), [])
     if strict:
+        if n is None:
+            raise ValueError('n must not be None when using strict mode.')
 
         def ret():
             for chunk in iterator:
@@ -151,7 +237,7 @@ def ret():
                     raise ValueError('iterable is not divisible by n.')
                 yield chunk
 
-        return iter(ret())
+        return ret()
     else:
         return iterator
 
@@ -173,15 +259,14 @@ def first(iterable, default=_marker):
     ``next(iter(iterable), default)``.
 
     """
-    try:
-        return next(iter(iterable))
-    except StopIteration as e:
-        if default is _marker:
-            raise ValueError(
-                'first() was called on an empty iterable, and no '
-                'default value was provided.'
-            ) from e
-        return default
+    for item in iterable:
+        return item
+    if default is _marker:
+        raise ValueError(
+            'first() was called on an empty iterable, '
+            'and no default value was provided.'
+        )
+    return default
 
 
 def last(iterable, default=_marker):
@@ -200,15 +285,14 @@ def last(iterable, default=_marker):
         if isinstance(iterable, Sequence):
             return iterable[-1]
         # Work around https://bugs.python.org/issue38525
-        elif hasattr(iterable, '__reversed__') and (hexversion != 0x030800F0):
+        if getattr(iterable, '__reversed__', None):
             return next(reversed(iterable))
-        else:
-            return deque(iterable, maxlen=1)[-1]
+        return deque(iterable, maxlen=1)[-1]
     except (IndexError, TypeError, StopIteration):
         if default is _marker:
             raise ValueError(
-                'last() was called on an empty iterable, and no default was '
-                'provided.'
+                'last() was called on an empty iterable, '
+                'and no default value was provided.'
             )
         return default
 
@@ -395,44 +479,6 @@ def __getitem__(self, index):
         return self._cache[index]
 
 
-def collate(*iterables, **kwargs):
-    """Return a sorted merge of the items from each of several already-sorted
-    *iterables*.
-
-        >>> list(collate('ACDZ', 'AZ', 'JKL'))
-        ['A', 'A', 'C', 'D', 'J', 'K', 'L', 'Z', 'Z']
-
-    Works lazily, keeping only the next value from each iterable in memory. Use
-    :func:`collate` to, for example, perform a n-way mergesort of items that
-    don't fit in memory.
-
-    If a *key* function is specified, the iterables will be sorted according
-    to its result:
-
-        >>> key = lambda s: int(s)  # Sort by numeric value, not by string
-        >>> list(collate(['1', '10'], ['2', '11'], key=key))
-        ['1', '2', '10', '11']
-
-
-    If the *iterables* are sorted in descending order, set *reverse* to
-    ``True``:
-
-        >>> list(collate([5, 3, 1], [4, 2, 0], reverse=True))
-        [5, 4, 3, 2, 1, 0]
-
-    If the elements of the passed-in iterables are out of order, you might get
-    unexpected results.
-
-    On Python 3.5+, this function is an alias for :func:`heapq.merge`.
-
-    """
-    warnings.warn(
-        "collate is no longer part of more_itertools, use heapq.merge",
-        DeprecationWarning,
-    )
-    return merge(*iterables, **kwargs)
-
-
 def consumer(func):
     """Decorator that automatically advances a PEP-342-style "reverse iterator"
     to its first yield point so you don't have to call ``next()`` on it
@@ -468,31 +514,46 @@ def wrapper(*args, **kwargs):
 def ilen(iterable):
     """Return the number of items in *iterable*.
 
-        >>> ilen(x for x in range(1000000) if x % 3 == 0)
-        333334
+    For example, there are 168 prime numbers below 1,000:
+
+        >>> ilen(sieve(1000))
+        168
 
-    This consumes the iterable, so handle with care.
+    Equivalent to, but faster than::
+
+        def ilen(iterable):
+            count = 0
+            for _ in iterable:
+                count += 1
+            return count
+
+    This fully consumes the iterable, so handle with care.
 
     """
-    # This approach was selected because benchmarks showed it's likely the
-    # fastest of the known implementations at the time of writing.
-    # See GitHub tracker: #236, #230.
-    counter = count()
-    deque(zip(iterable, counter), maxlen=0)
-    return next(counter)
+    # This is the "most beautiful of the fast variants" of this function.
+    # If you think you can improve on it, please ensure that your version
+    # is both 10x faster and 10x more beautiful.
+    return sum(compress(repeat(1), zip(iterable)))
 
 
 def iterate(func, start):
     """Return ``start``, ``func(start)``, ``func(func(start))``, ...
 
-    >>> from itertools import islice
-    >>> list(islice(iterate(lambda x: 2*x, 1), 10))
+    Produces an infinite iterator. To add a stopping condition,
+    use :func:`take`, ``takewhile``, or :func:`takewhile_inclusive`:.
+
+    >>> take(10, iterate(lambda x: 2*x, 1))
     [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
 
+    >>> collatz = lambda x: 3*x + 1 if x%2==1 else x // 2
+    >>> list(takewhile_inclusive(lambda x: x!=1, iterate(collatz, 10)))
+    [10, 5, 16, 8, 4, 2, 1]
+
     """
-    while True:
-        yield start
-        start = func(start)
+    with suppress(StopIteration):
+        while True:
+            yield start
+            start = func(start)
 
 
 def with_iter(context_manager):
@@ -526,7 +587,7 @@ def one(iterable, too_short=None, too_long=None):
         >>> one(it)  # doctest: +IGNORE_EXCEPTION_DETAIL
         Traceback (most recent call last):
         ...
-        ValueError: too many items in iterable (expected 1)'
+        ValueError: too few items in iterable (expected 1)'
         >>> too_short = IndexError('too few items')
         >>> one(it, too_short=too_short)  # doctest: +IGNORE_EXCEPTION_DETAIL
         Traceback (most recent call last):
@@ -554,27 +615,95 @@ def one(iterable, too_short=None, too_long=None):
     contents less destructively.
 
     """
-    it = iter(iterable)
+    iterator = iter(iterable)
+    for first in iterator:
+        for second in iterator:
+            msg = (
+                f'Expected exactly one item in iterable, but got {first!r}, '
+                f'{second!r}, and perhaps more.'
+            )
+            raise too_long or ValueError(msg)
+        return first
+    raise too_short or ValueError('too few items in iterable (expected 1)')
 
-    try:
-        first_value = next(it)
-    except StopIteration as e:
-        raise (
-            too_short or ValueError('too few items in iterable (expected 1)')
-        ) from e
 
-    try:
-        second_value = next(it)
-    except StopIteration:
-        pass
-    else:
-        msg = (
-            'Expected exactly one item in iterable, but got {!r}, {!r}, '
-            'and perhaps more.'.format(first_value, second_value)
+def raise_(exception, *args):
+    raise exception(*args)
+
+
+def strictly_n(iterable, n, too_short=None, too_long=None):
+    """Validate that *iterable* has exactly *n* items and return them if
+    it does. If it has fewer than *n* items, call function *too_short*
+    with the actual number of items. If it has more than *n* items, call function
+    *too_long* with the number ``n + 1``.
+
+        >>> iterable = ['a', 'b', 'c', 'd']
+        >>> n = 4
+        >>> list(strictly_n(iterable, n))
+        ['a', 'b', 'c', 'd']
+
+    Note that the returned iterable must be consumed in order for the check to
+    be made.
+
+    By default, *too_short* and *too_long* are functions that raise
+    ``ValueError``.
+
+        >>> list(strictly_n('ab', 3))  # doctest: +IGNORE_EXCEPTION_DETAIL
+        Traceback (most recent call last):
+        ...
+        ValueError: too few items in iterable (got 2)
+
+        >>> list(strictly_n('abc', 2))  # doctest: +IGNORE_EXCEPTION_DETAIL
+        Traceback (most recent call last):
+        ...
+        ValueError: too many items in iterable (got at least 3)
+
+    You can instead supply functions that do something else.
+    *too_short* will be called with the number of items in *iterable*.
+    *too_long* will be called with `n + 1`.
+
+        >>> def too_short(item_count):
+        ...     raise RuntimeError
+        >>> it = strictly_n('abcd', 6, too_short=too_short)
+        >>> list(it)  # doctest: +IGNORE_EXCEPTION_DETAIL
+        Traceback (most recent call last):
+        ...
+        RuntimeError
+
+        >>> def too_long(item_count):
+        ...     print('The boss is going to hear about this')
+        >>> it = strictly_n('abcdef', 4, too_long=too_long)
+        >>> list(it)
+        The boss is going to hear about this
+        ['a', 'b', 'c', 'd']
+
+    """
+    if too_short is None:
+        too_short = lambda item_count: raise_(
+            ValueError,
+            f'Too few items in iterable (got {item_count})',
+        )
+
+    if too_long is None:
+        too_long = lambda item_count: raise_(
+            ValueError,
+            f'Too many items in iterable (got at least {item_count})',
         )
-        raise too_long or ValueError(msg)
 
-    return first_value
+    it = iter(iterable)
+
+    sent = 0
+    for item in islice(it, n):
+        yield item
+        sent += 1
+
+    if sent < n:
+        too_short(sent)
+        return
+
+    for item in it:
+        too_long(n + 1)
+        return
 
 
 def distinct_permutations(iterable, r=None):
@@ -583,15 +712,15 @@ def distinct_permutations(iterable, r=None):
         >>> sorted(distinct_permutations([1, 0, 1]))
         [(0, 1, 1), (1, 0, 1), (1, 1, 0)]
 
-    Equivalent to ``set(permutations(iterable))``, except duplicates are not
-    generated and thrown away. For larger input sequences this is much more
-    efficient.
+    Equivalent to yielding from ``set(permutations(iterable))``, except
+    duplicates are not generated and thrown away. For larger input sequences
+    this is much more efficient.
 
     Duplicate permutations arise when there are duplicated elements in the
     input iterable. The number of items returned is
     `n! / (x_1! * x_2! * ... * x_n!)`, where `n` is the total number of
     items input, and each `x_i` is the count of a distinct item in the input
-    sequence.
+    sequence. The function :func:`multinomial` computes this directly.
 
     If *r* is given, only the *r*-length permutations are yielded.
 
@@ -600,7 +729,27 @@ def distinct_permutations(iterable, r=None):
         >>> sorted(distinct_permutations(range(3), r=2))
         [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
 
+    *iterable* need not be sortable, but note that using equal (``x == y``)
+    but non-identical (``id(x) != id(y)``) elements may produce surprising
+    behavior. For example, ``1`` and ``True`` are equal but non-identical:
+
+        >>> list(distinct_permutations([1, True, '3']))  # doctest: +SKIP
+        [
+            (1, True, '3'),
+            (1, '3', True),
+            ('3', 1, True)
+        ]
+        >>> list(distinct_permutations([1, 2, '3']))  # doctest: +SKIP
+        [
+            (1, 2, '3'),
+            (1, '3', 2),
+            (2, 1, '3'),
+            (2, '3', 1),
+            ('3', 1, 2),
+            ('3', 2, 1)
+        ]
     """
+
     # Algorithm: https://w.wiki/Qai
     def _full(A):
         while True:
@@ -665,18 +814,110 @@ def _partial(A, r):
             i += 1
             head[i:], tail[:] = tail[: r - i], tail[r - i :]
 
-    items = sorted(iterable)
+    items = list(iterable)
+
+    try:
+        items.sort()
+        sortable = True
+    except TypeError:
+        sortable = False
+
+        indices_dict = defaultdict(list)
+
+        for item in items:
+            indices_dict[items.index(item)].append(item)
+
+        indices = [items.index(item) for item in items]
+        indices.sort()
+
+        equivalent_items = {k: cycle(v) for k, v in indices_dict.items()}
+
+        def permuted_items(permuted_indices):
+            return tuple(
+                next(equivalent_items[index]) for index in permuted_indices
+            )
 
     size = len(items)
     if r is None:
         r = size
 
+    # functools.partial(_partial, ... )
+    algorithm = _full if (r == size) else partial(_partial, r=r)
+
     if 0 < r <= size:
-        return _full(items) if (r == size) else _partial(items, r)
+        if sortable:
+            return algorithm(items)
+        else:
+            return (
+                permuted_items(permuted_indices)
+                for permuted_indices in algorithm(indices)
+            )
 
     return iter(() if r else ((),))
 
 
+def derangements(iterable, r=None):
+    """Yield successive derangements of the elements in *iterable*.
+
+    A derangement is a permutation in which no element appears at its original
+    index. In other words, a derangement is a permutation that has no fixed points.
+
+    Suppose Alice, Bob, Carol, and Dave are playing Secret Santa.
+    The code below outputs all of the different ways to assign gift recipients
+    such that nobody is assigned to himself or herself:
+
+        >>> for d in derangements(['Alice', 'Bob', 'Carol', 'Dave']):
+        ...    print(', '.join(d))
+        Bob, Alice, Dave, Carol
+        Bob, Carol, Dave, Alice
+        Bob, Dave, Alice, Carol
+        Carol, Alice, Dave, Bob
+        Carol, Dave, Alice, Bob
+        Carol, Dave, Bob, Alice
+        Dave, Alice, Bob, Carol
+        Dave, Carol, Alice, Bob
+        Dave, Carol, Bob, Alice
+
+    If *r* is given, only the *r*-length derangements are yielded.
+
+        >>> sorted(derangements(range(3), 2))
+        [(1, 0), (1, 2), (2, 0)]
+        >>> sorted(derangements([0, 2, 3], 2))
+        [(2, 0), (2, 3), (3, 0)]
+
+    Elements are treated as unique based on their position, not on their value.
+
+    Consider the Secret Santa example with two *different* people who have
+    the *same* name. Then there are two valid gift assignments even though
+    it might appear that a person is assigned to themselves:
+
+        >>> names = ['Alice', 'Bob', 'Bob']
+        >>> list(derangements(names))
+        [('Bob', 'Bob', 'Alice'), ('Bob', 'Alice', 'Bob')]
+
+    To avoid confusion, make the inputs distinct:
+
+        >>> deduped = [f'{name}{index}' for index, name in enumerate(names)]
+        >>> list(derangements(deduped))
+        [('Bob1', 'Bob2', 'Alice0'), ('Bob2', 'Alice0', 'Bob1')]
+
+    The number of derangements of a set of size *n* is known as the
+    "subfactorial of n".  For n > 0, the subfactorial is:
+    ``round(math.factorial(n) / math.e)``.
+
+    References:
+
+    * Article:  https://www.numberanalytics.com/blog/ultimate-guide-to-derangements-in-combinatorics
+    * Sizes:    https://oeis.org/A000166
+    """
+    xs = tuple(iterable)
+    ys = tuple(range(len(xs)))
+    return compress(
+        permutations(xs, r=r),
+        map(all, map(map, repeat(is_not), repeat(ys), permutations(ys, r=r))),
+    )
+
+
 def intersperse(e, iterable, n=1):
     """Intersperse filler element *e* among the items in *iterable*, leaving
     *n* items between each filler element.
@@ -691,8 +932,8 @@ def intersperse(e, iterable, n=1):
     if n == 0:
         raise ValueError('n must be > 0')
     elif n == 1:
-        # interleave(repeat(e), iterable) -> e, x_0, e, e, x_1, e, x_2...
-        # islice(..., 1, None) -> x_0, e, e, x_1, e, x_2...
+        # interleave(repeat(e), iterable) -> e, x_0, e, x_1, e, x_2...
+        # islice(..., 1, None) -> x_0, e, x_1, e, x_2...
         return islice(interleave(repeat(e), iterable), 1, None)
     else:
         # interleave(filler, chunks) -> [e], [x_0, x_1], [e], [x_2, x_3]...
@@ -766,24 +1007,31 @@ def windowed(seq, n, fillvalue=None, step=1):
     if n < 0:
         raise ValueError('n must be >= 0')
     if n == 0:
-        yield tuple()
+        yield ()
         return
     if step < 1:
         raise ValueError('step must be >= 1')
 
-    window = deque(maxlen=n)
-    i = n
-    for _ in map(window.append, seq):
-        i -= 1
-        if not i:
-            i = step
-            yield tuple(window)
-
-    size = len(window)
-    if size < n:
-        yield tuple(chain(window, repeat(fillvalue, n - size)))
-    elif 0 < i < min(step, n):
-        window += (fillvalue,) * i
+    iterator = iter(seq)
+
+    # Generate first window
+    window = deque(islice(iterator, n), maxlen=n)
+
+    # Deal with the first window not being full
+    if not window:
+        return
+    if len(window) < n:
+        yield tuple(window) + ((fillvalue,) * (n - len(window)))
+        return
+    yield tuple(window)
+
+    # Create the filler for the next windows. The padding ensures
+    # we have just enough elements to fill the last window.
+    padding = (fillvalue,) * (n - 1 if step >= n else step - 1)
+    filler = map(window.append, chain(iterator, padding))
+
+    # Generate the rest of the windows
+    for _ in islice(filler, step - 1, None, step):
         yield tuple(window)
 
 
@@ -801,7 +1049,7 @@ def substrings(iterable):
     """
     # The length-1 substrings
     seq = []
-    for item in iter(iterable):
+    for item in iterable:
         seq.append(item)
         yield (item,)
     seq = tuple(seq)
@@ -848,7 +1096,7 @@ def substrings_indexes(seq, reverse=False):
 
 
 class bucket:
-    """Wrap *iterable* and return an object that buckets it iterable into
+    """Wrap *iterable* and return an object that buckets the iterable into
     child iterables based on a *key* function.
 
         >>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3']
@@ -934,7 +1182,7 @@ def __iter__(self):
             if self._validator(item_value):
                 self._cache[item_value].append(item)
 
-        yield from self._cache.keys()
+        return iter(self._cache)
 
     def __getitem__(self, value):
         if not self._validator(value):
@@ -980,10 +1228,8 @@ def spy(iterable, n=1):
         [1, 2, 3, 4, 5]
 
     """
-    it = iter(iterable)
-    head = take(n, it)
-
-    return head.copy(), chain(head, it)
+    p, q = tee(iterable)
+    return take(n, q), p
 
 
 def interleave(*iterables):
@@ -1012,8 +1258,99 @@ def interleave_longest(*iterables):
     is large).
 
     """
-    i = chain.from_iterable(zip_longest(*iterables, fillvalue=_marker))
-    return (x for x in i if x is not _marker)
+    for xs in zip_longest(*iterables, fillvalue=_marker):
+        for x in xs:
+            if x is not _marker:
+                yield x
+
+
+def interleave_evenly(iterables, lengths=None):
+    """
+    Interleave multiple iterables so that their elements are evenly distributed
+    throughout the output sequence.
+
+    >>> iterables = [1, 2, 3, 4, 5], ['a', 'b']
+    >>> list(interleave_evenly(iterables))
+    [1, 2, 'a', 3, 4, 'b', 5]
+
+    >>> iterables = [[1, 2, 3], [4, 5], [6, 7, 8]]
+    >>> list(interleave_evenly(iterables))
+    [1, 6, 4, 2, 7, 3, 8, 5]
+
+    This function requires iterables of known length. Iterables without
+    ``__len__()`` can be used by manually specifying lengths with *lengths*:
+
+    >>> from itertools import combinations, repeat
+    >>> iterables = [combinations(range(4), 2), ['a', 'b', 'c']]
+    >>> lengths = [4 * (4 - 1) // 2, 3]
+    >>> list(interleave_evenly(iterables, lengths=lengths))
+    [(0, 1), (0, 2), 'a', (0, 3), (1, 2), 'b', (1, 3), (2, 3), 'c']
+
+    Based on Bresenham's algorithm.
+    """
+    if lengths is None:
+        try:
+            lengths = [len(it) for it in iterables]
+        except TypeError:
+            raise ValueError(
+                'Iterable lengths could not be determined automatically. '
+                'Specify them with the lengths keyword.'
+            )
+    elif len(iterables) != len(lengths):
+        raise ValueError('Mismatching number of iterables and lengths.')
+
+    dims = len(lengths)
+
+    # sort iterables by length, descending
+    lengths_permute = sorted(
+        range(dims), key=lambda i: lengths[i], reverse=True
+    )
+    lengths_desc = [lengths[i] for i in lengths_permute]
+    iters_desc = [iter(iterables[i]) for i in lengths_permute]
+
+    # the longest iterable is the primary one (Bresenham: the longest
+    # distance along an axis)
+    delta_primary, deltas_secondary = lengths_desc[0], lengths_desc[1:]
+    iter_primary, iters_secondary = iters_desc[0], iters_desc[1:]
+    errors = [delta_primary // dims] * len(deltas_secondary)
+
+    to_yield = sum(lengths)
+    while to_yield:
+        yield next(iter_primary)
+        to_yield -= 1
+        # update errors for each secondary iterable
+        errors = [e - delta for e, delta in zip(errors, deltas_secondary)]
+
+        # those iterables for which the error is negative are yielded
+        # ("diagonal step" in Bresenham)
+        for i, e_ in enumerate(errors):
+            if e_ < 0:
+                yield next(iters_secondary[i])
+                to_yield -= 1
+                errors[i] += delta_primary
+
+
+def interleave_randomly(*iterables):
+    """Repeatedly select one of the input *iterables* at random and yield the next
+    item from it.
+
+        >>> iterables = [1, 2, 3], 'abc', (True, False, None)
+        >>> list(interleave_randomly(*iterables))  # doctest: +SKIP
+        ['a', 'b', 1, 'c', True, False, None, 2, 3]
+
+    The relative order of the items in each input iterable will preserved. Note the
+    sequences of items with this property are not equally likely to be generated.
+
+    """
+    iterators = [iter(e) for e in iterables]
+    while iterators:
+        idx = randrange(len(iterators))
+        try:
+            yield next(iterators[idx])
+        except StopIteration:
+            # equivalent to `list.pop` but slightly faster
+            iterators[idx] = iterators[-1]
+            del iterators[-1]
 
 
 def collapse(iterable, base_type=None, levels=None):
@@ -1042,26 +1379,38 @@ def collapse(iterable, base_type=None, levels=None):
     ['a', ['b'], 'c', ['d']]
 
     """
+    stack = deque()
+    # Add our first node group, treat the iterable as a single node
+    stack.appendleft((0, repeat(iterable, 1)))
 
-    def walk(node, level):
-        if (
-            ((levels is not None) and (level > levels))
-            or isinstance(node, (str, bytes))
-            or ((base_type is not None) and isinstance(node, base_type))
-        ):
-            yield node
-            return
+    while stack:
+        node_group = stack.popleft()
+        level, nodes = node_group
 
-        try:
-            tree = iter(node)
-        except TypeError:
-            yield node
-            return
-        else:
-            for child in tree:
-                yield from walk(child, level + 1)
+        # Check if beyond max level
+        if levels is not None and level > levels:
+            yield from nodes
+            continue
 
-    yield from walk(iterable, 0)
+        for node in nodes:
+            # Check if done iterating
+            if isinstance(node, (str, bytes)) or (
+                (base_type is not None) and isinstance(node, base_type)
+            ):
+                yield node
+            # Otherwise try to create child nodes
+            else:
+                try:
+                    tree = iter(node)
+                except TypeError:
+                    yield node
+                else:
+                    # Save our current location
+                    stack.appendleft(node_group)
+                    # Append the new child node
+                    stack.appendleft((level + 1, tree))
+                    # Break to process child node
+                    break
 
 
 def side_effect(func, iterable, chunk_size=None, before=None, after=None):
@@ -1154,7 +1503,7 @@ def ret():
                     raise ValueError("seq is not divisible by n.")
                 yield _slice
 
-        return iter(ret())
+        return ret()
     else:
         return iterator
 
@@ -1176,7 +1525,7 @@ def split_at(iterable, pred, maxsplit=-1, keep_separator=False):
         [[0], [2], [4, 5, 6, 7, 8, 9]]
 
     By default, the delimiting items are not included in the output.
-    The include them, set *keep_separator* to ``True``.
+    To include them, set *keep_separator* to ``True``.
 
         >>> list(split_at('abcdcba', lambda x: x == 'b', keep_separator=True))
         [['a'], ['b'], ['c', 'd', 'c'], ['b'], ['a']]
@@ -1229,7 +1578,7 @@ def split_before(iterable, pred, maxsplit=-1):
         if pred(item) and buf:
             yield buf
             if maxsplit == 1:
-                yield [item] + list(it)
+                yield [item, *it]
                 return
             buf = []
             maxsplit -= 1
@@ -1266,7 +1615,9 @@ def split_after(iterable, pred, maxsplit=-1):
         if pred(item) and buf:
             yield buf
             if maxsplit == 1:
-                yield list(it)
+                buf = list(it)
+                if buf:
+                    yield buf
                 return
             buf = []
             maxsplit -= 1
@@ -1308,7 +1659,7 @@ def split_when(iterable, pred, maxsplit=-1):
         if pred(cur_item, next_item):
             yield buf
             if maxsplit == 1:
-                yield [next_item] + list(it)
+                yield [next_item, *it]
                 return
             buf = []
             maxsplit -= 1
@@ -1333,15 +1684,15 @@ def split_into(iterable, sizes):
         [[1, 2], [3, 4, 5]]
 
     If the sum of *sizes* is larger than the length of *iterable*, fewer items
-    will be returned in the iteration that overruns *iterable* and further
+    will be returned in the iteration that overruns the *iterable* and further
     lists will be empty:
 
         >>> list(split_into([1,2,3,4], [1,2,3,4]))
         [[1], [2, 3], [4], []]
 
     When a ``None`` object is encountered in *sizes*, the returned list will
-    contain items up to the end of *iterable* the same way that itertools.slice
-    does:
+    contain items up to the end of *iterable* the same way that
+    :func:`itertools.slice` does:
 
         >>> list(split_into([1,2,3,4,5,6,7,8,9,0], [2,3,None]))
         [[1, 2], [3, 4, 5], [6, 7, 8, 9, 0]]
@@ -1372,28 +1723,50 @@ def padded(iterable, fillvalue=None, n=None, next_multiple=False):
         [1, 2, 3, '?', '?']
 
     If *next_multiple* is ``True``, *fillvalue* will be emitted until the
-    number of items emitted is a multiple of *n*::
+    number of items emitted is a multiple of *n*:
 
         >>> list(padded([1, 2, 3, 4], n=3, next_multiple=True))
         [1, 2, 3, 4, None, None]
 
     If *n* is ``None``, *fillvalue* will be emitted indefinitely.
 
+    To create an *iterable* of exactly size *n*, you can truncate with
+    :func:`islice`.
+
+        >>> list(islice(padded([1, 2, 3], '?'), 5))
+        [1, 2, 3, '?', '?']
+        >>> list(islice(padded([1, 2, 3, 4, 5, 6, 7, 8], '?'), 5))
+        [1, 2, 3, 4, 5]
+
     """
-    it = iter(iterable)
+    iterator = iter(iterable)
+    iterator_with_repeat = chain(iterator, repeat(fillvalue))
+
     if n is None:
-        yield from chain(it, repeat(fillvalue))
+        return iterator_with_repeat
     elif n < 1:
         raise ValueError('n must be at least 1')
+    elif next_multiple:
+
+        def slice_generator():
+            for first in iterator:
+                yield (first,)
+                yield islice(iterator_with_repeat, n - 1)
+
+        # While elements exist produce slices of size n
+        return chain.from_iterable(slice_generator())
     else:
-        item_count = 0
-        for item in it:
-            yield item
-            item_count += 1
+        # Ensure the first batch is at least size n then iterate
+        return chain(islice(iterator_with_repeat, n), iterator)
+
 
-        remaining = (n - item_count) % n if next_multiple else n - item_count
-        for _ in range(remaining):
-            yield fillvalue
+def repeat_each(iterable, n=2):
+    """Repeat each element in *iterable* *n* times.
+
+    >>> list(repeat_each('ABC', 3))
+    ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']
+    """
+    return chain.from_iterable(map(repeat, iterable, repeat(n)))
 
 
 def repeat_last(iterable, default=None):
@@ -1439,7 +1812,9 @@ def distribute(n, iterable):
         [[1], [2], [3], [], []]
 
     This function uses :func:`itertools.tee` and may require significant
-    storage. If you need the order items in the smaller iterables to match the
+    storage.
+
+    If you need the order items in the smaller iterables to match the
     original iterable, see :func:`divide`.
 
     """
@@ -1478,27 +1853,8 @@ def stagger(iterable, offsets=(-1, 0, 1), longest=False, fillvalue=None):
     )
 
 
-class UnequalIterablesError(ValueError):
-    def __init__(self, details=None):
-        msg = 'Iterables have different lengths'
-        if details is not None:
-            msg += (': index 0 has length {}; index {} has length {}').format(
-                *details
-            )
-
-        super().__init__(msg)
-
-
-def _zip_equal_generator(iterables):
-    for combo in zip_longest(*iterables, fillvalue=_marker):
-        for val in combo:
-            if val is _marker:
-                raise UnequalIterablesError()
-        yield combo
-
-
 def zip_equal(*iterables):
-    """``zip`` the input *iterables* together, but raise
+    """``zip`` the input *iterables* together but raise
     ``UnequalIterablesError`` if they aren't all the same length.
 
         >>> it_1 = range(3)
@@ -1524,23 +1880,8 @@ def zip_equal(*iterables):
             ),
             DeprecationWarning,
         )
-    # Check whether the iterables are all the same size.
-    try:
-        first_size = len(iterables[0])
-        for i, it in enumerate(iterables[1:], 1):
-            size = len(it)
-            if size != first_size:
-                break
-        else:
-            # If we didn't break out, we can use the built-in zip.
-            return zip(*iterables)
 
-        # If we did break out, there was a mismatch.
-        raise UnequalIterablesError(details=(first_size, i, size))
-    # If any one of the iterables didn't have a length, start reading
-    # them until one runs out.
-    except TypeError:
-        return _zip_equal_generator(iterables)
+    return _zip_equal(*iterables)
 
 
 def zip_offset(*iterables, offsets, longest=False, fillvalue=None):
@@ -1582,7 +1923,9 @@ def zip_offset(*iterables, offsets, longest=False, fillvalue=None):
     return zip(*staggered)
 
 
-def sort_together(iterables, key_list=(0,), key=None, reverse=False):
+def sort_together(
+    iterables, key_list=(0,), key=None, reverse=False, strict=False
+):
     """Return the input iterables sorted together, with *key_list* as the
     priority for sorting. All iterables are trimmed to the length of the
     shortest one.
@@ -1621,6 +1964,10 @@ def sort_together(iterables, key_list=(0,), key=None, reverse=False):
         >>> sort_together([(1, 2, 3), ('c', 'b', 'a')], reverse=True)
         [(3, 2, 1), ('a', 'b', 'c')]
 
+    If the *strict* keyword argument is ``True``, then
+    ``UnequalIterablesError`` will be raised if any of the iterables have
+    different lengths.
+
     """
     if key is None:
         # if there is no key function, the key argument to sorted is an
@@ -1643,8 +1990,9 @@ def sort_together(iterables, key_list=(0,), key=None, reverse=False):
                 *get_key_items(zipped_items)
             )
 
+    zipper = zip_equal if strict else zip
     return list(
-        zip(*sorted(zip(*iterables), key=key_argument, reverse=reverse))
+        zipper(*sorted(zipper(*iterables), key=key_argument, reverse=reverse))
     )
 
 
@@ -1653,7 +2001,7 @@ def unzip(iterable):
     of the zipped *iterable*.
 
     The ``i``-th iterable contains the ``i``-th element from each element
-    of the zipped iterable. The first element is used to to determine the
+    of the zipped iterable. The first element is used to determine the
     length of the remaining elements.
 
         >>> iterable = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
@@ -1668,7 +2016,7 @@ def unzip(iterable):
     :func:`itertools.tee` and thus may require significant storage.
 
     """
-    head, iterable = spy(iter(iterable))
+    head, iterable = spy(iterable)
     if not head:
         # empty iterable, e.g. zip([], [], [])
         return ()
@@ -1676,25 +2024,17 @@ def unzip(iterable):
     head = head[0]
     iterables = tee(iterable, len(head))
 
-    def itemgetter(i):
-        def getter(obj):
-            try:
-                return obj[i]
-            except IndexError:
-                # basically if we have an iterable like
-                # iter([(1, 2, 3), (4, 5), (6,)])
-                # the second unzipped iterable would fail at the third tuple
-                # since it would try to access tup[1]
-                # same with the third unzipped iterable and the second tuple
-                # to support these "improperly zipped" iterables,
-                # we create a custom itemgetter
-                # which just stops the unzipped iterables
-                # at first length mismatch
-                raise StopIteration
-
-        return getter
-
-    return tuple(map(itemgetter(i), it) for i, it in enumerate(iterables))
+    # If we have an iterable like iter([(1, 2, 3), (4, 5), (6,)]),
+    # the second unzipped iterable fails at the third tuple since
+    # it tries to access (6,)[1].
+    # Same with the third unzipped iterable and the second tuple.
+    # To support these "improperly zipped" iterables, we suppress
+    # the IndexError, which just stops the unzipped iterables at
+    # first length mismatch.
+    return tuple(
+        iter_suppress(map(itemgetter(i), it), IndexError)
+        for i, it in enumerate(iterables)
+    )
 
 
 def divide(n, iterable):
@@ -1721,9 +2061,9 @@ def divide(n, iterable):
         >>> [list(c) for c in children]
         [[1], [2], [3], [], []]
 
-    This function will exhaust the iterable before returning and may require
-    significant storage. If order is not important, see :func:`distribute`,
-    which does not first pull the iterable into memory.
+    This function will exhaust the iterable before returning.
+    If order is not important, see :func:`distribute`, which does not first
+    pull the iterable into memory.
 
     """
     if n < 1:
@@ -1919,7 +2259,7 @@ class numeric_range(abc.Sequence, abc.Hashable):
         >>> list(numeric_range(3, -1, -1.0))
         [3.0, 2.0, 1.0, 0.0]
 
-    Be aware of the limitations of floating point numbers; the representation
+    Be aware of the limitations of floating-point numbers; the representation
     of the yielded numbers may be surprising.
 
     ``datetime.datetime`` objects can be used for *start* and *stop*, if *step*
@@ -1952,20 +2292,17 @@ def __init__(self, *args):
             self._start, self._stop, self._step = args
         elif argc == 0:
             raise TypeError(
-                'numeric_range expected at least '
-                '1 argument, got {}'.format(argc)
+                f'numeric_range expected at least 1 argument, got {argc}'
             )
         else:
             raise TypeError(
-                'numeric_range expected at most '
-                '3 arguments, got {}'.format(argc)
+                f'numeric_range expected at most 3 arguments, got {argc}'
             )
 
         self._zero = type(self._step)(0)
         if self._step == self._zero:
             raise ValueError('numeric_range() arg 3 must not be zero')
         self._growing = self._step > self._zero
-        self._init_len()
 
     def __bool__(self):
         if self._growing:
@@ -2022,7 +2359,7 @@ def __getitem__(self, key):
         else:
             raise TypeError(
                 'numeric range indices must be '
-                'integers or slices, not {}'.format(type(key).__name__)
+                f'integers or slices, not {type(key).__name__}'
             )
 
     def __hash__(self):
@@ -2041,7 +2378,8 @@ def __iter__(self):
     def __len__(self):
         return self._len
 
-    def _init_len(self):
+    @cached_property
+    def _len(self):
         if self._growing:
             start = self._start
             stop = self._stop
@@ -2052,23 +2390,20 @@ def _init_len(self):
             step = -self._step
         distance = stop - start
         if distance <= self._zero:
-            self._len = 0
+            return 0
         else:  # distance > 0 and step > 0: regular euclidean division
             q, r = divmod(distance, step)
-            self._len = int(q) + int(r != self._zero)
+            return int(q) + int(r != self._zero)
 
     def __reduce__(self):
         return numeric_range, (self._start, self._stop, self._step)
 
     def __repr__(self):
         if self._step == 1:
-            return "numeric_range({}, {})".format(
-                repr(self._start), repr(self._stop)
-            )
-        else:
-            return "numeric_range({}, {}, {})".format(
-                repr(self._start), repr(self._stop), repr(self._step)
-            )
+            return f"numeric_range({self._start!r}, {self._stop!r})"
+        return (
+            f"numeric_range({self._start!r}, {self._stop!r}, {self._step!r})"
+        )
 
     def __reversed__(self):
         return iter(
@@ -2092,7 +2427,7 @@ def index(self, value):
                 if r == self._zero:
                     return int(q)
 
-        raise ValueError("{} is not in numeric range".format(value))
+        raise ValueError(f"{value} is not in numeric range")
 
     def _get_by_index(self, i):
         if i < 0:
@@ -2111,11 +2446,11 @@ def count_cycle(iterable, n=None):
     [(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')]
 
     """
-    iterable = tuple(iterable)
-    if not iterable:
+    seq = tuple(iterable)
+    if not seq:
         return iter(())
     counter = count() if n is None else range(n)
-    return ((i, item) for i in counter for item in iterable)
+    return zip(repeat_each(counter, len(seq)), cycle(seq))
 
 
 def mark_ends(iterable):
@@ -2139,20 +2474,13 @@ def mark_ends(iterable):
     300
     """
     it = iter(iterable)
-
-    try:
-        b = next(it)
-    except StopIteration:
-        return
-
-    try:
-        for i in count():
+    for a in it:
+        first = True
+        for b in it:
+            yield first, False, a
             a = b
-            b = next(it)
-            yield i == 0, False, a
-
-    except StopIteration:
-        yield i == 0, True, a
+            first = False
+        yield first, True, a
 
 
 def locate(iterable, pred=bool, window_size=None):
@@ -2203,6 +2531,16 @@ def locate(iterable, pred=bool, window_size=None):
     return compress(count(), starmap(pred, it))
 
 
+def longest_common_prefix(iterables):
+    """Yield elements of the longest common prefix among given *iterables*.
+
+    >>> ''.join(longest_common_prefix(['abcd', 'abc', 'abf']))
+    'ab'
+
+    """
+    return (c[0] for c in takewhile(all_equal, zip(*iterables)))
+
+
 def lstrip(iterable, pred):
     """Yield the items from *iterable*, but strip any from the beginning
     for which *pred* returns ``True``.
@@ -2268,8 +2606,8 @@ class islice_extended:
     """An extension of :func:`itertools.islice` that supports negative values
     for *stop*, *start*, and *step*.
 
-        >>> iterable = iter('abcdefgh')
-        >>> list(islice_extended(iterable, -4, -1))
+        >>> iterator = iter('abcdefgh')
+        >>> list(islice_extended(iterator, -4, -1))
         ['e', 'f', 'g']
 
     Slices with negative values require some caching of *iterable*, but this
@@ -2283,8 +2621,8 @@ class islice_extended:
 
     You can also use slice notation directly:
 
-        >>> iterable = map(str, count())
-        >>> it = islice_extended(iterable)[10:20:2]
+        >>> iterator = map(str, count())
+        >>> it = islice_extended(iterator)[10:20:2]
         >>> list(it)
         ['10', '12', '14', '16', '18']
 
@@ -2293,19 +2631,19 @@ class islice_extended:
     def __init__(self, iterable, *args):
         it = iter(iterable)
         if args:
-            self._iterable = _islice_helper(it, slice(*args))
+            self._iterator = _islice_helper(it, slice(*args))
         else:
-            self._iterable = it
+            self._iterator = it
 
     def __iter__(self):
         return self
 
     def __next__(self):
-        return next(self._iterable)
+        return next(self._iterator)
 
     def __getitem__(self, key):
         if isinstance(key, slice):
-            return islice_extended(_islice_helper(self._iterable, key))
+            return islice_extended(_islice_helper(self._iterator, key))
 
         raise TypeError('islice_extended.__getitem__ argument must be a slice')
 
@@ -2341,8 +2679,15 @@ def _islice_helper(it, s):
             if n <= 0:
                 return
 
-            for index, item in islice(cache, 0, n, step):
-                yield item
+            for index in range(n):
+                if index % step == 0:
+                    # pop and yield the item.
+                    # We don't want to use an intermediate variable
+                    # it would extend the lifetime of the current item
+                    yield cache.popleft()[1]
+                else:
+                    # just pop and discard the item
+                    cache.popleft()
         elif (stop is not None) and (stop < 0):
             # Advance to the start position
             next(islice(it, start, start), None)
@@ -2352,9 +2697,14 @@ def _islice_helper(it, s):
             cache = deque(islice(it, -stop), maxlen=-stop)
 
             for index, item in enumerate(it):
-                cached_item = cache.popleft()
                 if index % step == 0:
-                    yield cached_item
+                    # pop and yield the item.
+                    # We don't want to use an intermediate variable
+                    # it would extend the lifetime of the current item
+                    yield cache.popleft()
+                else:
+                    # just pop and discard the item
+                    cache.popleft()
                 cache.append(item)
         else:
             # When both start and stop are positive we have the normal case
@@ -2424,7 +2774,7 @@ def always_reversible(iterable):
         return reversed(list(iterable))
 
 
-def consecutive_groups(iterable, ordering=lambda x: x):
+def consecutive_groups(iterable, ordering=None):
     """Yield groups of consecutive items using :func:`itertools.groupby`.
     The *ordering* function determines whether two items are adjacent by
     returning their position.
@@ -2441,12 +2791,11 @@ def consecutive_groups(iterable, ordering=lambda x: x):
         [30, 31, 32, 33]
         [40]
 
-    For finding runs of adjacent letters, try using the :meth:`index` method
-    of a string of letters:
+    To find runs of adjacent letters, apply :func:`ord` function
+    to convert letters to ordinals.
 
-        >>> from string import ascii_lowercase
         >>> iterable = 'abcdfgilmnop'
-        >>> ordering = ascii_lowercase.index
+        >>> ordering = ord
         >>> for group in consecutive_groups(iterable, ordering):
         ...     print(list(group))
         ['a', 'b', 'c', 'd']
@@ -2466,9 +2815,12 @@ def consecutive_groups(iterable, ordering=lambda x: x):
         [[1, 2], [11, 12], [21, 22]]
 
     """
-    for k, g in groupby(
-        enumerate(iterable), key=lambda x: x[0] - ordering(x[1])
-    ):
+    if ordering is None:
+        key = lambda x: x[0] - x[1]
+    else:
+        key = lambda x: x[0] - ordering(x[1])
+
+    for k, g in groupby(enumerate(iterable), key=key):
         yield map(itemgetter(1), g)
 
 
@@ -2511,7 +2863,7 @@ def difference(iterable, func=sub, *, initial=None):
     if initial is not None:
         first = []
 
-    return chain(first, starmap(func, zip(b, a)))
+    return chain(first, map(func, b, a))
 
 
 class SequenceView(Sequence):
@@ -2556,7 +2908,7 @@ def __len__(self):
         return len(self._target)
 
     def __repr__(self):
-        return '{}({})'.format(self.__class__.__name__, repr(self._target))
+        return f'{self.__class__.__name__}({self._target!r})'
 
 
 class seekable:
@@ -2576,8 +2928,6 @@ class seekable:
         >>> it.seek(0)
         >>> next(it), next(it), next(it)
         ('0', '1', '2')
-        >>> next(it)
-        '3'
 
     You can also seek forward:
 
@@ -2589,8 +2939,25 @@ class seekable:
         >>> list(it)
         []
         >>> it.seek(0)  # Resetting works even after hitting the end
+        >>> next(it)
+        '0'
+
+    Call :meth:`relative_seek` to seek relative to the source iterator's
+    current position.
+
+        >>> it = seekable((str(n) for n in range(20)))
         >>> next(it), next(it), next(it)
         ('0', '1', '2')
+        >>> it.relative_seek(2)
+        >>> next(it)
+        '5'
+        >>> it.relative_seek(-3)  # Source is at '6', we move back to '3'
+        >>> next(it)
+        '3'
+        >>> it.relative_seek(-3)  # Source is at '4', we move back to '1'
+        >>> next(it)
+        '1'
+
 
     Call :meth:`peek` to look ahead one item without advancing the iterator:
 
@@ -2698,6 +3065,12 @@ def seek(self, index):
         if remainder > 0:
             consume(self, remainder)
 
+    def relative_seek(self, count):
+        if self._index is None:
+            self._index = len(self._cache)
+
+        self.seek(max(self._index + count, 0))
+
 
 class run_length:
     """
@@ -2725,7 +3098,7 @@ def encode(iterable):
 
     @staticmethod
     def decode(iterable):
-        return chain.from_iterable(repeat(k, n) for k, n in iterable)
+        return chain.from_iterable(starmap(repeat, iterable))
 
 
 def exactly_n(iterable, n, predicate=bool):
@@ -2743,17 +3116,37 @@ def exactly_n(iterable, n, predicate=bool):
     so avoid calling it on infinite iterables.
 
     """
-    return len(take(n + 1, filter(predicate, iterable))) == n
+    return ilen(islice(filter(predicate, iterable), n + 1)) == n
 
 
-def circular_shifts(iterable):
-    """Return a list of circular shifts of *iterable*.
+def circular_shifts(iterable, steps=1):
+    """Yield the circular shifts of *iterable*.
 
-    >>> circular_shifts(range(4))
+    >>> list(circular_shifts(range(4)))
     [(0, 1, 2, 3), (1, 2, 3, 0), (2, 3, 0, 1), (3, 0, 1, 2)]
+
+    Set *steps* to the number of places to rotate to the left
+    (or to the right if negative).  Defaults to 1.
+
+    >>> list(circular_shifts(range(4), 2))
+    [(0, 1, 2, 3), (2, 3, 0, 1)]
+
+    >>> list(circular_shifts(range(4), -1))
+    [(0, 1, 2, 3), (3, 0, 1, 2), (2, 3, 0, 1), (1, 2, 3, 0)]
+
     """
-    lst = list(iterable)
-    return take(len(lst), windowed(cycle(lst), len(lst)))
+    buffer = deque(iterable)
+    if steps == 0:
+        raise ValueError('Steps should be a non-zero integer')
+
+    buffer.rotate(steps)
+    steps = -steps
+    n = len(buffer)
+    n //= math.gcd(n, steps)
+
+    for _ in repeat(None, n):
+        buffer.rotate(steps)
+        yield tuple(buffer)
 
 
 def make_decorator(wrapping_func, result_index=0):
@@ -2804,6 +3197,7 @@ def make_decorator(wrapping_func, result_index=0):
         '7'
 
     """
+
     # See https://sites.google.com/site/bbayles/index/decorator_factory for
     # notes on how this works.
     def decorator(*wrapping_args, **wrapping_kwargs):
@@ -2872,13 +3266,19 @@ def map_reduce(iterable, keyfunc, valuefunc=None, reducefunc=None):
     dictionary.
 
     """
-    valuefunc = (lambda x: x) if (valuefunc is None) else valuefunc
 
     ret = defaultdict(list)
-    for item in iterable:
-        key = keyfunc(item)
-        value = valuefunc(item)
-        ret[key].append(value)
+
+    if valuefunc is None:
+        for item in iterable:
+            key = keyfunc(item)
+            ret[key].append(item)
+
+    else:
+        for item in iterable:
+            key = keyfunc(item)
+            value = valuefunc(item)
+            ret[key].append(value)
 
     if reducefunc is not None:
         for key, value_list in ret.items():
@@ -2900,9 +3300,9 @@ def rlocate(iterable, pred=bool, window_size=None):
     Set *pred* to a custom function to, e.g., find the indexes for a particular
     item:
 
-        >>> iterable = iter('abcb')
+        >>> iterator = iter('abcb')
         >>> pred = lambda x: x == 'b'
-        >>> list(rlocate(iterable, pred))
+        >>> list(rlocate(iterator, pred))
         [3, 1]
 
     If *window_size* is given, then the *pred* function will be called with
@@ -2968,7 +3368,7 @@ def replace(iterable, pred, substitutes, count=None, window_size=1):
 
     # Add padding such that the number of windows matches the length of the
     # iterable
-    it = chain(iterable, [_marker] * (window_size - 1))
+    it = chain(iterable, repeat(_marker, window_size - 1))
     windows = windowed(it, window_size)
 
     n = 0
@@ -3012,7 +3412,7 @@ def partitions(iterable):
         yield [sequence[i:j] for i, j in zip((0,) + i, i + (n,))]
 
 
-def set_partitions(iterable, k=None):
+def set_partitions(iterable, k=None, min_size=None, max_size=None):
     """
     Yield the set partitions of *iterable* into *k* parts. Set partitions are
     not order-preserving.
@@ -3036,10 +3436,24 @@ def set_partitions(iterable, k=None):
     ['b', 'ac']
     ['a', 'b', 'c']
 
-    """
-    L = list(iterable)
-    n = len(L)
-    if k is not None:
+    if *min_size* and/or *max_size* are given, the minimum and/or maximum size
+    per block in partition is set.
+
+    >>> iterable = 'abc'
+    >>> for part in set_partitions(iterable, min_size=2):
+    ...     print([''.join(p) for p in part])
+    ['abc']
+    >>> for part in set_partitions(iterable, max_size=2):
+    ...     print([''.join(p) for p in part])
+    ['a', 'bc']
+    ['ab', 'c']
+    ['b', 'ac']
+    ['a', 'b', 'c']
+
+    """
+    L = list(iterable)
+    n = len(L)
+    if k is not None:
         if k < 1:
             raise ValueError(
                 "Can't partition in a negative or zero number of groups"
@@ -3047,6 +3461,11 @@ def set_partitions(iterable, k=None):
         elif k > n:
             return
 
+    min_size = min_size if min_size is not None else 0
+    max_size = max_size if max_size is not None else n
+    if min_size > max_size:
+        return
+
     def set_partitions_helper(L, k):
         n = len(L)
         if k == 1:
@@ -3063,9 +3482,15 @@ def set_partitions_helper(L, k):
 
     if k is None:
         for k in range(1, n + 1):
-            yield from set_partitions_helper(L, k)
+            yield from filter(
+                lambda z: all(min_size <= len(bk) <= max_size for bk in z),
+                set_partitions_helper(L, k),
+            )
     else:
-        yield from set_partitions_helper(L, k)
+        yield from filter(
+            lambda z: all(min_size <= len(bk) <= max_size for bk in z),
+            set_partitions_helper(L, k),
+        )
 
 
 class time_limited:
@@ -3090,6 +3515,8 @@ class time_limited:
     stops if  the time elapsed is greater than *limit_seconds*. If your time
     limit is 1 second, but it takes 2 seconds to generate the first item from
     the iterable, the function will run for 2 seconds and not yield anything.
+    As a special case, when *limit_seconds* is zero, the iterator never
+    returns anything.
 
     """
 
@@ -3097,7 +3524,7 @@ def __init__(self, limit_seconds, iterable):
         if limit_seconds < 0:
             raise ValueError('limit_seconds must be positive')
         self.limit_seconds = limit_seconds
-        self._iterable = iter(iterable)
+        self._iterator = iter(iterable)
         self._start_time = monotonic()
         self.timed_out = False
 
@@ -3105,7 +3532,10 @@ def __iter__(self):
         return self
 
     def __next__(self):
-        item = next(self._iterable)
+        if self.limit_seconds == 0:
+            self.timed_out = True
+            raise StopIteration
+        item = next(self._iterator)
         if monotonic() - self._start_time > self.limit_seconds:
             self.timed_out = True
             raise StopIteration
@@ -3136,22 +3566,48 @@ def only(iterable, default=None, too_long=None):
     Note that :func:`only` attempts to advance *iterable* twice to ensure there
     is only one item.  See :func:`spy` or :func:`peekable` to check
     iterable contents less destructively.
+
     """
-    it = iter(iterable)
-    first_value = next(it, default)
+    iterator = iter(iterable)
+    for first in iterator:
+        for second in iterator:
+            msg = (
+                f'Expected exactly one item in iterable, but got {first!r}, '
+                f'{second!r}, and perhaps more.'
+            )
+            raise too_long or ValueError(msg)
+        return first
+    return default
 
-    try:
-        second_value = next(it)
-    except StopIteration:
-        pass
-    else:
-        msg = (
-            'Expected exactly one item in iterable, but got {!r}, {!r}, '
-            'and perhaps more.'.format(first_value, second_value)
-        )
-        raise too_long or ValueError(msg)
 
-    return first_value
+def _ichunk(iterator, n):
+    cache = deque()
+    chunk = islice(iterator, n)
+
+    def generator():
+        with suppress(StopIteration):
+            while True:
+                if cache:
+                    yield cache.popleft()
+                else:
+                    yield next(chunk)
+
+    def materialize_next(n=1):
+        # if n not specified materialize everything
+        if n is None:
+            cache.extend(chunk)
+            return len(cache)
+
+        to_cache = n - len(cache)
+
+        # materialize up to n
+        if to_cache > 0:
+            cache.extend(islice(chunk, to_cache))
+
+        # return number materialized up to n
+        return min(n, len(cache))
+
+    return (generator(), materialize_next)
 
 
 def ichunked(iterable, n):
@@ -3175,20 +3631,39 @@ def ichunked(iterable, n):
     [8, 9, 10, 11]
 
     """
-    source = iter(iterable)
-
+    iterator = iter(iterable)
     while True:
+        # Create new chunk
+        chunk, materialize_next = _ichunk(iterator, n)
+
         # Check to see whether we're at the end of the source iterable
-        item = next(source, _marker)
-        if item is _marker:
+        if not materialize_next():
             return
 
-        # Clone the source and yield an n-length slice
-        source, it = tee(chain([item], source))
-        yield islice(it, n)
+        yield chunk
 
-        # Advance the source iterable
-        consume(source, n)
+        # Fill previous chunk's cache
+        materialize_next(None)
+
+
+def iequals(*iterables):
+    """Return ``True`` if all given *iterables* are equal to each other,
+    which means that they contain the same elements in the same order.
+
+    The function is useful for comparing iterables of different data types
+    or iterables that do not support equality checks.
+
+    >>> iequals("abc", ['a', 'b', 'c'], ('a', 'b', 'c'), iter("abc"))
+    True
+
+    >>> iequals("abc", "acb")
+    False
+
+    Not to be confused with :func:`all_equal`, which checks whether all
+    elements of iterable are equal to each other.
+
+    """
+    return all(map(all_equal, zip_longest(*iterables, fillvalue=object())))
 
 
 def distinct_combinations(iterable, r):
@@ -3260,7 +3735,7 @@ def map_except(function, iterable, *exceptions):
     result, unless *function* raises one of the specified *exceptions*.
 
     *function* is called to transform each item in *iterable*.
-    It should be a accept one argument.
+    It should accept one argument.
 
     >>> iterable = ['1', '2', 'three', '4', None]
     >>> list(map_except(int, iterable, ValueError, TypeError))
@@ -3276,33 +3751,55 @@ def map_except(function, iterable, *exceptions):
             pass
 
 
-def _sample_unweighted(iterable, k):
-    # Implementation of "Algorithm L" from the 1994 paper by Kim-Hung Li:
-    # "Reservoir-Sampling Algorithms of Time Complexity O(n(1+log(N/n)))".
+def map_if(iterable, pred, func, func_else=None):
+    """Evaluate each item from *iterable* using *pred*. If the result is
+    equivalent to ``True``, transform the item with *func* and yield it.
+    Otherwise, transform the item with *func_else* and yield it.
+
+    *pred*, *func*, and *func_else* should each be functions that accept
+    one argument. By default, *func_else* is the identity function.
 
-    # Fill up the reservoir (collection of samples) with the first `k` samples
-    reservoir = take(k, iterable)
+    >>> from math import sqrt
+    >>> iterable = list(range(-5, 5))
+    >>> iterable
+    [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
+    >>> list(map_if(iterable, lambda x: x > 3, lambda x: 'toobig'))
+    [-5, -4, -3, -2, -1, 0, 1, 2, 3, 'toobig']
+    >>> list(map_if(iterable, lambda x: x >= 0,
+    ... lambda x: f'{sqrt(x):.2f}', lambda x: None))
+    [None, None, None, None, None, '0.00', '1.00', '1.41', '1.73', '2.00']
+    """
 
-    # Generate random number that's the largest in a sample of k U(0,1) numbers
-    # Largest order statistic: https://en.wikipedia.org/wiki/Order_statistic
-    W = exp(log(random()) / k)
+    if func_else is None:
+        for item in iterable:
+            yield func(item) if pred(item) else item
 
-    # The number of elements to skip before changing the reservoir is a random
-    # number with a geometric distribution. Sample it using random() and logs.
-    next_index = k + floor(log(random()) / log(1 - W))
+    else:
+        for item in iterable:
+            yield func(item) if pred(item) else func_else(item)
 
-    for index, element in enumerate(iterable, k):
 
-        if index == next_index:
+def _sample_unweighted(iterator, k, strict):
+    # Algorithm L in the 1994 paper by Kim-Hung Li:
+    # "Reservoir-Sampling Algorithms of Time Complexity O(n(1+log(N/n)))".
+
+    reservoir = list(islice(iterator, k))
+    if strict and len(reservoir) < k:
+        raise ValueError('Sample larger than population')
+    W = 1.0
+
+    with suppress(StopIteration):
+        while True:
+            W *= random() ** (1 / k)
+            skip = floor(log(random()) / log1p(-W))
+            element = next(islice(iterator, skip, None))
             reservoir[randrange(k)] = element
-            # The new W is the largest in a sample of k U(0, `old_W`) numbers
-            W *= exp(log(random()) / k)
-            next_index += floor(log(random()) / log(1 - W)) + 1
 
+    shuffle(reservoir)
     return reservoir
 
 
-def _sample_weighted(iterable, k, weights):
+def _sample_weighted(iterator, k, weights, strict):
     # Implementation of "A-ExpJ" from the 2006 paper by Efraimidis et al. :
     # "Weighted random sampling with a reservoir".
 
@@ -3311,7 +3808,10 @@ def _sample_weighted(iterable, k, weights):
 
     # Fill up the reservoir (collection of samples) with the first `k`
     # weight-keys and elements, then heapify the list.
-    reservoir = take(k, zip(weight_keys, iterable))
+    reservoir = take(k, zip(weight_keys, iterator))
+    if strict and len(reservoir) < k:
+        raise ValueError('Sample larger than population')
+
     heapify(reservoir)
 
     # The number of jumps before changing the reservoir is a random variable
@@ -3319,7 +3819,7 @@ def _sample_weighted(iterable, k, weights):
     smallest_weight_key, _ = reservoir[0]
     weights_to_skip = log(random()) / smallest_weight_key
 
-    for weight, element in zip(weights, iterable):
+    for weight, element in zip(weights, iterator):
         if weight >= weights_to_skip:
             # The notation here is consistent with the paper, but we store
             # the weight-keys in log-space for better numerical stability.
@@ -3333,47 +3833,130 @@ def _sample_weighted(iterable, k, weights):
         else:
             weights_to_skip -= weight
 
-    # Equivalent to [element for weight_key, element in sorted(reservoir)]
-    return [heappop(reservoir)[1] for _ in range(k)]
+    ret = [element for weight_key, element in reservoir]
+    shuffle(ret)
+    return ret
+
+
+def _sample_counted(population, k, counts, strict):
+    element = None
+    remaining = 0
 
+    def feed(i):
+        # Advance *i* steps ahead and consume an element
+        nonlocal element, remaining
+
+        while i + 1 > remaining:
+            i = i - remaining
+            element = next(population)
+            remaining = next(counts)
+        remaining -= i + 1
+        return element
+
+    with suppress(StopIteration):
+        reservoir = []
+        for _ in range(k):
+            reservoir.append(feed(0))
+
+    if strict and len(reservoir) < k:
+        raise ValueError('Sample larger than population')
+
+    with suppress(StopIteration):
+        W = 1.0
+        while True:
+            W *= random() ** (1 / k)
+            skip = floor(log(random()) / log1p(-W))
+            element = feed(skip)
+            reservoir[randrange(k)] = element
 
-def sample(iterable, k, weights=None):
+    shuffle(reservoir)
+    return reservoir
+
+
+def sample(iterable, k, weights=None, *, counts=None, strict=False):
     """Return a *k*-length list of elements chosen (without replacement)
-    from the *iterable*. Like :func:`random.sample`, but works on iterables
-    of unknown length.
+    from the *iterable*.
+
+    Similar to :func:`random.sample`, but works on inputs that aren't
+    indexable (such as sets and dictionaries) and on inputs where the
+    size isn't known in advance (such as generators).
 
     >>> iterable = range(100)
     >>> sample(iterable, 5)  # doctest: +SKIP
     [81, 60, 96, 16, 4]
 
-    An iterable with *weights* may also be given:
+    For iterables with repeated elements, you may supply *counts* to
+    indicate the repeats.
+
+    >>> iterable = ['a', 'b']
+    >>> counts = [3, 4]  # Equivalent to 'a', 'a', 'a', 'b', 'b', 'b', 'b'
+    >>> sample(iterable, k=3, counts=counts)  # doctest: +SKIP
+    ['a', 'a', 'b']
+
+    An iterable with *weights* may be given:
 
     >>> iterable = range(100)
     >>> weights = (i * i + 1 for i in range(100))
     >>> sampled = sample(iterable, 5, weights=weights)  # doctest: +SKIP
     [79, 67, 74, 66, 78]
 
-    The algorithm can also be used to generate weighted random permutations.
-    The relative weight of each item determines the probability that it
-    appears late in the permutation.
+    Weighted selections are made without replacement.
+    After an element is selected, it is removed from the pool and the
+    relative weights of the other elements increase (this
+    does not match the behavior of :func:`random.sample`'s *counts*
+    parameter). Note that *weights* may not be used with *counts*.
+
+    If the length of *iterable* is less than *k*,
+    ``ValueError`` is raised if *strict* is ``True`` and
+    all elements are returned (in shuffled order) if *strict* is ``False``.
+
+    By default, the `Algorithm L `__ reservoir sampling
+    technique is used. When *weights* are provided,
+    `Algorithm A-ExpJ `__ is used instead.
+
+    Notes on reproducibility:
+
+    * The algorithms rely on inexact floating-point functions provided
+      by the underlying math library (e.g. ``log``, ``log1p``, and ``pow``).
+      Those functions can `produce slightly different results
+      `_ on
+      different builds.  Accordingly, selections can vary across builds
+      even for the same seed.
+
+    * The algorithms loop over the input and make selections based on
+      ordinal position, so selections from unordered collections (such as
+      sets) won't reproduce across sessions on the same platform using the
+      same seed.  For example, this won't reproduce::
+
+          >> seed(8675309)
+          >> sample(set('abcdefghijklmnopqrstuvwxyz'), 10)
+          ['c', 'p', 'e', 'w', 's', 'a', 'j', 'd', 'n', 't']
 
-    >>> data = "abcdefgh"
-    >>> weights = range(1, len(data) + 1)
-    >>> sample(data, k=len(data), weights=weights)  # doctest: +SKIP
-    ['c', 'a', 'b', 'e', 'g', 'd', 'h', 'f']
     """
+    iterator = iter(iterable)
+
+    if k < 0:
+        raise ValueError('k must be non-negative')
+
     if k == 0:
         return []
 
-    iterable = iter(iterable)
-    if weights is None:
-        return _sample_unweighted(iterable, k)
-    else:
+    if weights is not None and counts is not None:
+        raise TypeError('weights and counts are mutually exclusive')
+
+    elif weights is not None:
         weights = iter(weights)
-        return _sample_weighted(iterable, k, weights)
+        return _sample_weighted(iterator, k, weights, strict)
+
+    elif counts is not None:
+        counts = iter(counts)
+        return _sample_counted(iterator, k, counts, strict)
+
+    else:
+        return _sample_unweighted(iterator, k, strict)
 
 
-def is_sorted(iterable, key=None, reverse=False):
+def is_sorted(iterable, key=None, reverse=False, strict=False):
     """Returns ``True`` if the items of iterable are in sorted order, and
     ``False`` otherwise. *key* and *reverse* have the same meaning that they do
     in the built-in :func:`sorted` function.
@@ -3383,13 +3966,26 @@ def is_sorted(iterable, key=None, reverse=False):
     >>> is_sorted([5, 4, 3, 1, 2], reverse=True)
     False
 
+    If *strict*, tests for strict sorting, that is, returns ``False`` if equal
+    elements are found:
+
+    >>> is_sorted([1, 2, 2])
+    True
+    >>> is_sorted([1, 2, 2], strict=True)
+    False
+
     The function returns ``False`` after encountering the first out-of-order
-    item. If there are no out-of-order items, the iterable is exhausted.
+    item, which means it may produce results that differ from the built-in
+    :func:`sorted` function for objects with unusual comparison dynamics
+    (like ``math.nan``). If there are no out-of-order items, the iterable is
+    exhausted.
     """
-
-    compare = lt if reverse else gt
     it = iterable if (key is None) else map(key, iterable)
-    return not any(starmap(compare, pairwise(it)))
+    a, b = tee(it)
+    next(b, None)
+    if reverse:
+        b, a = a, b
+    return all(map(lt, a, b)) if strict else not any(map(lt, b, a))
 
 
 class AbortThread(BaseException):
@@ -3453,7 +4049,10 @@ def __init__(self, func, callback_kwd='callback', wait_seconds=0.1):
         self._aborted = False
         self._future = None
         self._wait_seconds = wait_seconds
-        self._executor = __import__("concurrent.futures").futures.ThreadPoolExecutor(max_workers=1)
+        # Lazily import concurrent.future
+        self._executor = __import__(
+            'concurrent.futures'
+        ).futures.ThreadPoolExecutor(max_workers=1)
         self._iterator = self._reader()
 
     def __enter__(self):
@@ -3649,7 +4248,8 @@ def nth_permutation(iterable, r, index):
     elif not 0 <= r < n:
         raise ValueError
     else:
-        c = factorial(n) // factorial(n - r)
+        c = perm(n, r)
+    assert c > 0  # factorial(n)>0, and r>> nth_combination_with_replacement(range(5), 3, 5)
+        (0, 1, 1)
+
+    ``ValueError`` will be raised If *r* is negative or greater than the length
+    of *iterable*.
+    ``IndexError`` will be raised if the given *index* is invalid.
+    """
+    pool = tuple(iterable)
+    n = len(pool)
+    if (r < 0) or (r > n):
+        raise ValueError
+
+    c = comb(n + r - 1, r)
+
+    if index < 0:
+        index += c
+
+    if (index < 0) or (index >= c):
+        raise IndexError
+
+    result = []
+    i = 0
+    while r:
+        r -= 1
+        while n >= 0:
+            num_combs = comb(n + r - 1, r)
+            if index < num_combs:
+                break
+            n -= 1
+            i += 1
+            index -= num_combs
+        result.append(pool[i])
+
+    return tuple(result)
+
+
 def value_chain(*args):
     """Yield all arguments passed to the function in the same order in which
     they were passed. If an argument itself is iterable then iterate over its
@@ -3686,6 +4329,12 @@ def value_chain(*args):
         >>> list(value_chain('12', '34', ['56', '78']))
         ['12', '34', '56', '78']
 
+    Pre- or postpend a single element to an iterable:
+
+        >>> list(value_chain(1, [2, 3, 4, 5, 6]))
+        [1, 2, 3, 4, 5, 6]
+        >>> list(value_chain([1, 2, 3, 4, 5], 6))
+        [1, 2, 3, 4, 5, 6]
 
     Multiple levels of nesting are not flattened.
 
@@ -3758,14 +4407,71 @@ def combination_index(element, iterable):
 
     n, _ = last(pool, default=(n, None))
 
-    # Python versiosn below 3.8 don't have math.comb
+    # Python versions below 3.8 don't have math.comb
     index = 1
     for i, j in enumerate(reversed(indexes), start=1):
         j = n - j
         if i <= j:
-            index += factorial(j) // (factorial(i) * factorial(j - i))
+            index += comb(j, i)
+
+    return comb(n + 1, k + 1) - index
+
+
+def combination_with_replacement_index(element, iterable):
+    """Equivalent to
+    ``list(combinations_with_replacement(iterable, r)).index(element)``
+
+    The subsequences with repetition of *iterable* that are of length *r* can
+    be ordered lexicographically. :func:`combination_with_replacement_index`
+    computes the index of the first *element*, without computing the previous
+    combinations with replacement.
+
+        >>> combination_with_replacement_index('adf', 'abcdefg')
+        20
+
+    ``ValueError`` will be raised if the given *element* isn't one of the
+    combinations with replacement of *iterable*.
+    """
+    element = tuple(element)
+    l = len(element)
+    element = enumerate(element)
+
+    k, y = next(element, (None, None))
+    if k is None:
+        return 0
+
+    indexes = []
+    pool = tuple(iterable)
+    for n, x in enumerate(pool):
+        while x == y:
+            indexes.append(n)
+            tmp, y = next(element, (None, None))
+            if tmp is None:
+                break
+            else:
+                k = tmp
+        if y is None:
+            break
+    else:
+        raise ValueError(
+            'element is not a combination with replacement of iterable'
+        )
+
+    n = len(pool)
+    occupations = [0] * n
+    for p in indexes:
+        occupations[p] += 1
+
+    index = 0
+    cumulative_sum = 0
+    for k in range(1, n):
+        cumulative_sum += occupations[k - 1]
+        j = l + n - 1 - k - cumulative_sum
+        i = n - k
+        if i <= j:
+            index += comb(j, i)
 
-    return factorial(n + 1) // (factorial(k + 1) * factorial(n - k)) - index
+    return index
 
 
 def permutation_index(element, iterable):
@@ -3811,14 +4517,787 @@ class countable:
     """
 
     def __init__(self, iterable):
-        self._it = iter(iterable)
+        self._iterator = iter(iterable)
         self.items_seen = 0
 
     def __iter__(self):
         return self
 
     def __next__(self):
-        item = next(self._it)
+        item = next(self._iterator)
         self.items_seen += 1
 
         return item
+
+
+def chunked_even(iterable, n):
+    """Break *iterable* into lists of approximately length *n*.
+    Items are distributed such the lengths of the lists differ by at most
+    1 item.
+
+    >>> iterable = [1, 2, 3, 4, 5, 6, 7]
+    >>> n = 3
+    >>> list(chunked_even(iterable, n))  # List lengths: 3, 2, 2
+    [[1, 2, 3], [4, 5], [6, 7]]
+    >>> list(chunked(iterable, n))  # List lengths: 3, 3, 1
+    [[1, 2, 3], [4, 5, 6], [7]]
+
+    """
+    iterator = iter(iterable)
+
+    # Initialize a buffer to process the chunks while keeping
+    # some back to fill any underfilled chunks
+    min_buffer = (n - 1) * (n - 2)
+    buffer = list(islice(iterator, min_buffer))
+
+    # Append items until we have a completed chunk
+    for _ in islice(map(buffer.append, iterator), n, None, n):
+        yield buffer[:n]
+        del buffer[:n]
+
+    # Check if any chunks need addition processing
+    if not buffer:
+        return
+    length = len(buffer)
+
+    # Chunks are either size `full_size <= n` or `partial_size = full_size - 1`
+    q, r = divmod(length, n)
+    num_lists = q + (1 if r > 0 else 0)
+    q, r = divmod(length, num_lists)
+    full_size = q + (1 if r > 0 else 0)
+    partial_size = full_size - 1
+    num_full = length - partial_size * num_lists
+
+    # Yield chunks of full size
+    partial_start_idx = num_full * full_size
+    if full_size > 0:
+        for i in range(0, partial_start_idx, full_size):
+            yield buffer[i : i + full_size]
+
+    # Yield chunks of partial size
+    if partial_size > 0:
+        for i in range(partial_start_idx, length, partial_size):
+            yield buffer[i : i + partial_size]
+
+
+def zip_broadcast(*objects, scalar_types=(str, bytes), strict=False):
+    """A version of :func:`zip` that "broadcasts" any scalar
+    (i.e., non-iterable) items into output tuples.
+
+    >>> iterable_1 = [1, 2, 3]
+    >>> iterable_2 = ['a', 'b', 'c']
+    >>> scalar = '_'
+    >>> list(zip_broadcast(iterable_1, iterable_2, scalar))
+    [(1, 'a', '_'), (2, 'b', '_'), (3, 'c', '_')]
+
+    The *scalar_types* keyword argument determines what types are considered
+    scalar. It is set to ``(str, bytes)`` by default. Set it to ``None`` to
+    treat strings and byte strings as iterable:
+
+    >>> list(zip_broadcast('abc', 0, 'xyz', scalar_types=None))
+    [('a', 0, 'x'), ('b', 0, 'y'), ('c', 0, 'z')]
+
+    If the *strict* keyword argument is ``True``, then
+    ``UnequalIterablesError`` will be raised if any of the iterables have
+    different lengths.
+    """
+
+    def is_scalar(obj):
+        if scalar_types and isinstance(obj, scalar_types):
+            return True
+        try:
+            iter(obj)
+        except TypeError:
+            return True
+        else:
+            return False
+
+    size = len(objects)
+    if not size:
+        return
+
+    new_item = [None] * size
+    iterables, iterable_positions = [], []
+    for i, obj in enumerate(objects):
+        if is_scalar(obj):
+            new_item[i] = obj
+        else:
+            iterables.append(iter(obj))
+            iterable_positions.append(i)
+
+    if not iterables:
+        yield tuple(objects)
+        return
+
+    zipper = _zip_equal if strict else zip
+    for item in zipper(*iterables):
+        for i, new_item[i] in zip(iterable_positions, item):
+            pass
+        yield tuple(new_item)
+
+
+def unique_in_window(iterable, n, key=None):
+    """Yield the items from *iterable* that haven't been seen recently.
+    *n* is the size of the lookback window.
+
+        >>> iterable = [0, 1, 0, 2, 3, 0]
+        >>> n = 3
+        >>> list(unique_in_window(iterable, n))
+        [0, 1, 2, 3, 0]
+
+    The *key* function, if provided, will be used to determine uniqueness:
+
+        >>> list(unique_in_window('abAcda', 3, key=lambda x: x.lower()))
+        ['a', 'b', 'c', 'd', 'a']
+
+    The items in *iterable* must be hashable.
+
+    """
+    if n <= 0:
+        raise ValueError('n must be greater than 0')
+
+    window = deque(maxlen=n)
+    counts = defaultdict(int)
+    use_key = key is not None
+
+    for item in iterable:
+        if len(window) == n:
+            to_discard = window[0]
+            if counts[to_discard] == 1:
+                del counts[to_discard]
+            else:
+                counts[to_discard] -= 1
+
+        k = key(item) if use_key else item
+        if k not in counts:
+            yield item
+        counts[k] += 1
+        window.append(k)
+
+
+def duplicates_everseen(iterable, key=None):
+    """Yield duplicate elements after their first appearance.
+
+    >>> list(duplicates_everseen('mississippi'))
+    ['s', 'i', 's', 's', 'i', 'p', 'i']
+    >>> list(duplicates_everseen('AaaBbbCccAaa', str.lower))
+    ['a', 'a', 'b', 'b', 'c', 'c', 'A', 'a', 'a']
+
+    This function is analogous to :func:`unique_everseen` and is subject to
+    the same performance considerations.
+
+    """
+    seen_set = set()
+    seen_list = []
+    use_key = key is not None
+
+    for element in iterable:
+        k = key(element) if use_key else element
+        try:
+            if k not in seen_set:
+                seen_set.add(k)
+            else:
+                yield element
+        except TypeError:
+            if k not in seen_list:
+                seen_list.append(k)
+            else:
+                yield element
+
+
+def duplicates_justseen(iterable, key=None):
+    """Yields serially-duplicate elements after their first appearance.
+
+    >>> list(duplicates_justseen('mississippi'))
+    ['s', 's', 'p']
+    >>> list(duplicates_justseen('AaaBbbCccAaa', str.lower))
+    ['a', 'a', 'b', 'b', 'c', 'c', 'a', 'a']
+
+    This function is analogous to :func:`unique_justseen`.
+
+    """
+    return flatten(g for _, g in groupby(iterable, key) for _ in g)
+
+
+def classify_unique(iterable, key=None):
+    """Classify each element in terms of its uniqueness.
+
+    For each element in the input iterable, return a 3-tuple consisting of:
+
+    1. The element itself
+    2. ``False`` if the element is equal to the one preceding it in the input,
+       ``True`` otherwise (i.e. the equivalent of :func:`unique_justseen`)
+    3. ``False`` if this element has been seen anywhere in the input before,
+       ``True`` otherwise (i.e. the equivalent of :func:`unique_everseen`)
+
+    >>> list(classify_unique('otto'))    # doctest: +NORMALIZE_WHITESPACE
+    [('o', True,  True),
+     ('t', True,  True),
+     ('t', False, False),
+     ('o', True,  False)]
+
+    This function is analogous to :func:`unique_everseen` and is subject to
+    the same performance considerations.
+
+    """
+    seen_set = set()
+    seen_list = []
+    use_key = key is not None
+    previous = None
+
+    for i, element in enumerate(iterable):
+        k = key(element) if use_key else element
+        is_unique_justseen = not i or previous != k
+        previous = k
+        is_unique_everseen = False
+        try:
+            if k not in seen_set:
+                seen_set.add(k)
+                is_unique_everseen = True
+        except TypeError:
+            if k not in seen_list:
+                seen_list.append(k)
+                is_unique_everseen = True
+        yield element, is_unique_justseen, is_unique_everseen
+
+
+def minmax(iterable_or_value, *others, key=None, default=_marker):
+    """Returns both the smallest and largest items from an iterable
+    or from two or more arguments.
+
+        >>> minmax([3, 1, 5])
+        (1, 5)
+
+        >>> minmax(4, 2, 6)
+        (2, 6)
+
+    If a *key* function is provided, it will be used to transform the input
+    items for comparison.
+
+        >>> minmax([5, 30], key=str)  # '30' sorts before '5'
+        (30, 5)
+
+    If a *default* value is provided, it will be returned if there are no
+    input items.
+
+        >>> minmax([], default=(0, 0))
+        (0, 0)
+
+    Otherwise ``ValueError`` is raised.
+
+    This function makes a single pass over the input elements and takes care to
+    minimize the number of comparisons made during processing.
+
+    Note that unlike the builtin ``max`` function, which always returns the first
+    item with the maximum value, this function may return another item when there are
+    ties.
+
+    This function is based on the
+    `recipe `__ by
+    Raymond Hettinger.
+    """
+    iterable = (iterable_or_value, *others) if others else iterable_or_value
+
+    it = iter(iterable)
+
+    try:
+        lo = hi = next(it)
+    except StopIteration as exc:
+        if default is _marker:
+            raise ValueError(
+                '`minmax()` argument is an empty iterable. '
+                'Provide a `default` value to suppress this error.'
+            ) from exc
+        return default
+
+    # Different branches depending on the presence of key. This saves a lot
+    # of unimportant copies which would slow the "key=None" branch
+    # significantly down.
+    if key is None:
+        for x, y in zip_longest(it, it, fillvalue=lo):
+            if y < x:
+                x, y = y, x
+            if x < lo:
+                lo = x
+            if hi < y:
+                hi = y
+
+    else:
+        lo_key = hi_key = key(lo)
+
+        for x, y in zip_longest(it, it, fillvalue=lo):
+            x_key, y_key = key(x), key(y)
+
+            if y_key < x_key:
+                x, y, x_key, y_key = y, x, y_key, x_key
+            if x_key < lo_key:
+                lo, lo_key = x, x_key
+            if hi_key < y_key:
+                hi, hi_key = y, y_key
+
+    return lo, hi
+
+
+def constrained_batches(
+    iterable, max_size, max_count=None, get_len=len, strict=True
+):
+    """Yield batches of items from *iterable* with a combined size limited by
+    *max_size*.
+
+    >>> iterable = [b'12345', b'123', b'12345678', b'1', b'1', b'12', b'1']
+    >>> list(constrained_batches(iterable, 10))
+    [(b'12345', b'123'), (b'12345678', b'1', b'1'), (b'12', b'1')]
+
+    If a *max_count* is supplied, the number of items per batch is also
+    limited:
+
+    >>> iterable = [b'12345', b'123', b'12345678', b'1', b'1', b'12', b'1']
+    >>> list(constrained_batches(iterable, 10, max_count = 2))
+    [(b'12345', b'123'), (b'12345678', b'1'), (b'1', b'12'), (b'1',)]
+
+    If a *get_len* function is supplied, use that instead of :func:`len` to
+    determine item size.
+
+    If *strict* is ``True``, raise ``ValueError`` if any single item is bigger
+    than *max_size*. Otherwise, allow single items to exceed *max_size*.
+    """
+    if max_size <= 0:
+        raise ValueError('maximum size must be greater than zero')
+
+    batch = []
+    batch_size = 0
+    batch_count = 0
+    for item in iterable:
+        item_len = get_len(item)
+        if strict and item_len > max_size:
+            raise ValueError('item size exceeds maximum size')
+
+        reached_count = batch_count == max_count
+        reached_size = item_len + batch_size > max_size
+        if batch_count and (reached_size or reached_count):
+            yield tuple(batch)
+            batch.clear()
+            batch_size = 0
+            batch_count = 0
+
+        batch.append(item)
+        batch_size += item_len
+        batch_count += 1
+
+    if batch:
+        yield tuple(batch)
+
+
+def gray_product(*iterables):
+    """Like :func:`itertools.product`, but return tuples in an order such
+    that only one element in the generated tuple changes from one iteration
+    to the next.
+
+        >>> list(gray_product('AB','CD'))
+        [('A', 'C'), ('B', 'C'), ('B', 'D'), ('A', 'D')]
+
+    This function consumes all of the input iterables before producing output.
+    If any of the input iterables have fewer than two items, ``ValueError``
+    is raised.
+
+    For information on the algorithm, see
+    `this section `__
+    of Donald Knuth's *The Art of Computer Programming*.
+    """
+    all_iterables = tuple(tuple(x) for x in iterables)
+    iterable_count = len(all_iterables)
+    for iterable in all_iterables:
+        if len(iterable) < 2:
+            raise ValueError("each iterable must have two or more items")
+
+    # This is based on "Algorithm H" from section 7.2.1.1, page 20.
+    # a holds the indexes of the source iterables for the n-tuple to be yielded
+    # f is the array of "focus pointers"
+    # o is the array of "directions"
+    a = [0] * iterable_count
+    f = list(range(iterable_count + 1))
+    o = [1] * iterable_count
+    while True:
+        yield tuple(all_iterables[i][a[i]] for i in range(iterable_count))
+        j = f[0]
+        f[0] = 0
+        if j == iterable_count:
+            break
+        a[j] = a[j] + o[j]
+        if a[j] == 0 or a[j] == len(all_iterables[j]) - 1:
+            o[j] = -o[j]
+            f[j] = f[j + 1]
+            f[j + 1] = j + 1
+
+
+def partial_product(*iterables):
+    """Yields tuples containing one item from each iterator, with subsequent
+    tuples changing a single item at a time by advancing each iterator until it
+    is exhausted. This sequence guarantees every value in each iterable is
+    output at least once without generating all possible combinations.
+
+    This may be useful, for example, when testing an expensive function.
+
+        >>> list(partial_product('AB', 'C', 'DEF'))
+        [('A', 'C', 'D'), ('B', 'C', 'D'), ('B', 'C', 'E'), ('B', 'C', 'F')]
+    """
+
+    iterators = list(map(iter, iterables))
+
+    try:
+        prod = [next(it) for it in iterators]
+    except StopIteration:
+        return
+    yield tuple(prod)
+
+    for i, it in enumerate(iterators):
+        for prod[i] in it:
+            yield tuple(prod)
+
+
+def takewhile_inclusive(predicate, iterable):
+    """A variant of :func:`takewhile` that yields one additional element.
+
+        >>> list(takewhile_inclusive(lambda x: x < 5, [1, 4, 6, 4, 1]))
+        [1, 4, 6]
+
+    :func:`takewhile` would return ``[1, 4]``.
+    """
+    for x in iterable:
+        yield x
+        if not predicate(x):
+            break
+
+
+def outer_product(func, xs, ys, *args, **kwargs):
+    """A generalized outer product that applies a binary function to all
+    pairs of items. Returns a 2D matrix with ``len(xs)`` rows and ``len(ys)``
+    columns.
+    Also accepts ``*args`` and ``**kwargs`` that are passed to ``func``.
+
+    Multiplication table:
+
+    >>> list(outer_product(mul, range(1, 4), range(1, 6)))
+    [(1, 2, 3, 4, 5), (2, 4, 6, 8, 10), (3, 6, 9, 12, 15)]
+
+    Cross tabulation:
+
+    >>> xs = ['A', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B']
+    >>> ys = ['X', 'X', 'X', 'Y', 'Z', 'Z', 'Y', 'Y', 'Z', 'Z']
+    >>> pair_counts = Counter(zip(xs, ys))
+    >>> count_rows = lambda x, y: pair_counts[x, y]
+    >>> list(outer_product(count_rows, sorted(set(xs)), sorted(set(ys))))
+    [(2, 3, 0), (1, 0, 4)]
+
+    Usage with ``*args`` and ``**kwargs``:
+
+    >>> animals = ['cat', 'wolf', 'mouse']
+    >>> list(outer_product(min, animals, animals, key=len))
+    [('cat', 'cat', 'cat'), ('cat', 'wolf', 'wolf'), ('cat', 'wolf', 'mouse')]
+    """
+    ys = tuple(ys)
+    return batched(
+        starmap(lambda x, y: func(x, y, *args, **kwargs), product(xs, ys)),
+        n=len(ys),
+    )
+
+
+def iter_suppress(iterable, *exceptions):
+    """Yield each of the items from *iterable*. If the iteration raises one of
+    the specified *exceptions*, that exception will be suppressed and iteration
+    will stop.
+
+    >>> from itertools import chain
+    >>> def breaks_at_five(x):
+    ...     while True:
+    ...         if x >= 5:
+    ...             raise RuntimeError
+    ...         yield x
+    ...         x += 1
+    >>> it_1 = iter_suppress(breaks_at_five(1), RuntimeError)
+    >>> it_2 = iter_suppress(breaks_at_five(2), RuntimeError)
+    >>> list(chain(it_1, it_2))
+    [1, 2, 3, 4, 2, 3, 4]
+    """
+    try:
+        yield from iterable
+    except exceptions:
+        return
+
+
+def filter_map(func, iterable):
+    """Apply *func* to every element of *iterable*, yielding only those which
+    are not ``None``.
+
+    >>> elems = ['1', 'a', '2', 'b', '3']
+    >>> list(filter_map(lambda s: int(s) if s.isnumeric() else None, elems))
+    [1, 2, 3]
+    """
+    for x in iterable:
+        y = func(x)
+        if y is not None:
+            yield y
+
+
+def powerset_of_sets(iterable):
+    """Yields all possible subsets of the iterable.
+
+        >>> list(powerset_of_sets([1, 2, 3]))  # doctest: +SKIP
+        [set(), {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}]
+        >>> list(powerset_of_sets([1, 1, 0]))  # doctest: +SKIP
+        [set(), {1}, {0}, {0, 1}]
+
+    :func:`powerset_of_sets` takes care to minimize the number
+    of hash operations performed.
+    """
+    sets = tuple(dict.fromkeys(map(frozenset, zip(iterable))))
+    return chain.from_iterable(
+        starmap(set().union, combinations(sets, r))
+        for r in range(len(sets) + 1)
+    )
+
+
+def join_mappings(**field_to_map):
+    """
+    Joins multiple mappings together using their common keys.
+
+    >>> user_scores = {'elliot': 50, 'claris': 60}
+    >>> user_times = {'elliot': 30, 'claris': 40}
+    >>> join_mappings(score=user_scores, time=user_times)
+    {'elliot': {'score': 50, 'time': 30}, 'claris': {'score': 60, 'time': 40}}
+    """
+    ret = defaultdict(dict)
+
+    for field_name, mapping in field_to_map.items():
+        for key, value in mapping.items():
+            ret[key][field_name] = value
+
+    return dict(ret)
+
+
+def _complex_sumprod(v1, v2):
+    """High precision sumprod() for complex numbers.
+    Used by :func:`dft` and :func:`idft`.
+    """
+
+    real = attrgetter('real')
+    imag = attrgetter('imag')
+    r1 = chain(map(real, v1), map(neg, map(imag, v1)))
+    r2 = chain(map(real, v2), map(imag, v2))
+    i1 = chain(map(real, v1), map(imag, v1))
+    i2 = chain(map(imag, v2), map(real, v2))
+    return complex(_fsumprod(r1, r2), _fsumprod(i1, i2))
+
+
+def dft(xarr):
+    """Discrete Fourier Transform. *xarr* is a sequence of complex numbers.
+    Yields the components of the corresponding transformed output vector.
+
+    >>> import cmath
+    >>> xarr = [1, 2-1j, -1j, -1+2j]  # time domain
+    >>> Xarr = [2, -2-2j, -2j, 4+4j]  # frequency domain
+    >>> magnitudes, phases = zip(*map(cmath.polar, Xarr))
+    >>> all(map(cmath.isclose, dft(xarr), Xarr))
+    True
+
+    Inputs are restricted to numeric types that can add and multiply
+    with a complex number.  This includes int, float, complex, and
+    Fraction, but excludes Decimal.
+
+    See :func:`idft` for the inverse Discrete Fourier Transform.
+    """
+    N = len(xarr)
+    roots_of_unity = [e ** (n / N * tau * -1j) for n in range(N)]
+    for k in range(N):
+        coeffs = [roots_of_unity[k * n % N] for n in range(N)]
+        yield _complex_sumprod(xarr, coeffs)
+
+
+def idft(Xarr):
+    """Inverse Discrete Fourier Transform. *Xarr* is a sequence of
+    complex numbers. Yields the components of the corresponding
+    inverse-transformed output vector.
+
+    >>> import cmath
+    >>> xarr = [1, 2-1j, -1j, -1+2j]  # time domain
+    >>> Xarr = [2, -2-2j, -2j, 4+4j]  # frequency domain
+    >>> all(map(cmath.isclose, idft(Xarr), xarr))
+    True
+
+    Inputs are restricted to numeric types that can add and multiply
+    with a complex number.  This includes int, float, complex, and
+    Fraction, but excludes Decimal.
+
+    See :func:`dft` for the Discrete Fourier Transform.
+    """
+    N = len(Xarr)
+    roots_of_unity = [e ** (n / N * tau * 1j) for n in range(N)]
+    for k in range(N):
+        coeffs = [roots_of_unity[k * n % N] for n in range(N)]
+        yield _complex_sumprod(Xarr, coeffs) / N
+
+
+def doublestarmap(func, iterable):
+    """Apply *func* to every item of *iterable* by dictionary unpacking
+    the item into *func*.
+
+    The difference between :func:`itertools.starmap` and :func:`doublestarmap`
+    parallels the distinction between ``func(*a)`` and ``func(**a)``.
+
+    >>> iterable = [{'a': 1, 'b': 2}, {'a': 40, 'b': 60}]
+    >>> list(doublestarmap(lambda a, b: a + b, iterable))
+    [3, 100]
+
+    ``TypeError`` will be raised if *func*'s signature doesn't match the
+    mapping contained in *iterable* or if *iterable* does not contain mappings.
+    """
+    for item in iterable:
+        yield func(**item)
+
+
+def _nth_prime_bounds(n):
+    """Bounds for the nth prime (counting from 1): lb < p_n < ub."""
+    # At and above 688,383, the lb/ub spread is under 0.003 * p_n.
+
+    if n < 1:
+        raise ValueError
+
+    if n < 6:
+        return (n, 2.25 * n)
+
+    # https://en.wikipedia.org/wiki/Prime-counting_function#Inequalities
+    upper_bound = n * log(n * log(n))
+    lower_bound = upper_bound - n
+    if n >= 688_383:
+        upper_bound -= n * (1.0 - (log(log(n)) - 2.0) / log(n))
+
+    return lower_bound, upper_bound
+
+
+def nth_prime(n, *, approximate=False):
+    """Return the nth prime (counting from 0).
+
+    >>> nth_prime(0)
+    2
+    >>> nth_prime(100)
+    547
+
+    If *approximate* is set to True, will return a prime close
+    to the nth prime.  The estimation is much faster than computing
+    an exact result.
+
+    >>> nth_prime(200_000_000, approximate=True)  # Exact result is 4222234763
+    4217820427
+
+    """
+    lb, ub = _nth_prime_bounds(n + 1)
+
+    if not approximate or n <= 1_000_000:
+        return nth(sieve(ceil(ub)), n)
+
+    # Search from the midpoint and return the first odd prime
+    odd = floor((lb + ub) / 2) | 1
+    return first_true(count(odd, step=2), pred=is_prime)
+
+
+def argmin(iterable, *, key=None):
+    """
+    Index of the first occurrence of a minimum value in an iterable.
+
+        >>> argmin('efghabcdijkl')
+        4
+        >>> argmin([3, 2, 1, 0, 4, 2, 1, 0])
+        3
+
+    For example, look up a label corresponding to the position
+    of a value that minimizes a cost function::
+
+        >>> def cost(x):
+        ...     "Days for a wound to heal given a subject's age."
+        ...     return x**2 - 20*x + 150
+        ...
+        >>> labels =  ['homer', 'marge', 'bart', 'lisa', 'maggie']
+        >>> ages =    [  35,      30,      10,      9,      1    ]
+
+        # Fastest healing family member
+        >>> labels[argmin(ages, key=cost)]
+        'bart'
+
+        # Age with fastest healing
+        >>> min(ages, key=cost)
+        10
+
+    """
+    if key is not None:
+        iterable = map(key, iterable)
+    return min(enumerate(iterable), key=itemgetter(1))[0]
+
+
+def argmax(iterable, *, key=None):
+    """
+    Index of the first occurrence of a maximum value in an iterable.
+
+        >>> argmax('abcdefghabcd')
+        7
+        >>> argmax([0, 1, 2, 3, 3, 2, 1, 0])
+        3
+
+    For example, identify the best machine learning model::
+
+        >>> models =   ['svm', 'random forest', 'knn', 'naïve bayes']
+        >>> accuracy = [  68,        61,          84,       72      ]
+
+        # Most accurate model
+        >>> models[argmax(accuracy)]
+        'knn'
+
+        # Best accuracy
+        >>> max(accuracy)
+        84
+
+    """
+    if key is not None:
+        iterable = map(key, iterable)
+    return max(enumerate(iterable), key=itemgetter(1))[0]
+
+
+def extract(iterable, indices):
+    """Yield values at the specified indices.
+
+    Example:
+
+        >>> data = 'abcdefghijklmnopqrstuvwxyz'
+        >>> list(extract(data, [7, 4, 11, 11, 14]))
+        ['h', 'e', 'l', 'l', 'o']
+
+    The *iterable* is consumed lazily and can be infinite.
+    The *indices* are consumed immediately and must be finite.
+
+    Raises ``IndexError`` if an index lies beyond the iterable.
+    Raises ``ValueError`` for negative indices.
+    """
+
+    iterator = iter(iterable)
+    index_and_position = sorted(zip(indices, count()))
+
+    if index_and_position and index_and_position[0][0] < 0:
+        raise ValueError('Indices must be non-negative')
+
+    buffer = {}
+    iterator_position = -1
+    next_to_emit = 0
+
+    for index, order in index_and_position:
+        advance = index - iterator_position
+        if advance:
+            try:
+                value = next(islice(iterator, advance - 1, None))
+            except StopIteration:
+                raise IndexError(index)
+            iterator_position = index
+
+        buffer[order] = value
+
+        while next_to_emit in buffer:
+            yield buffer.pop(next_to_emit)
+            next_to_emit += 1
diff --git a/setuptools/_vendor/more_itertools/more.pyi b/setuptools/_vendor/more_itertools/more.pyi
index 2fba9cb300..b5e33f8b74 100644
--- a/setuptools/_vendor/more_itertools/more.pyi
+++ b/setuptools/_vendor/more_itertools/more.pyi
@@ -1,35 +1,169 @@
 """Stubs for more_itertools.more"""
 
-from typing import (
-    Any,
-    Callable,
+from __future__ import annotations
+
+import sys
+import types
+
+from collections.abc import (
     Container,
-    Dict,
-    Generic,
     Hashable,
     Iterable,
     Iterator,
-    List,
-    Optional,
+    Mapping,
     Reversible,
     Sequence,
     Sized,
-    Tuple,
-    Union,
+)
+from contextlib import AbstractContextManager
+from typing import (
+    Any,
+    Callable,
+    Generic,
     TypeVar,
+    overload,
     type_check_only,
 )
-from types import TracebackType
-from typing_extensions import ContextManager, Protocol, Type, overload
+from typing_extensions import Protocol
+
+__all__ = [
+    'AbortThread',
+    'SequenceView',
+    'UnequalIterablesError',
+    'adjacent',
+    'all_unique',
+    'always_iterable',
+    'always_reversible',
+    'argmax',
+    'argmin',
+    'bucket',
+    'callback_iter',
+    'chunked',
+    'chunked_even',
+    'circular_shifts',
+    'collapse',
+    'combination_index',
+    'combination_with_replacement_index',
+    'consecutive_groups',
+    'constrained_batches',
+    'consumer',
+    'count_cycle',
+    'countable',
+    'derangements',
+    'dft',
+    'difference',
+    'distinct_combinations',
+    'distinct_permutations',
+    'distribute',
+    'divide',
+    'doublestarmap',
+    'duplicates_everseen',
+    'duplicates_justseen',
+    'classify_unique',
+    'exactly_n',
+    'extract',
+    'filter_except',
+    'filter_map',
+    'first',
+    'gray_product',
+    'groupby_transform',
+    'ichunked',
+    'iequals',
+    'idft',
+    'ilen',
+    'interleave',
+    'interleave_evenly',
+    'interleave_longest',
+    'interleave_randomly',
+    'intersperse',
+    'is_sorted',
+    'islice_extended',
+    'iterate',
+    'iter_suppress',
+    'join_mappings',
+    'last',
+    'locate',
+    'longest_common_prefix',
+    'lstrip',
+    'make_decorator',
+    'map_except',
+    'map_if',
+    'map_reduce',
+    'mark_ends',
+    'minmax',
+    'nth_or_last',
+    'nth_permutation',
+    'nth_prime',
+    'nth_product',
+    'nth_combination_with_replacement',
+    'numeric_range',
+    'one',
+    'only',
+    'outer_product',
+    'padded',
+    'partial_product',
+    'partitions',
+    'peekable',
+    'permutation_index',
+    'powerset_of_sets',
+    'product_index',
+    'raise_',
+    'repeat_each',
+    'repeat_last',
+    'replace',
+    'rlocate',
+    'rstrip',
+    'run_length',
+    'sample',
+    'seekable',
+    'set_partitions',
+    'side_effect',
+    'sliced',
+    'sort_together',
+    'split_after',
+    'split_at',
+    'split_before',
+    'split_into',
+    'split_when',
+    'spy',
+    'stagger',
+    'strip',
+    'strictly_n',
+    'substrings',
+    'substrings_indexes',
+    'takewhile_inclusive',
+    'time_limited',
+    'unique_in_window',
+    'unique_to_each',
+    'unzip',
+    'value_chain',
+    'windowed',
+    'windowed_complete',
+    'with_iter',
+    'zip_broadcast',
+    'zip_equal',
+    'zip_offset',
+]
 
 # Type and type variable definitions
 _T = TypeVar('_T')
+_T1 = TypeVar('_T1')
+_T2 = TypeVar('_T2')
+_T3 = TypeVar('_T3')
+_T4 = TypeVar('_T4')
+_T5 = TypeVar('_T5')
 _U = TypeVar('_U')
 _V = TypeVar('_V')
 _W = TypeVar('_W')
 _T_co = TypeVar('_T_co', covariant=True)
-_GenFn = TypeVar('_GenFn', bound=Callable[..., Iterator[object]])
-_Raisable = Union[BaseException, 'Type[BaseException]']
+_GenFn = TypeVar('_GenFn', bound=Callable[..., Iterator[Any]])
+_Raisable = BaseException | type[BaseException]
+
+# The type of isinstance's second argument (from typeshed builtins)
+if sys.version_info >= (3, 10):
+    _ClassInfo = type | types.UnionType | tuple[_ClassInfo, ...]
+else:
+    _ClassInfo = type | tuple[_ClassInfo, ...]
 
 @type_check_only
 class _SizedIterable(Protocol[_T_co], Sized, Iterable[_T_co]): ...
@@ -37,23 +171,25 @@ class _SizedIterable(Protocol[_T_co], Sized, Iterable[_T_co]): ...
 @type_check_only
 class _SizedReversible(Protocol[_T_co], Sized, Reversible[_T_co]): ...
 
+@type_check_only
+class _SupportsSlicing(Protocol[_T_co]):
+    def __getitem__(self, __k: slice) -> _T_co: ...
+
 def chunked(
-    iterable: Iterable[_T], n: int, strict: bool = ...
-) -> Iterator[List[_T]]: ...
+    iterable: Iterable[_T], n: int | None, strict: bool = ...
+) -> Iterator[list[_T]]: ...
 @overload
 def first(iterable: Iterable[_T]) -> _T: ...
 @overload
-def first(iterable: Iterable[_T], default: _U) -> Union[_T, _U]: ...
+def first(iterable: Iterable[_T], default: _U) -> _T | _U: ...
 @overload
 def last(iterable: Iterable[_T]) -> _T: ...
 @overload
-def last(iterable: Iterable[_T], default: _U) -> Union[_T, _U]: ...
+def last(iterable: Iterable[_T], default: _U) -> _T | _U: ...
 @overload
 def nth_or_last(iterable: Iterable[_T], n: int) -> _T: ...
 @overload
-def nth_or_last(
-    iterable: Iterable[_T], n: int, default: _U
-) -> Union[_T, _U]: ...
+def nth_or_last(iterable: Iterable[_T], n: int, default: _U) -> _T | _U: ...
 
 class peekable(Generic[_T], Iterator[_T]):
     def __init__(self, iterable: Iterable[_T]) -> None: ...
@@ -62,52 +198,61 @@ class peekable(Generic[_T], Iterator[_T]):
     @overload
     def peek(self) -> _T: ...
     @overload
-    def peek(self, default: _U) -> Union[_T, _U]: ...
+    def peek(self, default: _U) -> _T | _U: ...
     def prepend(self, *items: _T) -> None: ...
     def __next__(self) -> _T: ...
     @overload
     def __getitem__(self, index: int) -> _T: ...
     @overload
-    def __getitem__(self, index: slice) -> List[_T]: ...
+    def __getitem__(self, index: slice) -> list[_T]: ...
 
-def collate(*iterables: Iterable[_T], **kwargs: Any) -> Iterable[_T]: ...
 def consumer(func: _GenFn) -> _GenFn: ...
-def ilen(iterable: Iterable[object]) -> int: ...
+def ilen(iterable: Iterable[_T]) -> int: ...
 def iterate(func: Callable[[_T], _T], start: _T) -> Iterator[_T]: ...
 def with_iter(
-    context_manager: ContextManager[Iterable[_T]],
+    context_manager: AbstractContextManager[Iterable[_T]],
 ) -> Iterator[_T]: ...
 def one(
     iterable: Iterable[_T],
-    too_short: Optional[_Raisable] = ...,
-    too_long: Optional[_Raisable] = ...,
+    too_short: _Raisable | None = ...,
+    too_long: _Raisable | None = ...,
 ) -> _T: ...
+def raise_(exception: _Raisable, *args: Any) -> None: ...
+def strictly_n(
+    iterable: Iterable[_T],
+    n: int,
+    too_short: _GenFn | None = ...,
+    too_long: _GenFn | None = ...,
+) -> list[_T]: ...
 def distinct_permutations(
-    iterable: Iterable[_T], r: Optional[int] = ...
-) -> Iterator[Tuple[_T, ...]]: ...
+    iterable: Iterable[_T], r: int | None = ...
+) -> Iterator[tuple[_T, ...]]: ...
+def derangements(
+    iterable: Iterable[_T], r: int | None = None
+) -> Iterator[tuple[_T, ...]]: ...
 def intersperse(
     e: _U, iterable: Iterable[_T], n: int = ...
-) -> Iterator[Union[_T, _U]]: ...
-def unique_to_each(*iterables: Iterable[_T]) -> List[List[_T]]: ...
+) -> Iterator[_T | _U]: ...
+def unique_to_each(*iterables: Iterable[_T]) -> list[list[_T]]: ...
 @overload
 def windowed(
     seq: Iterable[_T], n: int, *, step: int = ...
-) -> Iterator[Tuple[Optional[_T], ...]]: ...
+) -> Iterator[tuple[_T | None, ...]]: ...
 @overload
 def windowed(
     seq: Iterable[_T], n: int, fillvalue: _U, step: int = ...
-) -> Iterator[Tuple[Union[_T, _U], ...]]: ...
-def substrings(iterable: Iterable[_T]) -> Iterator[Tuple[_T, ...]]: ...
+) -> Iterator[tuple[_T | _U, ...]]: ...
+def substrings(iterable: Iterable[_T]) -> Iterator[tuple[_T, ...]]: ...
 def substrings_indexes(
     seq: Sequence[_T], reverse: bool = ...
-) -> Iterator[Tuple[Sequence[_T], int, int]]: ...
+) -> Iterator[tuple[Sequence[_T], int, int]]: ...
 
 class bucket(Generic[_T, _U], Container[_U]):
     def __init__(
         self,
         iterable: Iterable[_T],
         key: Callable[[_T], _U],
-        validator: Optional[Callable[[object], object]] = ...,
+        validator: Callable[[_U], object] | None = ...,
     ) -> None: ...
     def __contains__(self, value: object) -> bool: ...
     def __iter__(self) -> Iterator[_U]: ...
@@ -115,130 +260,259 @@ class bucket(Generic[_T, _U], Container[_U]):
 
 def spy(
     iterable: Iterable[_T], n: int = ...
-) -> Tuple[List[_T], Iterator[_T]]: ...
+) -> tuple[list[_T], Iterator[_T]]: ...
 def interleave(*iterables: Iterable[_T]) -> Iterator[_T]: ...
 def interleave_longest(*iterables: Iterable[_T]) -> Iterator[_T]: ...
+def interleave_evenly(
+    iterables: list[Iterable[_T]], lengths: list[int] | None = ...
+) -> Iterator[_T]: ...
+def interleave_randomly(*iterables: Iterable[_T]) -> Iterable[_T]: ...
 def collapse(
     iterable: Iterable[Any],
-    base_type: Optional[type] = ...,
-    levels: Optional[int] = ...,
+    base_type: _ClassInfo | None = ...,
+    levels: int | None = ...,
 ) -> Iterator[Any]: ...
 @overload
 def side_effect(
     func: Callable[[_T], object],
     iterable: Iterable[_T],
     chunk_size: None = ...,
-    before: Optional[Callable[[], object]] = ...,
-    after: Optional[Callable[[], object]] = ...,
+    before: Callable[[], object] | None = ...,
+    after: Callable[[], object] | None = ...,
 ) -> Iterator[_T]: ...
 @overload
 def side_effect(
-    func: Callable[[List[_T]], object],
+    func: Callable[[list[_T]], object],
     iterable: Iterable[_T],
     chunk_size: int,
-    before: Optional[Callable[[], object]] = ...,
-    after: Optional[Callable[[], object]] = ...,
+    before: Callable[[], object] | None = ...,
+    after: Callable[[], object] | None = ...,
 ) -> Iterator[_T]: ...
 def sliced(
-    seq: Sequence[_T], n: int, strict: bool = ...
-) -> Iterator[Sequence[_T]]: ...
+    seq: _SupportsSlicing[_T], n: int, strict: bool = ...
+) -> Iterator[_T]: ...
 def split_at(
     iterable: Iterable[_T],
     pred: Callable[[_T], object],
     maxsplit: int = ...,
     keep_separator: bool = ...,
-) -> Iterator[List[_T]]: ...
+) -> Iterator[list[_T]]: ...
 def split_before(
     iterable: Iterable[_T], pred: Callable[[_T], object], maxsplit: int = ...
-) -> Iterator[List[_T]]: ...
+) -> Iterator[list[_T]]: ...
 def split_after(
     iterable: Iterable[_T], pred: Callable[[_T], object], maxsplit: int = ...
-) -> Iterator[List[_T]]: ...
+) -> Iterator[list[_T]]: ...
 def split_when(
     iterable: Iterable[_T],
     pred: Callable[[_T, _T], object],
     maxsplit: int = ...,
-) -> Iterator[List[_T]]: ...
+) -> Iterator[list[_T]]: ...
 def split_into(
-    iterable: Iterable[_T], sizes: Iterable[Optional[int]]
-) -> Iterator[List[_T]]: ...
+    iterable: Iterable[_T], sizes: Iterable[int | None]
+) -> Iterator[list[_T]]: ...
 @overload
 def padded(
     iterable: Iterable[_T],
     *,
-    n: Optional[int] = ...,
-    next_multiple: bool = ...
-) -> Iterator[Optional[_T]]: ...
+    n: int | None = ...,
+    next_multiple: bool = ...,
+) -> Iterator[_T | None]: ...
 @overload
 def padded(
     iterable: Iterable[_T],
     fillvalue: _U,
-    n: Optional[int] = ...,
+    n: int | None = ...,
     next_multiple: bool = ...,
-) -> Iterator[Union[_T, _U]]: ...
+) -> Iterator[_T | _U]: ...
 @overload
 def repeat_last(iterable: Iterable[_T]) -> Iterator[_T]: ...
 @overload
-def repeat_last(
-    iterable: Iterable[_T], default: _U
-) -> Iterator[Union[_T, _U]]: ...
-def distribute(n: int, iterable: Iterable[_T]) -> List[Iterator[_T]]: ...
+def repeat_last(iterable: Iterable[_T], default: _U) -> Iterator[_T | _U]: ...
+def distribute(n: int, iterable: Iterable[_T]) -> list[Iterator[_T]]: ...
 @overload
 def stagger(
     iterable: Iterable[_T],
     offsets: _SizedIterable[int] = ...,
     longest: bool = ...,
-) -> Iterator[Tuple[Optional[_T], ...]]: ...
+) -> Iterator[tuple[_T | None, ...]]: ...
 @overload
 def stagger(
     iterable: Iterable[_T],
     offsets: _SizedIterable[int] = ...,
     longest: bool = ...,
     fillvalue: _U = ...,
-) -> Iterator[Tuple[Union[_T, _U], ...]]: ...
+) -> Iterator[tuple[_T | _U, ...]]: ...
 
 class UnequalIterablesError(ValueError):
-    def __init__(
-        self, details: Optional[Tuple[int, int, int]] = ...
-    ) -> None: ...
+    def __init__(self, details: tuple[int, int, int] | None = ...) -> None: ...
+
+# zip_equal
+@overload
+def zip_equal(__iter1: Iterable[_T1]) -> Iterator[tuple[_T1]]: ...
+@overload
+def zip_equal(
+    __iter1: Iterable[_T1], __iter2: Iterable[_T2]
+) -> Iterator[tuple[_T1, _T2]]: ...
+@overload
+def zip_equal(
+    __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]
+) -> Iterator[tuple[_T1, _T2, _T3]]: ...
+@overload
+def zip_equal(
+    __iter1: Iterable[_T1],
+    __iter2: Iterable[_T2],
+    __iter3: Iterable[_T3],
+    __iter4: Iterable[_T4],
+) -> Iterator[tuple[_T1, _T2, _T3, _T4]]: ...
+@overload
+def zip_equal(
+    __iter1: Iterable[_T1],
+    __iter2: Iterable[_T2],
+    __iter3: Iterable[_T3],
+    __iter4: Iterable[_T4],
+    __iter5: Iterable[_T5],
+) -> Iterator[tuple[_T1, _T2, _T3, _T4, _T5]]: ...
+@overload
+def zip_equal(
+    __iter1: Iterable[Any],
+    __iter2: Iterable[Any],
+    __iter3: Iterable[Any],
+    __iter4: Iterable[Any],
+    __iter5: Iterable[Any],
+    __iter6: Iterable[Any],
+    *iterables: Iterable[Any],
+) -> Iterator[tuple[Any, ...]]: ...
 
-def zip_equal(*iterables: Iterable[_T]) -> Iterator[Tuple[_T, ...]]: ...
+# zip_offset
+@overload
+def zip_offset(
+    __iter1: Iterable[_T1],
+    *,
+    offsets: _SizedIterable[int],
+    longest: bool = ...,
+    fillvalue: None = None,
+) -> Iterator[tuple[_T1 | None]]: ...
 @overload
 def zip_offset(
-    *iterables: Iterable[_T], offsets: _SizedIterable[int], longest: bool = ...
-) -> Iterator[Tuple[Optional[_T], ...]]: ...
+    __iter1: Iterable[_T1],
+    __iter2: Iterable[_T2],
+    *,
+    offsets: _SizedIterable[int],
+    longest: bool = ...,
+    fillvalue: None = None,
+) -> Iterator[tuple[_T1 | None, _T2 | None]]: ...
 @overload
 def zip_offset(
+    __iter1: Iterable[_T],
+    __iter2: Iterable[_T],
+    __iter3: Iterable[_T],
     *iterables: Iterable[_T],
     offsets: _SizedIterable[int],
     longest: bool = ...,
-    fillvalue: _U
-) -> Iterator[Tuple[Union[_T, _U], ...]]: ...
+    fillvalue: None = None,
+) -> Iterator[tuple[_T | None, ...]]: ...
+@overload
+def zip_offset(
+    __iter1: Iterable[_T1],
+    *,
+    offsets: _SizedIterable[int],
+    longest: bool = ...,
+    fillvalue: _U,
+) -> Iterator[tuple[_T1 | _U]]: ...
+@overload
+def zip_offset(
+    __iter1: Iterable[_T1],
+    __iter2: Iterable[_T2],
+    *,
+    offsets: _SizedIterable[int],
+    longest: bool = ...,
+    fillvalue: _U,
+) -> Iterator[tuple[_T1 | _U, _T2 | _U]]: ...
+@overload
+def zip_offset(
+    __iter1: Iterable[_T],
+    __iter2: Iterable[_T],
+    __iter3: Iterable[_T],
+    *iterables: Iterable[_T],
+    offsets: _SizedIterable[int],
+    longest: bool = ...,
+    fillvalue: _U,
+) -> Iterator[tuple[_T | _U, ...]]: ...
 def sort_together(
     iterables: Iterable[Iterable[_T]],
     key_list: Iterable[int] = ...,
-    key: Optional[Callable[..., Any]] = ...,
+    key: Callable[..., Any] | None = ...,
     reverse: bool = ...,
-) -> List[Tuple[_T, ...]]: ...
-def unzip(iterable: Iterable[Sequence[_T]]) -> Tuple[Iterator[_T], ...]: ...
-def divide(n: int, iterable: Iterable[_T]) -> List[Iterator[_T]]: ...
+    strict: bool = ...,
+) -> list[tuple[_T, ...]]: ...
+def unzip(iterable: Iterable[Sequence[_T]]) -> tuple[Iterator[_T], ...]: ...
+def divide(n: int, iterable: Iterable[_T]) -> list[Iterator[_T]]: ...
 def always_iterable(
     obj: object,
-    base_type: Union[
-        type, Tuple[Union[type, Tuple[Any, ...]], ...], None
-    ] = ...,
+    base_type: _ClassInfo | None = ...,
 ) -> Iterator[Any]: ...
 def adjacent(
     predicate: Callable[[_T], bool],
     iterable: Iterable[_T],
     distance: int = ...,
-) -> Iterator[Tuple[bool, _T]]: ...
+) -> Iterator[tuple[bool, _T]]: ...
+@overload
+def groupby_transform(
+    iterable: Iterable[_T],
+    keyfunc: None = None,
+    valuefunc: None = None,
+    reducefunc: None = None,
+) -> Iterator[tuple[_T, Iterator[_T]]]: ...
+@overload
+def groupby_transform(
+    iterable: Iterable[_T],
+    keyfunc: Callable[[_T], _U],
+    valuefunc: None,
+    reducefunc: None,
+) -> Iterator[tuple[_U, Iterator[_T]]]: ...
+@overload
+def groupby_transform(
+    iterable: Iterable[_T],
+    keyfunc: None,
+    valuefunc: Callable[[_T], _V],
+    reducefunc: None,
+) -> Iterator[tuple[_T, Iterator[_V]]]: ...
+@overload
 def groupby_transform(
     iterable: Iterable[_T],
-    keyfunc: Optional[Callable[[_T], _U]] = ...,
-    valuefunc: Optional[Callable[[_T], _V]] = ...,
-    reducefunc: Optional[Callable[..., _W]] = ...,
-) -> Iterator[Tuple[_T, _W]]: ...
+    keyfunc: Callable[[_T], _U],
+    valuefunc: Callable[[_T], _V],
+    reducefunc: None,
+) -> Iterator[tuple[_U, Iterator[_V]]]: ...
+@overload
+def groupby_transform(
+    iterable: Iterable[_T],
+    keyfunc: None,
+    valuefunc: None,
+    reducefunc: Callable[[Iterator[_T]], _W],
+) -> Iterator[tuple[_T, _W]]: ...
+@overload
+def groupby_transform(
+    iterable: Iterable[_T],
+    keyfunc: Callable[[_T], _U],
+    valuefunc: None,
+    reducefunc: Callable[[Iterator[_T]], _W],
+) -> Iterator[tuple[_U, _W]]: ...
+@overload
+def groupby_transform(
+    iterable: Iterable[_T],
+    keyfunc: None,
+    valuefunc: Callable[[_T], _V],
+    reducefunc: Callable[[Iterator[_V]], _W],
+) -> Iterator[tuple[_T, _W]]: ...
+@overload
+def groupby_transform(
+    iterable: Iterable[_T],
+    keyfunc: Callable[[_T], _U],
+    valuefunc: Callable[[_T], _V],
+    reducefunc: Callable[[Iterator[_V]], _W],
+) -> Iterator[tuple[_U, _W]]: ...
 
 class numeric_range(Generic[_T, _U], Sequence[_T], Hashable, Reversible[_T]):
     @overload
@@ -259,22 +533,22 @@ class numeric_range(Generic[_T, _U], Sequence[_T], Hashable, Reversible[_T]):
     def __len__(self) -> int: ...
     def __reduce__(
         self,
-    ) -> Tuple[Type[numeric_range[_T, _U]], Tuple[_T, _T, _U]]: ...
+    ) -> tuple[type[numeric_range[_T, _U]], tuple[_T, _T, _U]]: ...
     def __repr__(self) -> str: ...
     def __reversed__(self) -> Iterator[_T]: ...
     def count(self, value: _T) -> int: ...
     def index(self, value: _T) -> int: ...  # type: ignore
 
 def count_cycle(
-    iterable: Iterable[_T], n: Optional[int] = ...
-) -> Iterable[Tuple[int, _T]]: ...
+    iterable: Iterable[_T], n: int | None = ...
+) -> Iterable[tuple[int, _T]]: ...
 def mark_ends(
     iterable: Iterable[_T],
-) -> Iterable[Tuple[bool, bool, _T]]: ...
+) -> Iterable[tuple[bool, bool, _T]]: ...
 def locate(
-    iterable: Iterable[object],
+    iterable: Iterable[_T],
     pred: Callable[..., Any] = ...,
-    window_size: Optional[int] = ...,
+    window_size: int | None = ...,
 ) -> Iterator[int]: ...
 def lstrip(
     iterable: Iterable[_T], pred: Callable[[_T], object]
@@ -287,24 +561,22 @@ def strip(
 ) -> Iterator[_T]: ...
 
 class islice_extended(Generic[_T], Iterator[_T]):
-    def __init__(
-        self, iterable: Iterable[_T], *args: Optional[int]
-    ) -> None: ...
+    def __init__(self, iterable: Iterable[_T], *args: int | None) -> None: ...
     def __iter__(self) -> islice_extended[_T]: ...
     def __next__(self) -> _T: ...
     def __getitem__(self, index: slice) -> islice_extended[_T]: ...
 
 def always_reversible(iterable: Iterable[_T]) -> Iterator[_T]: ...
 def consecutive_groups(
-    iterable: Iterable[_T], ordering: Callable[[_T], int] = ...
+    iterable: Iterable[_T], ordering: None | Callable[[_T], int] = ...
 ) -> Iterator[Iterator[_T]]: ...
 @overload
 def difference(
     iterable: Iterable[_T],
     func: Callable[[_T, _T], _U] = ...,
     *,
-    initial: None = ...
-) -> Iterator[Union[_T, _U]]: ...
+    initial: None = ...,
+) -> Iterator[_T | _U]: ...
 @overload
 def difference(
     iterable: Iterable[_T], func: Callable[[_T, _T], _U] = ..., *, initial: _U
@@ -320,7 +592,7 @@ class SequenceView(Generic[_T], Sequence[_T]):
 
 class seekable(Generic[_T], Iterator[_T]):
     def __init__(
-        self, iterable: Iterable[_T], maxlen: Optional[int] = ...
+        self, iterable: Iterable[_T], maxlen: int | None = ...
     ) -> None: ...
     def __iter__(self) -> seekable[_T]: ...
     def __next__(self) -> _T: ...
@@ -328,20 +600,23 @@ class seekable(Generic[_T], Iterator[_T]):
     @overload
     def peek(self) -> _T: ...
     @overload
-    def peek(self, default: _U) -> Union[_T, _U]: ...
+    def peek(self, default: _U) -> _T | _U: ...
     def elements(self) -> SequenceView[_T]: ...
     def seek(self, index: int) -> None: ...
+    def relative_seek(self, count: int) -> None: ...
 
 class run_length:
     @staticmethod
-    def encode(iterable: Iterable[_T]) -> Iterator[Tuple[_T, int]]: ...
+    def encode(iterable: Iterable[_T]) -> Iterator[tuple[_T, int]]: ...
     @staticmethod
-    def decode(iterable: Iterable[Tuple[_T, int]]) -> Iterator[_T]: ...
+    def decode(iterable: Iterable[tuple[_T, int]]) -> Iterator[_T]: ...
 
 def exactly_n(
     iterable: Iterable[_T], n: int, predicate: Callable[[_T], object] = ...
 ) -> bool: ...
-def circular_shifts(iterable: Iterable[_T]) -> List[Tuple[_T, ...]]: ...
+def circular_shifts(
+    iterable: Iterable[_T], steps: int = 1
+) -> list[tuple[_T, ...]]: ...
 def make_decorator(
     wrapping_func: Callable[..., _U], result_index: int = ...
 ) -> Callable[..., Callable[[Callable[..., Any]], Callable[..., _U]]]: ...
@@ -351,44 +626,47 @@ def map_reduce(
     keyfunc: Callable[[_T], _U],
     valuefunc: None = ...,
     reducefunc: None = ...,
-) -> Dict[_U, List[_T]]: ...
+) -> dict[_U, list[_T]]: ...
 @overload
 def map_reduce(
     iterable: Iterable[_T],
     keyfunc: Callable[[_T], _U],
     valuefunc: Callable[[_T], _V],
     reducefunc: None = ...,
-) -> Dict[_U, List[_V]]: ...
+) -> dict[_U, list[_V]]: ...
 @overload
 def map_reduce(
     iterable: Iterable[_T],
     keyfunc: Callable[[_T], _U],
     valuefunc: None = ...,
-    reducefunc: Callable[[List[_T]], _W] = ...,
-) -> Dict[_U, _W]: ...
+    reducefunc: Callable[[list[_T]], _W] = ...,
+) -> dict[_U, _W]: ...
 @overload
 def map_reduce(
     iterable: Iterable[_T],
     keyfunc: Callable[[_T], _U],
     valuefunc: Callable[[_T], _V],
-    reducefunc: Callable[[List[_V]], _W],
-) -> Dict[_U, _W]: ...
+    reducefunc: Callable[[list[_V]], _W],
+) -> dict[_U, _W]: ...
 def rlocate(
     iterable: Iterable[_T],
     pred: Callable[..., object] = ...,
-    window_size: Optional[int] = ...,
+    window_size: int | None = ...,
 ) -> Iterator[int]: ...
 def replace(
     iterable: Iterable[_T],
     pred: Callable[..., object],
     substitutes: Iterable[_U],
-    count: Optional[int] = ...,
+    count: int | None = ...,
     window_size: int = ...,
-) -> Iterator[Union[_T, _U]]: ...
-def partitions(iterable: Iterable[_T]) -> Iterator[List[List[_T]]]: ...
+) -> Iterator[_T | _U]: ...
+def partitions(iterable: Iterable[_T]) -> Iterator[list[list[_T]]]: ...
 def set_partitions(
-    iterable: Iterable[_T], k: Optional[int] = ...
-) -> Iterator[List[List[_T]]]: ...
+    iterable: Iterable[_T],
+    k: int | None = ...,
+    min_size: int | None = ...,
+    max_size: int | None = ...,
+) -> Iterator[list[list[_T]]]: ...
 
 class time_limited(Generic[_T], Iterator[_T]):
     def __init__(
@@ -399,35 +677,54 @@ class time_limited(Generic[_T], Iterator[_T]):
 
 @overload
 def only(
-    iterable: Iterable[_T], *, too_long: Optional[_Raisable] = ...
-) -> Optional[_T]: ...
+    iterable: Iterable[_T], *, too_long: _Raisable | None = ...
+) -> _T | None: ...
 @overload
 def only(
-    iterable: Iterable[_T], default: _U, too_long: Optional[_Raisable] = ...
-) -> Union[_T, _U]: ...
+    iterable: Iterable[_T], default: _U, too_long: _Raisable | None = ...
+) -> _T | _U: ...
 def ichunked(iterable: Iterable[_T], n: int) -> Iterator[Iterator[_T]]: ...
 def distinct_combinations(
     iterable: Iterable[_T], r: int
-) -> Iterator[Tuple[_T, ...]]: ...
+) -> Iterator[tuple[_T, ...]]: ...
 def filter_except(
     validator: Callable[[Any], object],
     iterable: Iterable[_T],
-    *exceptions: Type[BaseException]
+    *exceptions: type[BaseException],
 ) -> Iterator[_T]: ...
 def map_except(
     function: Callable[[Any], _U],
     iterable: Iterable[_T],
-    *exceptions: Type[BaseException]
+    *exceptions: type[BaseException],
 ) -> Iterator[_U]: ...
+def map_if(
+    iterable: Iterable[Any],
+    pred: Callable[[Any], bool],
+    func: Callable[[Any], Any],
+    func_else: Callable[[Any], Any] | None = ...,
+) -> Iterator[Any]: ...
+def _sample_unweighted(
+    iterator: Iterator[_T], k: int, strict: bool
+) -> list[_T]: ...
+def _sample_counted(
+    population: Iterator[_T], k: int, counts: Iterable[int], strict: bool
+) -> list[_T]: ...
+def _sample_weighted(
+    iterator: Iterator[_T], k: int, weights: Iterator[float], strict: bool
+) -> list[_T]: ...
 def sample(
     iterable: Iterable[_T],
     k: int,
-    weights: Optional[Iterable[float]] = ...,
-) -> List[_T]: ...
+    weights: Iterable[float] | None = ...,
+    *,
+    counts: Iterable[int] | None = ...,
+    strict: bool = False,
+) -> list[_T]: ...
 def is_sorted(
     iterable: Iterable[_T],
-    key: Optional[Callable[[_T], _U]] = ...,
+    key: Callable[[_T], _U] | None = ...,
     reverse: bool = False,
+    strict: bool = False,
 ) -> bool: ...
 
 class AbortThread(BaseException):
@@ -443,10 +740,10 @@ class callback_iter(Generic[_T], Iterator[_T]):
     def __enter__(self) -> callback_iter[_T]: ...
     def __exit__(
         self,
-        exc_type: Optional[Type[BaseException]],
-        exc_value: Optional[BaseException],
-        traceback: Optional[TracebackType],
-    ) -> Optional[bool]: ...
+        exc_type: type[BaseException] | None,
+        exc_value: BaseException | None,
+        traceback: types.TracebackType | None,
+    ) -> bool | None: ...
     def __iter__(self) -> callback_iter[_T]: ...
     def __next__(self) -> _T: ...
     def _reader(self) -> Iterator[_T]: ...
@@ -457,24 +754,196 @@ class callback_iter(Generic[_T], Iterator[_T]):
 
 def windowed_complete(
     iterable: Iterable[_T], n: int
-) -> Iterator[Tuple[_T, ...]]: ...
+) -> Iterator[tuple[tuple[_T, ...], tuple[_T, ...], tuple[_T, ...]]]: ...
 def all_unique(
-    iterable: Iterable[_T], key: Optional[Callable[[_T], _U]] = ...
+    iterable: Iterable[_T], key: Callable[[_T], _U] | None = ...
 ) -> bool: ...
-def nth_product(index: int, *args: Iterable[_T]) -> Tuple[_T, ...]: ...
+def nth_product(index: int, *args: Iterable[_T]) -> tuple[_T, ...]: ...
+def nth_combination_with_replacement(
+    iterable: Iterable[_T], r: int, index: int
+) -> tuple[_T, ...]: ...
 def nth_permutation(
     iterable: Iterable[_T], r: int, index: int
-) -> Tuple[_T, ...]: ...
-def value_chain(*args: Union[_T, Iterable[_T]]) -> Iterable[_T]: ...
+) -> tuple[_T, ...]: ...
+def value_chain(*args: _T | Iterable[_T]) -> Iterable[_T]: ...
 def product_index(element: Iterable[_T], *args: Iterable[_T]) -> int: ...
 def combination_index(
     element: Iterable[_T], iterable: Iterable[_T]
 ) -> int: ...
+def combination_with_replacement_index(
+    element: Iterable[_T], iterable: Iterable[_T]
+) -> int: ...
 def permutation_index(
     element: Iterable[_T], iterable: Iterable[_T]
 ) -> int: ...
+def repeat_each(iterable: Iterable[_T], n: int = ...) -> Iterator[_T]: ...
 
 class countable(Generic[_T], Iterator[_T]):
     def __init__(self, iterable: Iterable[_T]) -> None: ...
     def __iter__(self) -> countable[_T]: ...
     def __next__(self) -> _T: ...
+    items_seen: int
+
+def chunked_even(iterable: Iterable[_T], n: int) -> Iterator[list[_T]]: ...
+@overload
+def zip_broadcast(
+    __obj1: _T | Iterable[_T],
+    *,
+    scalar_types: _ClassInfo | None = ...,
+    strict: bool = ...,
+) -> Iterable[tuple[_T, ...]]: ...
+@overload
+def zip_broadcast(
+    __obj1: _T | Iterable[_T],
+    __obj2: _T | Iterable[_T],
+    *,
+    scalar_types: _ClassInfo | None = ...,
+    strict: bool = ...,
+) -> Iterable[tuple[_T, ...]]: ...
+@overload
+def zip_broadcast(
+    __obj1: _T | Iterable[_T],
+    __obj2: _T | Iterable[_T],
+    __obj3: _T | Iterable[_T],
+    *,
+    scalar_types: _ClassInfo | None = ...,
+    strict: bool = ...,
+) -> Iterable[tuple[_T, ...]]: ...
+@overload
+def zip_broadcast(
+    __obj1: _T | Iterable[_T],
+    __obj2: _T | Iterable[_T],
+    __obj3: _T | Iterable[_T],
+    __obj4: _T | Iterable[_T],
+    *,
+    scalar_types: _ClassInfo | None = ...,
+    strict: bool = ...,
+) -> Iterable[tuple[_T, ...]]: ...
+@overload
+def zip_broadcast(
+    __obj1: _T | Iterable[_T],
+    __obj2: _T | Iterable[_T],
+    __obj3: _T | Iterable[_T],
+    __obj4: _T | Iterable[_T],
+    __obj5: _T | Iterable[_T],
+    *,
+    scalar_types: _ClassInfo | None = ...,
+    strict: bool = ...,
+) -> Iterable[tuple[_T, ...]]: ...
+@overload
+def zip_broadcast(
+    __obj1: _T | Iterable[_T],
+    __obj2: _T | Iterable[_T],
+    __obj3: _T | Iterable[_T],
+    __obj4: _T | Iterable[_T],
+    __obj5: _T | Iterable[_T],
+    __obj6: _T | Iterable[_T],
+    *objects: _T | Iterable[_T],
+    scalar_types: _ClassInfo | None = ...,
+    strict: bool = ...,
+) -> Iterable[tuple[_T, ...]]: ...
+def unique_in_window(
+    iterable: Iterable[_T], n: int, key: Callable[[_T], _U] | None = ...
+) -> Iterator[_T]: ...
+def duplicates_everseen(
+    iterable: Iterable[_T], key: Callable[[_T], _U] | None = ...
+) -> Iterator[_T]: ...
+def duplicates_justseen(
+    iterable: Iterable[_T], key: Callable[[_T], _U] | None = ...
+) -> Iterator[_T]: ...
+def classify_unique(
+    iterable: Iterable[_T], key: Callable[[_T], _U] | None = ...
+) -> Iterator[tuple[_T, bool, bool]]: ...
+
+class _SupportsLessThan(Protocol):
+    def __lt__(self, __other: Any) -> bool: ...
+
+_SupportsLessThanT = TypeVar("_SupportsLessThanT", bound=_SupportsLessThan)
+
+@overload
+def minmax(
+    iterable_or_value: Iterable[_SupportsLessThanT], *, key: None = None
+) -> tuple[_SupportsLessThanT, _SupportsLessThanT]: ...
+@overload
+def minmax(
+    iterable_or_value: Iterable[_T], *, key: Callable[[_T], _SupportsLessThan]
+) -> tuple[_T, _T]: ...
+@overload
+def minmax(
+    iterable_or_value: Iterable[_SupportsLessThanT],
+    *,
+    key: None = None,
+    default: _U,
+) -> _U | tuple[_SupportsLessThanT, _SupportsLessThanT]: ...
+@overload
+def minmax(
+    iterable_or_value: Iterable[_T],
+    *,
+    key: Callable[[_T], _SupportsLessThan],
+    default: _U,
+) -> _U | tuple[_T, _T]: ...
+@overload
+def minmax(
+    iterable_or_value: _SupportsLessThanT,
+    __other: _SupportsLessThanT,
+    *others: _SupportsLessThanT,
+) -> tuple[_SupportsLessThanT, _SupportsLessThanT]: ...
+@overload
+def minmax(
+    iterable_or_value: _T,
+    __other: _T,
+    *others: _T,
+    key: Callable[[_T], _SupportsLessThan],
+) -> tuple[_T, _T]: ...
+def longest_common_prefix(
+    iterables: Iterable[Iterable[_T]],
+) -> Iterator[_T]: ...
+def iequals(*iterables: Iterable[Any]) -> bool: ...
+def constrained_batches(
+    iterable: Iterable[_T],
+    max_size: int,
+    max_count: int | None = ...,
+    get_len: Callable[[_T], object] = ...,
+    strict: bool = ...,
+) -> Iterator[tuple[_T]]: ...
+def gray_product(*iterables: Iterable[_T]) -> Iterator[tuple[_T, ...]]: ...
+def partial_product(*iterables: Iterable[_T]) -> Iterator[tuple[_T, ...]]: ...
+def takewhile_inclusive(
+    predicate: Callable[[_T], bool], iterable: Iterable[_T]
+) -> Iterator[_T]: ...
+def outer_product(
+    func: Callable[[_T, _U], _V],
+    xs: Iterable[_T],
+    ys: Iterable[_U],
+    *args: Any,
+    **kwargs: Any,
+) -> Iterator[tuple[_V, ...]]: ...
+def iter_suppress(
+    iterable: Iterable[_T],
+    *exceptions: type[BaseException],
+) -> Iterator[_T]: ...
+def filter_map(
+    func: Callable[[_T], _V | None],
+    iterable: Iterable[_T],
+) -> Iterator[_V]: ...
+def powerset_of_sets(iterable: Iterable[_T]) -> Iterator[set[_T]]: ...
+def join_mappings(
+    **field_to_map: Mapping[_T, _V],
+) -> dict[_T, dict[str, _V]]: ...
+def doublestarmap(
+    func: Callable[..., _T],
+    iterable: Iterable[Mapping[str, Any]],
+) -> Iterator[_T]: ...
+def dft(xarr: Sequence[complex]) -> Iterator[complex]: ...
+def idft(Xarr: Sequence[complex]) -> Iterator[complex]: ...
+def _nth_prime_ub(n: int) -> float: ...
+def nth_prime(n: int, *, approximate: bool = ...) -> int: ...
+def argmin(
+    iterable: Iterable[_T], *, key: Callable[[_T], _U] | None = ...
+) -> int: ...
+def argmax(
+    iterable: Iterable[_T], *, key: Callable[[_T], _U] | None = ...
+) -> int: ...
+def extract(
+    iterable: Iterable[_T], indices: Iterable[int]
+) -> Iterator[_T]: ...
diff --git a/setuptools/_vendor/more_itertools/recipes.py b/setuptools/_vendor/more_itertools/recipes.py
index 521abd7c2c..dacf61407d 100644
--- a/setuptools/_vendor/more_itertools/recipes.py
+++ b/setuptools/_vendor/more_itertools/recipes.py
@@ -7,32 +7,52 @@
 .. [1] http://docs.python.org/library/itertools.html#recipes
 
 """
-import warnings
+
+import random
+
+from bisect import bisect_left, insort
 from collections import deque
+from contextlib import suppress
+from functools import lru_cache, partial, reduce
+from heapq import heappush, heappushpop
 from itertools import (
+    accumulate,
     chain,
     combinations,
+    compress,
     count,
     cycle,
     groupby,
     islice,
+    product,
     repeat,
     starmap,
+    takewhile,
     tee,
     zip_longest,
 )
-import operator
+from math import prod, comb, isqrt, gcd
+from operator import mul, not_, itemgetter, getitem, index
 from random import randrange, sample, choice
+from sys import hexversion
 
 __all__ = [
     'all_equal',
+    'batched',
+    'before_and_after',
     'consume',
     'convolve',
     'dotproduct',
     'first_true',
+    'factor',
     'flatten',
     'grouper',
+    'is_prime',
     'iter_except',
+    'iter_index',
+    'loops',
+    'matmul',
+    'multinomial',
     'ncycles',
     'nth',
     'nth_combination',
@@ -40,25 +60,65 @@
     'pad_none',
     'pairwise',
     'partition',
+    'polynomial_eval',
+    'polynomial_from_roots',
+    'polynomial_derivative',
     'powerset',
     'prepend',
     'quantify',
+    'reshape',
     'random_combination_with_replacement',
     'random_combination',
     'random_permutation',
     'random_product',
     'repeatfunc',
     'roundrobin',
+    'running_median',
+    'sieve',
+    'sliding_window',
+    'subslices',
+    'sum_of_squares',
     'tabulate',
     'tail',
     'take',
+    'totient',
+    'transpose',
+    'triplewise',
+    'unique',
     'unique_everseen',
     'unique_justseen',
 ]
 
+_marker = object()
+
+
+# zip with strict is available for Python 3.10+
+try:
+    zip(strict=True)
+except TypeError:  # pragma: no cover
+    _zip_strict = zip
+else:  # pragma: no cover
+    _zip_strict = partial(zip, strict=True)
+
+
+# math.sumprod is available for Python 3.12+
+try:
+    from math import sumprod as _sumprod
+except ImportError:  # pragma: no cover
+    _sumprod = lambda x, y: dotproduct(x, y)
+
+
+# heapq max-heap functions are available for Python 3.14+
+try:
+    from heapq import heappush_max, heappushpop_max
+except ImportError:  # pragma: no cover
+    _max_heap_available = False
+else:  # pragma: no cover
+    _max_heap_available = True
+
 
 def take(n, iterable):
-    """Return first *n* items of the iterable as a list.
+    """Return first *n* items of the *iterable* as a list.
 
         >>> take(3, range(10))
         [0, 1, 2]
@@ -99,7 +159,12 @@ def tail(n, iterable):
     ['E', 'F', 'G']
 
     """
-    return iter(deque(iterable, maxlen=n))
+    try:
+        size = len(iterable)
+    except TypeError:
+        return iter(deque(iterable, maxlen=n))
+    else:
+        return islice(iterable, max(0, size - n), None)
 
 
 def consume(iterator, n=None):
@@ -155,7 +220,7 @@ def nth(iterable, n, default=None):
     return next(islice(iterable, n, None), default)
 
 
-def all_equal(iterable):
+def all_equal(iterable, key=None):
     """
     Returns ``True`` if all the elements are equal to each other.
 
@@ -164,9 +229,21 @@ def all_equal(iterable):
         >>> all_equal('aaab')
         False
 
+    A function that accepts a single argument and returns a transformed version
+    of each input item can be specified with *key*:
+
+        >>> all_equal('AaaA', key=str.casefold)
+        True
+        >>> all_equal([1, 2, 3], key=lambda x: x < 10)
+        True
+
     """
-    g = groupby(iterable)
-    return next(g, True) and not next(g, False)
+    iterator = groupby(iterable, key)
+    for first in iterator:
+        for second in iterator:
+            return False
+        return True
+    return True
 
 
 def quantify(iterable, pred=bool):
@@ -209,11 +286,14 @@ def ncycles(iterable, n):
 def dotproduct(vec1, vec2):
     """Returns the dot product of the two iterables.
 
-    >>> dotproduct([10, 10], [20, 20])
-    400
+    >>> dotproduct([10, 15, 12], [0.65, 0.80, 1.25])
+    33.5
+    >>> 10 * 0.65 + 15 * 0.80 + 12 * 1.25
+    33.5
 
+    In Python 3.12 and later, use ``math.sumprod()`` instead.
     """
-    return sum(map(operator.mul, vec1, vec2))
+    return sum(map(mul, vec1, vec2))
 
 
 def flatten(listOfLists):
@@ -266,39 +346,98 @@ def _pairwise(iterable):
     """
     a, b = tee(iterable)
     next(b, None)
-    yield from zip(a, b)
+    return zip(a, b)
 
 
 try:
     from itertools import pairwise as itertools_pairwise
-except ImportError:
+except ImportError:  # pragma: no cover
     pairwise = _pairwise
-else:
+else:  # pragma: no cover
 
     def pairwise(iterable):
-        yield from itertools_pairwise(iterable)
+        return itertools_pairwise(iterable)
 
     pairwise.__doc__ = _pairwise.__doc__
 
 
-def grouper(iterable, n, fillvalue=None):
-    """Collect data into fixed-length chunks or blocks.
+class UnequalIterablesError(ValueError):
+    def __init__(self, details=None):
+        msg = 'Iterables have different lengths'
+        if details is not None:
+            msg += (': index 0 has length {}; index {} has length {}').format(
+                *details
+            )
+
+        super().__init__(msg)
+
+
+def _zip_equal_generator(iterables):
+    for combo in zip_longest(*iterables, fillvalue=_marker):
+        for val in combo:
+            if val is _marker:
+                raise UnequalIterablesError()
+        yield combo
+
+
+def _zip_equal(*iterables):
+    # Check whether the iterables are all the same size.
+    try:
+        first_size = len(iterables[0])
+        for i, it in enumerate(iterables[1:], 1):
+            size = len(it)
+            if size != first_size:
+                raise UnequalIterablesError(details=(first_size, i, size))
+        # All sizes are equal, we can use the built-in zip.
+        return zip(*iterables)
+    # If any one of the iterables didn't have a length, start reading
+    # them until one runs out.
+    except TypeError:
+        return _zip_equal_generator(iterables)
+
+
+def grouper(iterable, n, incomplete='fill', fillvalue=None):
+    """Group elements from *iterable* into fixed-length groups of length *n*.
+
+    >>> list(grouper('ABCDEF', 3))
+    [('A', 'B', 'C'), ('D', 'E', 'F')]
+
+    The keyword arguments *incomplete* and *fillvalue* control what happens for
+    iterables whose length is not a multiple of *n*.
 
-    >>> list(grouper('ABCDEFG', 3, 'x'))
+    When *incomplete* is `'fill'`, the last group will contain instances of
+    *fillvalue*.
+
+    >>> list(grouper('ABCDEFG', 3, incomplete='fill', fillvalue='x'))
     [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')]
 
+    When *incomplete* is `'ignore'`, the last group will not be emitted.
+
+    >>> list(grouper('ABCDEFG', 3, incomplete='ignore', fillvalue='x'))
+    [('A', 'B', 'C'), ('D', 'E', 'F')]
+
+    When *incomplete* is `'strict'`, a subclass of `ValueError` will be raised.
+
+    >>> iterator = grouper('ABCDEFG', 3, incomplete='strict')
+    >>> list(iterator)  # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+    ...
+    UnequalIterablesError
+
     """
-    if isinstance(iterable, int):
-        warnings.warn(
-            "grouper expects iterable as first parameter", DeprecationWarning
-        )
-        n, iterable = iterable, n
-    args = [iter(iterable)] * n
-    return zip_longest(fillvalue=fillvalue, *args)
+    iterators = [iter(iterable)] * n
+    if incomplete == 'fill':
+        return zip_longest(*iterators, fillvalue=fillvalue)
+    if incomplete == 'strict':
+        return _zip_equal(*iterators)
+    if incomplete == 'ignore':
+        return zip(*iterators)
+    else:
+        raise ValueError('Expected fill, strict, or ignore')
 
 
 def roundrobin(*iterables):
-    """Yields an item from each iterable, alternating between them.
+    """Visit input iterables in a cycle until each is exhausted.
 
         >>> list(roundrobin('ABC', 'D', 'EF'))
         ['A', 'D', 'E', 'B', 'F', 'C']
@@ -308,16 +447,11 @@ def roundrobin(*iterables):
     iterables is small).
 
     """
-    # Recipe credited to George Sakkis
-    pending = len(iterables)
-    nexts = cycle(iter(it).__next__ for it in iterables)
-    while pending:
-        try:
-            for next in nexts:
-                yield next()
-        except StopIteration:
-            pending -= 1
-            nexts = cycle(islice(nexts, pending))
+    # Algorithm credited to George Sakkis
+    iterators = map(iter, iterables)
+    for num_active in range(len(iterables), 0, -1):
+        iterators = cycle(islice(iterators, num_active))
+        yield from map(next, iterators)
 
 
 def partition(pred, iterable):
@@ -343,12 +477,9 @@ def partition(pred, iterable):
     if pred is None:
         pred = bool
 
-    evaluations = ((pred(x), x) for x in iterable)
-    t1, t2 = tee(evaluations)
-    return (
-        (x for (cond, x) in t1 if not cond),
-        (x for (cond, x) in t2 if cond),
-    )
+    t1, t2, p = tee(iterable, 3)
+    p1, p2 = tee(map(pred, p))
+    return (compress(t1, map(not_, p1)), compress(t2, p2))
 
 
 def powerset(iterable):
@@ -359,16 +490,14 @@ def powerset(iterable):
 
     :func:`powerset` will operate on iterables that aren't :class:`set`
     instances, so repeated elements in the input will produce repeated elements
-    in the output. Use :func:`unique_everseen` on the input to avoid generating
-    duplicates:
+    in the output.
 
         >>> seq = [1, 1, 0]
         >>> list(powerset(seq))
         [(), (1,), (1,), (0,), (1, 1), (1, 0), (1, 0), (1, 1, 0)]
-        >>> from more_itertools import unique_everseen
-        >>> list(powerset(unique_everseen(seq)))
-        [(), (1,), (0,), (1, 0)]
 
+    For a variant that efficiently yields actual :class:`set` instances, see
+    :func:`powerset_of_sets`.
     """
     s = list(iterable)
     return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
@@ -396,7 +525,7 @@ def unique_everseen(iterable, key=None):
         >>> list(unique_everseen(iterable, key=tuple))  # Faster
         [[1, 2], [2, 3]]
 
-    Similary, you may want to convert unhashable ``set`` objects with
+    Similarly, you may want to convert unhashable ``set`` objects with
     ``key=frozenset``. For ``dict`` objects,
     ``key=lambda x: frozenset(x.items())`` can be used.
 
@@ -428,7 +557,30 @@ def unique_justseen(iterable, key=None):
     ['A', 'B', 'C', 'A', 'D']
 
     """
-    return map(next, map(operator.itemgetter(1), groupby(iterable, key)))
+    if key is None:
+        return map(itemgetter(0), groupby(iterable))
+
+    return map(next, map(itemgetter(1), groupby(iterable, key)))
+
+
+def unique(iterable, key=None, reverse=False):
+    """Yields unique elements in sorted order.
+
+    >>> list(unique([[1, 2], [3, 4], [1, 2]]))
+    [[1, 2], [3, 4]]
+
+    *key* and *reverse* are passed to :func:`sorted`.
+
+    >>> list(unique('ABBcCAD', str.casefold))
+    ['A', 'B', 'c', 'D']
+    >>> list(unique('ABBcCAD', str.casefold, reverse=True))
+    ['D', 'c', 'B', 'A']
+
+    The elements in *iterable* need not be hashable, but they must be
+    comparable for sorting to work.
+    """
+    sequenced = sorted(iterable, key=key, reverse=reverse)
+    return unique_justseen(sequenced, key=key)
 
 
 def iter_except(func, exception, first=None):
@@ -442,14 +594,22 @@ def iter_except(func, exception, first=None):
         >>> list(iter_except(l.pop, IndexError))
         [2, 1, 0]
 
+    Multiple exceptions can be specified as a stopping condition:
+
+        >>> l = [1, 2, 3, '...', 4, 5, 6]
+        >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError)))
+        [7, 6, 5]
+        >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError)))
+        [4, 3, 2]
+        >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError)))
+        []
+
     """
-    try:
+    with suppress(exception):
         if first is not None:
             yield first()
-        while 1:
+        while True:
             yield func()
-    except exception:
-        pass
 
 
 def first_true(iterable, default=None, pred=None):
@@ -485,7 +645,7 @@ def random_product(*args, repeat=1):
         ('a', 2, 'd', 3)
 
     This equivalent to taking a random selection from
-    ``itertools.product(*args, **kwarg)``.
+    ``itertools.product(*args, repeat=repeat)``.
 
     """
     pools = [tuple(pool) for pool in args] * repeat
@@ -601,20 +761,711 @@ def prepend(value, iterator):
 
 
 def convolve(signal, kernel):
-    """Convolve the iterable *signal* with the iterable *kernel*.
+    """Discrete linear convolution of two iterables.
+    Equivalent to polynomial multiplication.
+
+    For example, multiplying ``(x² -x - 20)`` by ``(x - 3)``
+    gives ``(x³ -4x² -17x + 60)``.
 
-        >>> signal = (1, 2, 3, 4, 5)
-        >>> kernel = [3, 2, 1]
-        >>> list(convolve(signal, kernel))
-        [3, 8, 14, 20, 26, 14, 5]
+        >>> list(convolve([1, -1, -20], [1, -3]))
+        [1, -4, -17, 60]
 
-    Note: the input arguments are not interchangeable, as the *kernel*
-    is immediately consumed and stored.
+    Examples of popular kinds of kernels:
+
+    * The kernel ``[0.25, 0.25, 0.25, 0.25]`` computes a moving average.
+      For image data, this blurs the image and reduces noise.
+    * The kernel ``[1/2, 0, -1/2]`` estimates the first derivative of
+      a function evaluated at evenly spaced inputs.
+    * The kernel ``[1, -2, 1]`` estimates the second derivative of a
+      function evaluated at evenly spaced inputs.
+
+    Convolutions are mathematically commutative; however, the inputs are
+    evaluated differently.  The signal is consumed lazily and can be
+    infinite. The kernel is fully consumed before the calculations begin.
+
+    Supports all numeric types: int, float, complex, Decimal, Fraction.
+
+    References:
+
+    * Article:  https://betterexplained.com/articles/intuitive-convolution/
+    * Video by 3Blue1Brown:  https://www.youtube.com/watch?v=KuXjwB4LzSA
 
     """
+    # This implementation comes from an older version of the itertools
+    # documentation.  While the newer implementation is a bit clearer,
+    # this one was kept because the inlined window logic is faster
+    # and it avoids an unnecessary deque-to-tuple conversion.
     kernel = tuple(kernel)[::-1]
     n = len(kernel)
     window = deque([0], maxlen=n) * n
     for x in chain(signal, repeat(0, n - 1)):
         window.append(x)
-        yield sum(map(operator.mul, kernel, window))
+        yield _sumprod(kernel, window)
+
+
+def before_and_after(predicate, it):
+    """A variant of :func:`takewhile` that allows complete access to the
+    remainder of the iterator.
+
+         >>> it = iter('ABCdEfGhI')
+         >>> all_upper, remainder = before_and_after(str.isupper, it)
+         >>> ''.join(all_upper)
+         'ABC'
+         >>> ''.join(remainder) # takewhile() would lose the 'd'
+         'dEfGhI'
+
+    Note that the first iterator must be fully consumed before the second
+    iterator can generate valid results.
+    """
+    trues, after = tee(it)
+    trues = compress(takewhile(predicate, trues), zip(after))
+    return trues, after
+
+
+def triplewise(iterable):
+    """Return overlapping triplets from *iterable*.
+
+    >>> list(triplewise('ABCDE'))
+    [('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E')]
+
+    """
+    # This deviates from the itertools documentation recipe - see
+    # https://github.com/more-itertools/more-itertools/issues/889
+    t1, t2, t3 = tee(iterable, 3)
+    next(t3, None)
+    next(t3, None)
+    next(t2, None)
+    return zip(t1, t2, t3)
+
+
+def _sliding_window_islice(iterable, n):
+    # Fast path for small, non-zero values of n.
+    iterators = tee(iterable, n)
+    for i, iterator in enumerate(iterators):
+        next(islice(iterator, i, i), None)
+    return zip(*iterators)
+
+
+def _sliding_window_deque(iterable, n):
+    # Normal path for other values of n.
+    iterator = iter(iterable)
+    window = deque(islice(iterator, n - 1), maxlen=n)
+    for x in iterator:
+        window.append(x)
+        yield tuple(window)
+
+
+def sliding_window(iterable, n):
+    """Return a sliding window of width *n* over *iterable*.
+
+        >>> list(sliding_window(range(6), 4))
+        [(0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5)]
+
+    If *iterable* has fewer than *n* items, then nothing is yielded:
+
+        >>> list(sliding_window(range(3), 4))
+        []
+
+    For a variant with more features, see :func:`windowed`.
+    """
+    if n > 20:
+        return _sliding_window_deque(iterable, n)
+    elif n > 2:
+        return _sliding_window_islice(iterable, n)
+    elif n == 2:
+        return pairwise(iterable)
+    elif n == 1:
+        return zip(iterable)
+    else:
+        raise ValueError(f'n should be at least one, not {n}')
+
+
+def subslices(iterable):
+    """Return all contiguous non-empty subslices of *iterable*.
+
+        >>> list(subslices('ABC'))
+        [['A'], ['A', 'B'], ['A', 'B', 'C'], ['B'], ['B', 'C'], ['C']]
+
+    This is similar to :func:`substrings`, but emits items in a different
+    order.
+    """
+    seq = list(iterable)
+    slices = starmap(slice, combinations(range(len(seq) + 1), 2))
+    return map(getitem, repeat(seq), slices)
+
+
+def polynomial_from_roots(roots):
+    """Compute a polynomial's coefficients from its roots.
+
+    >>> roots = [5, -4, 3]            # (x - 5) * (x + 4) * (x - 3)
+    >>> polynomial_from_roots(roots)  # x³ - 4 x² - 17 x + 60
+    [1, -4, -17, 60]
+
+    Note that polynomial coefficients are specified in descending power order.
+
+    Supports all numeric types: int, float, complex, Decimal, Fraction.
+    """
+
+    # This recipe differs from the one in itertools docs in that it
+    # applies list() after each call to convolve().  This avoids
+    # hitting stack limits with nested generators.
+
+    poly = [1]
+    for root in roots:
+        poly = list(convolve(poly, (1, -root)))
+    return poly
+
+
+def iter_index(iterable, value, start=0, stop=None):
+    """Yield the index of each place in *iterable* that *value* occurs,
+    beginning with index *start* and ending before index *stop*.
+
+
+    >>> list(iter_index('AABCADEAF', 'A'))
+    [0, 1, 4, 7]
+    >>> list(iter_index('AABCADEAF', 'A', 1))  # start index is inclusive
+    [1, 4, 7]
+    >>> list(iter_index('AABCADEAF', 'A', 1, 7))  # stop index is not inclusive
+    [1, 4]
+
+    The behavior for non-scalar *values* matches the built-in Python types.
+
+    >>> list(iter_index('ABCDABCD', 'AB'))
+    [0, 4]
+    >>> list(iter_index([0, 1, 2, 3, 0, 1, 2, 3], [0, 1]))
+    []
+    >>> list(iter_index([[0, 1], [2, 3], [0, 1], [2, 3]], [0, 1]))
+    [0, 2]
+
+    See :func:`locate` for a more general means of finding the indexes
+    associated with particular values.
+
+    """
+    seq_index = getattr(iterable, 'index', None)
+    if seq_index is None:
+        # Slow path for general iterables
+        iterator = islice(iterable, start, stop)
+        for i, element in enumerate(iterator, start):
+            if element is value or element == value:
+                yield i
+    else:
+        # Fast path for sequences
+        stop = len(iterable) if stop is None else stop
+        i = start - 1
+        with suppress(ValueError):
+            while True:
+                yield (i := seq_index(value, i + 1, stop))
+
+
+def sieve(n):
+    """Yield the primes less than n.
+
+    >>> list(sieve(30))
+    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
+
+    """
+    # This implementation comes from an older version of the itertools
+    # documentation.  The newer implementation is easier to read but is
+    # less lazy.
+    if n > 2:
+        yield 2
+    start = 3
+    data = bytearray((0, 1)) * (n // 2)
+    for p in iter_index(data, 1, start, stop=isqrt(n) + 1):
+        yield from iter_index(data, 1, start, p * p)
+        data[p * p : n : p + p] = bytes(len(range(p * p, n, p + p)))
+        start = p * p
+    yield from iter_index(data, 1, start)
+
+
+def _batched(iterable, n, *, strict=False):  # pragma: no cover
+    """Batch data into tuples of length *n*. If the number of items in
+    *iterable* is not divisible by *n*:
+    * The last batch will be shorter if *strict* is ``False``.
+    * :exc:`ValueError` will be raised if *strict* is ``True``.
+
+    >>> list(batched('ABCDEFG', 3))
+    [('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]
+
+    On Python 3.13 and above, this is an alias for :func:`itertools.batched`.
+    """
+    if n < 1:
+        raise ValueError('n must be at least one')
+    iterator = iter(iterable)
+    while batch := tuple(islice(iterator, n)):
+        if strict and len(batch) != n:
+            raise ValueError('batched(): incomplete batch')
+        yield batch
+
+
+if hexversion >= 0x30D00A2:  # pragma: no cover
+    from itertools import batched as itertools_batched
+
+    def batched(iterable, n, *, strict=False):
+        return itertools_batched(iterable, n, strict=strict)
+
+    batched.__doc__ = _batched.__doc__
+else:  # pragma: no cover
+    batched = _batched
+
+
+def transpose(it):
+    """Swap the rows and columns of the input matrix.
+
+    >>> list(transpose([(1, 2, 3), (11, 22, 33)]))
+    [(1, 11), (2, 22), (3, 33)]
+
+    The caller should ensure that the dimensions of the input are compatible.
+    If the input is empty, no output will be produced.
+    """
+    return _zip_strict(*it)
+
+
+def _is_scalar(value, stringlike=(str, bytes)):
+    "Scalars are bytes, strings, and non-iterables."
+    try:
+        iter(value)
+    except TypeError:
+        return True
+    return isinstance(value, stringlike)
+
+
+def _flatten_tensor(tensor):
+    "Depth-first iterator over scalars in a tensor."
+    iterator = iter(tensor)
+    while True:
+        try:
+            value = next(iterator)
+        except StopIteration:
+            return iterator
+        iterator = chain((value,), iterator)
+        if _is_scalar(value):
+            return iterator
+        iterator = chain.from_iterable(iterator)
+
+
+def reshape(matrix, shape):
+    """Change the shape of a *matrix*.
+
+    If *shape* is an integer, the matrix must be two dimensional
+    and the shape is interpreted as the desired number of columns:
+
+        >>> matrix = [(0, 1), (2, 3), (4, 5)]
+        >>> cols = 3
+        >>> list(reshape(matrix, cols))
+        [(0, 1, 2), (3, 4, 5)]
+
+    If *shape* is a tuple (or other iterable), the input matrix can have
+    any number of dimensions. It will first be flattened and then rebuilt
+    to the desired shape which can also be multidimensional:
+
+        >>> matrix = [(0, 1), (2, 3), (4, 5)]    # Start with a 3 x 2 matrix
+
+        >>> list(reshape(matrix, (2, 3)))        # Make a 2 x 3 matrix
+        [(0, 1, 2), (3, 4, 5)]
+
+        >>> list(reshape(matrix, (6,)))          # Make a vector of length six
+        [0, 1, 2, 3, 4, 5]
+
+        >>> list(reshape(matrix, (2, 1, 3, 1)))  # Make 2 x 1 x 3 x 1 tensor
+        [(((0,), (1,), (2,)),), (((3,), (4,), (5,)),)]
+
+    Each dimension is assumed to be uniform, either all arrays or all scalars.
+    Flattening stops when the first value in a dimension is a scalar.
+    Scalars are bytes, strings, and non-iterables.
+    The reshape iterator stops when the requested shape is complete
+    or when the input is exhausted, whichever comes first.
+
+    """
+    if isinstance(shape, int):
+        return batched(chain.from_iterable(matrix), shape)
+    first_dim, *dims = shape
+    scalar_stream = _flatten_tensor(matrix)
+    reshaped = reduce(batched, reversed(dims), scalar_stream)
+    return islice(reshaped, first_dim)
+
+
+def matmul(m1, m2):
+    """Multiply two matrices.
+
+    >>> list(matmul([(7, 5), (3, 5)], [(2, 5), (7, 9)]))
+    [(49, 80), (41, 60)]
+
+    The caller should ensure that the dimensions of the input matrices are
+    compatible with each other.
+
+    Supports all numeric types: int, float, complex, Decimal, Fraction.
+    """
+    n = len(m2[0])
+    return batched(starmap(_sumprod, product(m1, transpose(m2))), n)
+
+
+def _factor_pollard(n):
+    # Return a factor of n using Pollard's rho algorithm.
+    # Efficient when n is odd and composite.
+    for b in range(1, n):
+        x = y = 2
+        d = 1
+        while d == 1:
+            x = (x * x + b) % n
+            y = (y * y + b) % n
+            y = (y * y + b) % n
+            d = gcd(x - y, n)
+        if d != n:
+            return d
+    raise ValueError('prime or under 5')  # pragma: no cover
+
+
+_primes_below_211 = tuple(sieve(211))
+
+
+def factor(n):
+    """Yield the prime factors of n.
+
+    >>> list(factor(360))
+    [2, 2, 2, 3, 3, 5]
+
+    Finds small factors with trial division.  Larger factors are
+    either verified as prime with ``is_prime`` or split into
+    smaller factors with Pollard's rho algorithm.
+    """
+
+    # Corner case reduction
+    if n < 2:
+        return
+
+    # Trial division reduction
+    for prime in _primes_below_211:
+        while not n % prime:
+            yield prime
+            n //= prime
+
+    # Pollard's rho reduction
+    primes = []
+    todo = [n] if n > 1 else []
+    for n in todo:
+        if n < 211**2 or is_prime(n):
+            primes.append(n)
+        else:
+            fact = _factor_pollard(n)
+            todo += (fact, n // fact)
+    yield from sorted(primes)
+
+
+def polynomial_eval(coefficients, x):
+    """Evaluate a polynomial at a specific value.
+
+    Computes with better numeric stability than Horner's method.
+
+    Evaluate ``x^3 - 4 * x^2 - 17 * x + 60`` at ``x = 2.5``:
+
+    >>> coefficients = [1, -4, -17, 60]
+    >>> x = 2.5
+    >>> polynomial_eval(coefficients, x)
+    8.125
+
+    Note that polynomial coefficients are specified in descending power order.
+
+    Supports all numeric types: int, float, complex, Decimal, Fraction.
+    """
+    n = len(coefficients)
+    if n == 0:
+        return type(x)(0)
+    powers = map(pow, repeat(x), reversed(range(n)))
+    return _sumprod(coefficients, powers)
+
+
+def sum_of_squares(it):
+    """Return the sum of the squares of the input values.
+
+    >>> sum_of_squares([10, 20, 30])
+    1400
+
+    Supports all numeric types: int, float, complex, Decimal, Fraction.
+    """
+    return _sumprod(*tee(it))
+
+
+def polynomial_derivative(coefficients):
+    """Compute the first derivative of a polynomial.
+
+    Evaluate the derivative of ``x³ - 4 x² - 17 x + 60``:
+
+    >>> coefficients = [1, -4, -17, 60]
+    >>> derivative_coefficients = polynomial_derivative(coefficients)
+    >>> derivative_coefficients
+    [3, -8, -17]
+
+    Note that polynomial coefficients are specified in descending power order.
+
+    Supports all numeric types: int, float, complex, Decimal, Fraction.
+    """
+    n = len(coefficients)
+    powers = reversed(range(1, n))
+    return list(map(mul, coefficients, powers))
+
+
+def totient(n):
+    """Return the count of natural numbers up to *n* that are coprime with *n*.
+
+    Euler's totient function φ(n) gives the number of totatives.
+    Totative are integers k in the range 1 ≤ k ≤ n such that gcd(n, k) = 1.
+
+    >>> n = 9
+    >>> totient(n)
+    6
+
+    >>> totatives = [x for x in range(1, n) if gcd(n, x) == 1]
+    >>> totatives
+    [1, 2, 4, 5, 7, 8]
+    >>> len(totatives)
+    6
+
+    Reference:  https://en.wikipedia.org/wiki/Euler%27s_totient_function
+
+    """
+    for prime in set(factor(n)):
+        n -= n // prime
+    return n
+
+
+# Miller–Rabin primality test: https://oeis.org/A014233
+_perfect_tests = [
+    (2047, (2,)),
+    (9080191, (31, 73)),
+    (4759123141, (2, 7, 61)),
+    (1122004669633, (2, 13, 23, 1662803)),
+    (2152302898747, (2, 3, 5, 7, 11)),
+    (3474749660383, (2, 3, 5, 7, 11, 13)),
+    (18446744073709551616, (2, 325, 9375, 28178, 450775, 9780504, 1795265022)),
+    (
+        3317044064679887385961981,
+        (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41),
+    ),
+]
+
+
+@lru_cache
+def _shift_to_odd(n):
+    'Return s, d such that 2**s * d == n'
+    s = ((n - 1) ^ n).bit_length() - 1
+    d = n >> s
+    assert (1 << s) * d == n and d & 1 and s >= 0
+    return s, d
+
+
+def _strong_probable_prime(n, base):
+    assert (n > 2) and (n & 1) and (2 <= base < n)
+
+    s, d = _shift_to_odd(n - 1)
+
+    x = pow(base, d, n)
+    if x == 1 or x == n - 1:
+        return True
+
+    for _ in range(s - 1):
+        x = x * x % n
+        if x == n - 1:
+            return True
+
+    return False
+
+
+# Separate instance of Random() that doesn't share state
+# with the default user instance of Random().
+_private_randrange = random.Random().randrange
+
+
+def is_prime(n):
+    """Return ``True`` if *n* is prime and ``False`` otherwise.
+
+    Basic examples:
+
+        >>> is_prime(37)
+        True
+        >>> is_prime(3 * 13)
+        False
+        >>> is_prime(18_446_744_073_709_551_557)
+        True
+
+    Find the next prime over one billion:
+
+        >>> next(filter(is_prime, count(10**9)))
+        1000000007
+
+    Generate random primes up to 200 bits and up to 60 decimal digits:
+
+        >>> from random import seed, randrange, getrandbits
+        >>> seed(18675309)
+
+        >>> next(filter(is_prime, map(getrandbits, repeat(200))))
+        893303929355758292373272075469392561129886005037663238028407
+
+        >>> next(filter(is_prime, map(randrange, repeat(10**60))))
+        269638077304026462407872868003560484232362454342414618963649
+
+    This function is exact for values of *n* below 10**24.  For larger inputs,
+    the probabilistic Miller-Rabin primality test has a less than 1 in 2**128
+    chance of a false positive.
+    """
+
+    if n < 17:
+        return n in {2, 3, 5, 7, 11, 13}
+
+    if not (n & 1 and n % 3 and n % 5 and n % 7 and n % 11 and n % 13):
+        return False
+
+    for limit, bases in _perfect_tests:
+        if n < limit:
+            break
+    else:
+        bases = (_private_randrange(2, n - 1) for i in range(64))
+
+    return all(_strong_probable_prime(n, base) for base in bases)
+
+
+def loops(n):
+    """Returns an iterable with *n* elements for efficient looping.
+    Like ``range(n)`` but doesn't create integers.
+
+    >>> i = 0
+    >>> for _ in loops(5):
+    ...     i += 1
+    >>> i
+    5
+
+    """
+    return repeat(None, n)
+
+
+def multinomial(*counts):
+    """Number of distinct arrangements of a multiset.
+
+    The expression ``multinomial(3, 4, 2)`` has several equivalent
+    interpretations:
+
+    * In the expansion of ``(a + b + c)⁹``, the coefficient of the
+      ``a³b⁴c²`` term is 1260.
+
+    * There are 1260 distinct ways to arrange 9 balls consisting of 3 reds, 4
+      greens, and 2 blues.
+
+    * There are 1260 unique ways to place 9 distinct objects into three bins
+      with sizes 3, 4, and 2.
+
+    The :func:`multinomial` function computes the length of
+    :func:`distinct_permutations`.  For example, there are 83,160 distinct
+    anagrams of the word "abracadabra":
+
+        >>> from more_itertools import distinct_permutations, ilen
+        >>> ilen(distinct_permutations('abracadabra'))
+        83160
+
+    This can be computed directly from the letter counts, 5a 2b 2r 1c 1d:
+
+        >>> from collections import Counter
+        >>> list(Counter('abracadabra').values())
+        [5, 2, 2, 1, 1]
+        >>> multinomial(5, 2, 2, 1, 1)
+        83160
+
+    A binomial coefficient is a special case of multinomial where there are
+    only two categories.  For example, the number of ways to arrange 12 balls
+    with 5 reds and 7 blues is ``multinomial(5, 7)`` or ``math.comb(12, 5)``.
+
+    Likewise, factorial is a special case of multinomial where
+    the multiplicities are all just 1 so that
+    ``multinomial(1, 1, 1, 1, 1, 1, 1) == math.factorial(7)``.
+
+    Reference:  https://en.wikipedia.org/wiki/Multinomial_theorem
+
+    """
+    return prod(map(comb, accumulate(counts), counts))
+
+
+def _running_median_minheap_and_maxheap(iterator):  # pragma: no cover
+    "Non-windowed running_median() for Python 3.14+"
+
+    read = iterator.__next__
+    lo = []  # max-heap
+    hi = []  # min-heap (same size as or one smaller than lo)
+
+    with suppress(StopIteration):
+        while True:
+            heappush_max(lo, heappushpop(hi, read()))
+            yield lo[0]
+
+            heappush(hi, heappushpop_max(lo, read()))
+            yield (lo[0] + hi[0]) / 2
+
+
+def _running_median_minheap_only(iterator):  # pragma: no cover
+    "Backport of non-windowed running_median() for Python 3.13 and prior."
+
+    read = iterator.__next__
+    lo = []  # max-heap (actually a minheap with negated values)
+    hi = []  # min-heap (same size as or one smaller than lo)
+
+    with suppress(StopIteration):
+        while True:
+            heappush(lo, -heappushpop(hi, read()))
+            yield -lo[0]
+
+            heappush(hi, -heappushpop(lo, -read()))
+            yield (hi[0] - lo[0]) / 2
+
+
+def _running_median_windowed(iterator, maxlen):
+    "Yield median of values in a sliding window."
+
+    window = deque()
+    ordered = []
+
+    for x in iterator:
+        window.append(x)
+        insort(ordered, x)
+
+        if len(ordered) > maxlen:
+            i = bisect_left(ordered, window.popleft())
+            del ordered[i]
+
+        n = len(ordered)
+        m = n // 2
+        yield ordered[m] if n & 1 else (ordered[m - 1] + ordered[m]) / 2
+
+
+def running_median(iterable, *, maxlen=None):
+    """Cumulative median of values seen so far or values in a sliding window.
+
+    Set *maxlen* to a positive integer to specify the maximum size
+    of the sliding window.  The default of *None* is equivalent to
+    an unbounded window.
+
+    For example:
+
+        >>> list(running_median([5.0, 9.0, 4.0, 12.0, 8.0, 9.0]))
+        [5.0, 7.0, 5.0, 7.0, 8.0, 8.5]
+        >>> list(running_median([5.0, 9.0, 4.0, 12.0, 8.0, 9.0], maxlen=3))
+        [5.0, 7.0, 5.0, 9.0, 8.0, 9.0]
+
+    Supports numeric types such as int, float, Decimal, and Fraction,
+    but not complex numbers which are unorderable.
+
+    On version Python 3.13 and prior, max-heaps are simulated with
+    negative values. The negation causes Decimal inputs to apply context
+    rounding, making the results slightly different than that obtained
+    by statistics.median().
+    """
+
+    iterator = iter(iterable)
+
+    if maxlen is not None:
+        maxlen = index(maxlen)
+        if maxlen <= 0:
+            raise ValueError('Window size should be positive')
+        return _running_median_windowed(iterator, maxlen)
+
+    if not _max_heap_available:
+        return _running_median_minheap_only(iterator)  # pragma: no cover
+
+    return _running_median_minheap_and_maxheap(iterator)  # pragma: no cover
diff --git a/setuptools/_vendor/more_itertools/recipes.pyi b/setuptools/_vendor/more_itertools/recipes.pyi
index 5e39d96390..de3d0a1777 100644
--- a/setuptools/_vendor/more_itertools/recipes.pyi
+++ b/setuptools/_vendor/more_itertools/recipes.pyi
@@ -1,103 +1,205 @@
 """Stubs for more_itertools.recipes"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Iterator, Sequence
+from decimal import Decimal
+from fractions import Fraction
 from typing import (
     Any,
     Callable,
-    Iterable,
-    Iterator,
-    List,
-    Optional,
-    Tuple,
     TypeVar,
-    Union,
+    overload,
 )
-from typing_extensions import overload, Type
+
+__all__ = [
+    'all_equal',
+    'batched',
+    'before_and_after',
+    'consume',
+    'convolve',
+    'dotproduct',
+    'first_true',
+    'factor',
+    'flatten',
+    'grouper',
+    'is_prime',
+    'iter_except',
+    'iter_index',
+    'loops',
+    'matmul',
+    'multinomial',
+    'ncycles',
+    'nth',
+    'nth_combination',
+    'padnone',
+    'pad_none',
+    'pairwise',
+    'partition',
+    'polynomial_eval',
+    'polynomial_from_roots',
+    'polynomial_derivative',
+    'powerset',
+    'prepend',
+    'quantify',
+    'reshape',
+    'random_combination_with_replacement',
+    'random_combination',
+    'random_permutation',
+    'random_product',
+    'repeatfunc',
+    'roundrobin',
+    'running_median',
+    'sieve',
+    'sliding_window',
+    'subslices',
+    'sum_of_squares',
+    'tabulate',
+    'tail',
+    'take',
+    'totient',
+    'transpose',
+    'triplewise',
+    'unique',
+    'unique_everseen',
+    'unique_justseen',
+]
 
 # Type and type variable definitions
 _T = TypeVar('_T')
+_T1 = TypeVar('_T1')
+_T2 = TypeVar('_T2')
 _U = TypeVar('_U')
+_NumberT = TypeVar("_NumberT", float, Decimal, Fraction)
 
-def take(n: int, iterable: Iterable[_T]) -> List[_T]: ...
+def take(n: int, iterable: Iterable[_T]) -> list[_T]: ...
 def tabulate(
     function: Callable[[int], _T], start: int = ...
 ) -> Iterator[_T]: ...
 def tail(n: int, iterable: Iterable[_T]) -> Iterator[_T]: ...
-def consume(iterator: Iterable[object], n: Optional[int] = ...) -> None: ...
+def consume(iterator: Iterable[_T], n: int | None = ...) -> None: ...
 @overload
-def nth(iterable: Iterable[_T], n: int) -> Optional[_T]: ...
+def nth(iterable: Iterable[_T], n: int) -> _T | None: ...
 @overload
-def nth(iterable: Iterable[_T], n: int, default: _U) -> Union[_T, _U]: ...
-def all_equal(iterable: Iterable[object]) -> bool: ...
+def nth(iterable: Iterable[_T], n: int, default: _U) -> _T | _U: ...
+def all_equal(
+    iterable: Iterable[_T], key: Callable[[_T], _U] | None = ...
+) -> bool: ...
 def quantify(
     iterable: Iterable[_T], pred: Callable[[_T], bool] = ...
 ) -> int: ...
-def pad_none(iterable: Iterable[_T]) -> Iterator[Optional[_T]]: ...
-def padnone(iterable: Iterable[_T]) -> Iterator[Optional[_T]]: ...
+def pad_none(iterable: Iterable[_T]) -> Iterator[_T | None]: ...
+def padnone(iterable: Iterable[_T]) -> Iterator[_T | None]: ...
 def ncycles(iterable: Iterable[_T], n: int) -> Iterator[_T]: ...
-def dotproduct(vec1: Iterable[object], vec2: Iterable[object]) -> object: ...
+def dotproduct(vec1: Iterable[_T1], vec2: Iterable[_T2]) -> Any: ...
 def flatten(listOfLists: Iterable[Iterable[_T]]) -> Iterator[_T]: ...
 def repeatfunc(
-    func: Callable[..., _U], times: Optional[int] = ..., *args: Any
+    func: Callable[..., _U], times: int | None = ..., *args: Any
 ) -> Iterator[_U]: ...
-def pairwise(iterable: Iterable[_T]) -> Iterator[Tuple[_T, _T]]: ...
-@overload
-def grouper(
-    iterable: Iterable[_T], n: int
-) -> Iterator[Tuple[Optional[_T], ...]]: ...
-@overload
+def pairwise(iterable: Iterable[_T]) -> Iterator[tuple[_T, _T]]: ...
 def grouper(
-    iterable: Iterable[_T], n: int, fillvalue: _U
-) -> Iterator[Tuple[Union[_T, _U], ...]]: ...
-@overload
-def grouper(  # Deprecated interface
-    iterable: int, n: Iterable[_T]
-) -> Iterator[Tuple[Optional[_T], ...]]: ...
-@overload
-def grouper(  # Deprecated interface
-    iterable: int, n: Iterable[_T], fillvalue: _U
-) -> Iterator[Tuple[Union[_T, _U], ...]]: ...
+    iterable: Iterable[_T],
+    n: int,
+    incomplete: str = ...,
+    fillvalue: _U = ...,
+) -> Iterator[tuple[_T | _U, ...]]: ...
 def roundrobin(*iterables: Iterable[_T]) -> Iterator[_T]: ...
 def partition(
-    pred: Optional[Callable[[_T], object]], iterable: Iterable[_T]
-) -> Tuple[Iterator[_T], Iterator[_T]]: ...
-def powerset(iterable: Iterable[_T]) -> Iterator[Tuple[_T, ...]]: ...
+    pred: Callable[[_T], object] | None, iterable: Iterable[_T]
+) -> tuple[Iterator[_T], Iterator[_T]]: ...
+def powerset(iterable: Iterable[_T]) -> Iterator[tuple[_T, ...]]: ...
 def unique_everseen(
-    iterable: Iterable[_T], key: Optional[Callable[[_T], _U]] = ...
+    iterable: Iterable[_T], key: Callable[[_T], _U] | None = ...
 ) -> Iterator[_T]: ...
 def unique_justseen(
-    iterable: Iterable[_T], key: Optional[Callable[[_T], object]] = ...
+    iterable: Iterable[_T], key: Callable[[_T], object] | None = ...
+) -> Iterator[_T]: ...
+def unique(
+    iterable: Iterable[_T],
+    key: Callable[[_T], object] | None = ...,
+    reverse: bool = False,
 ) -> Iterator[_T]: ...
 @overload
 def iter_except(
-    func: Callable[[], _T], exception: Type[BaseException], first: None = ...
+    func: Callable[[], _T],
+    exception: type[BaseException] | tuple[type[BaseException], ...],
+    first: None = ...,
 ) -> Iterator[_T]: ...
 @overload
 def iter_except(
     func: Callable[[], _T],
-    exception: Type[BaseException],
+    exception: type[BaseException] | tuple[type[BaseException], ...],
     first: Callable[[], _U],
-) -> Iterator[Union[_T, _U]]: ...
+) -> Iterator[_T | _U]: ...
 @overload
 def first_true(
-    iterable: Iterable[_T], *, pred: Optional[Callable[[_T], object]] = ...
-) -> Optional[_T]: ...
+    iterable: Iterable[_T], *, pred: Callable[[_T], object] | None = ...
+) -> _T | None: ...
 @overload
 def first_true(
     iterable: Iterable[_T],
     default: _U,
-    pred: Optional[Callable[[_T], object]] = ...,
-) -> Union[_T, _U]: ...
+    pred: Callable[[_T], object] | None = ...,
+) -> _T | _U: ...
 def random_product(
     *args: Iterable[_T], repeat: int = ...
-) -> Tuple[_T, ...]: ...
+) -> tuple[_T, ...]: ...
 def random_permutation(
-    iterable: Iterable[_T], r: Optional[int] = ...
-) -> Tuple[_T, ...]: ...
-def random_combination(iterable: Iterable[_T], r: int) -> Tuple[_T, ...]: ...
+    iterable: Iterable[_T], r: int | None = ...
+) -> tuple[_T, ...]: ...
+def random_combination(iterable: Iterable[_T], r: int) -> tuple[_T, ...]: ...
 def random_combination_with_replacement(
     iterable: Iterable[_T], r: int
-) -> Tuple[_T, ...]: ...
+) -> tuple[_T, ...]: ...
 def nth_combination(
     iterable: Iterable[_T], r: int, index: int
-) -> Tuple[_T, ...]: ...
-def prepend(value: _T, iterator: Iterable[_U]) -> Iterator[Union[_T, _U]]: ...
+) -> tuple[_T, ...]: ...
+def prepend(value: _T, iterator: Iterable[_U]) -> Iterator[_T | _U]: ...
 def convolve(signal: Iterable[_T], kernel: Iterable[_T]) -> Iterator[_T]: ...
+def before_and_after(
+    predicate: Callable[[_T], bool], it: Iterable[_T]
+) -> tuple[Iterator[_T], Iterator[_T]]: ...
+def triplewise(iterable: Iterable[_T]) -> Iterator[tuple[_T, _T, _T]]: ...
+def sliding_window(
+    iterable: Iterable[_T], n: int
+) -> Iterator[tuple[_T, ...]]: ...
+def subslices(iterable: Iterable[_T]) -> Iterator[list[_T]]: ...
+def polynomial_from_roots(roots: Sequence[_T]) -> list[_T]: ...
+def iter_index(
+    iterable: Iterable[_T],
+    value: Any,
+    start: int | None = ...,
+    stop: int | None = ...,
+) -> Iterator[int]: ...
+def sieve(n: int) -> Iterator[int]: ...
+def _batched(
+    iterable: Iterable[_T], n: int, *, strict: bool = False
+) -> Iterator[tuple[_T, ...]]: ...
+
+batched = _batched
+
+def transpose(
+    it: Iterable[Iterable[_T]],
+) -> Iterator[tuple[_T, ...]]: ...
+@overload
+def reshape(
+    matrix: Iterable[Iterable[_T]], shape: int
+) -> Iterator[tuple[_T, ...]]: ...
+@overload
+def reshape(matrix: Iterable[Any], shape: Iterable[int]) -> Iterator[Any]: ...
+def matmul(m1: Sequence[_T], m2: Sequence[_T]) -> Iterator[tuple[_T]]: ...
+def _factor_trial(n: int) -> Iterator[int]: ...
+def _factor_pollard(n: int) -> int: ...
+def factor(n: int) -> Iterator[int]: ...
+def polynomial_eval(coefficients: Sequence[_T], x: _U) -> _U: ...
+def sum_of_squares(it: Iterable[_T]) -> _T: ...
+def polynomial_derivative(coefficients: Sequence[_T]) -> list[_T]: ...
+def totient(n: int) -> int: ...
+def _shift_to_odd(n: int) -> tuple[int, int]: ...
+def _strong_probable_prime(n: int, base: int) -> bool: ...
+def is_prime(n: int) -> bool: ...
+def loops(n: int) -> Iterator[None]: ...
+def multinomial(*counts: int) -> int: ...
+def running_median(
+    iterable: Iterable[_NumberT], *, maxlen: int | None = ...
+) -> Iterator[_NumberT]: ...
diff --git a/setuptools/_vendor/ordered_set-3.1.1.dist-info/INSTALLER b/setuptools/_vendor/ordered_set-3.1.1.dist-info/INSTALLER
deleted file mode 100644
index a1b589e38a..0000000000
--- a/setuptools/_vendor/ordered_set-3.1.1.dist-info/INSTALLER
+++ /dev/null
@@ -1 +0,0 @@
-pip
diff --git a/setuptools/_vendor/ordered_set-3.1.1.dist-info/METADATA b/setuptools/_vendor/ordered_set-3.1.1.dist-info/METADATA
deleted file mode 100644
index 4c64d142b9..0000000000
--- a/setuptools/_vendor/ordered_set-3.1.1.dist-info/METADATA
+++ /dev/null
@@ -1,155 +0,0 @@
-Metadata-Version: 2.1
-Name: ordered-set
-Version: 3.1.1
-Summary: A MutableSet that remembers its order, so that every entry has an index.
-Home-page: https://github.com/LuminosoInsight/ordered-set
-Maintainer: Robyn Speer
-Maintainer-email: rspeer@luminoso.com
-License: MIT-LICENSE
-Platform: any
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: MIT License
-Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 2
-Classifier: Programming Language :: Python :: 2.7
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3.4
-Classifier: Programming Language :: Python :: 3.5
-Classifier: Programming Language :: Python :: 3.6
-Classifier: Programming Language :: Python :: 3.7
-Classifier: Programming Language :: Python :: Implementation :: CPython
-Classifier: Programming Language :: Python :: Implementation :: PyPy
-Requires-Python: >=2.7
-Description-Content-Type: text/markdown
-License-File: MIT-LICENSE
-
-[![Travis](https://img.shields.io/travis/LuminosoInsight/ordered-set/master.svg?label=Travis%20CI)](https://travis-ci.org/LuminosoInsight/ordered-set)
-[![Codecov](https://codecov.io/github/LuminosoInsight/ordered-set/badge.svg?branch=master&service=github)](https://codecov.io/github/LuminosoInsight/ordered-set?branch=master)
-[![Pypi](https://img.shields.io/pypi/v/ordered-set.svg)](https://pypi.python.org/pypi/ordered-set)
-
-An OrderedSet is a mutable data structure that is a hybrid of a list and a set.
-It remembers the order of its entries, and every entry has an index number that
-can be looked up.
-
-
-## Usage examples
-
-An OrderedSet is created and used like a set:
-
-    >>> from ordered_set import OrderedSet
-
-    >>> letters = OrderedSet('abracadabra')
-
-    >>> letters
-    OrderedSet(['a', 'b', 'r', 'c', 'd'])
-
-    >>> 'r' in letters
-    True
-
-It is efficient to find the index of an entry in an OrderedSet, or find an
-entry by its index. To help with this use case, the `.add()` method returns
-the index of the added item, whether it was already in the set or not.
-
-    >>> letters.index('r')
-    2
-
-    >>> letters[2]
-    'r'
-
-    >>> letters.add('r')
-    2
-
-    >>> letters.add('x')
-    5
-
-OrderedSets implement the union (`|`), intersection (`&`), and difference (`-`)
-operators like sets do.
-
-    >>> letters |= OrderedSet('shazam')
-
-    >>> letters
-    OrderedSet(['a', 'b', 'r', 'c', 'd', 'x', 's', 'h', 'z', 'm'])
-
-    >>> letters & set('aeiou')
-    OrderedSet(['a'])
-
-    >>> letters -= 'abcd'
-
-    >>> letters
-    OrderedSet(['r', 'x', 's', 'h', 'z', 'm'])
-
-The `__getitem__()` and `index()` methods have been extended to accept any
-iterable except a string, returning a list, to perform NumPy-like "fancy
-indexing".
-
-    >>> letters = OrderedSet('abracadabra')
-
-    >>> letters[[0, 2, 3]]
-    ['a', 'r', 'c']
-
-    >>> letters.index(['a', 'r', 'c'])
-    [0, 2, 3]
-
-OrderedSet implements `__getstate__` and `__setstate__` so it can be pickled,
-and implements the abstract base classes `collections.MutableSet` and
-`collections.Sequence`.
-
-
-## Interoperability with NumPy and Pandas
-
-An OrderedSet can be used as a bi-directional mapping between a sparse
-vocabulary and dense index numbers. As of version 3.1, it accepts NumPy arrays
-of index numbers as well as lists.
-
-This combination of features makes OrderedSet a simple implementation of many
-of the things that `pandas.Index` is used for, and many of its operations are
-faster than the equivalent pandas operations.
-
-For further compatibility with pandas.Index, `get_loc` (the pandas method for
-looking up a single index) and `get_indexer` (the pandas method for fancy
-indexing in reverse) are both aliases for `index` (which handles both cases
-in OrderedSet).
-
-
-## Type hinting
-To use type hinting features install `ordered-set-stubs` package from
-[PyPI](https://pypi.org/project/ordered-set-stubs/):
-
-    $ pip install ordered-set-stubs
-
-
-## Authors
-
-OrderedSet was implemented by Robyn Speer. Jon Crall contributed changes and
-tests to make it fit the Python set API.
-
-
-## Comparisons
-
-The original implementation of OrderedSet was a [recipe posted to ActiveState
-Recipes][recipe] by Raymond Hettiger, released under the MIT license.
-
-[recipe]: https://code.activestate.com/recipes/576694-orderedset/
-
-Hettiger's implementation kept its content in a doubly-linked list referenced by a
-dict. As a result, looking up an item by its index was an O(N) operation, while
-deletion was O(1).
-
-This version makes different trade-offs for the sake of efficient lookups. Its
-content is a standard Python list instead of a doubly-linked list. This
-provides O(1) lookups by index at the expense of O(N) deletion, as well as
-slightly faster iteration.
-
-In Python 3.6 and later, the built-in `dict` type is inherently ordered. If you
-ignore the dictionary values, that also gives you a simple ordered set, with
-fast O(1) insertion, deletion, iteration and membership testing. However, `dict`
-does not provide the list-like random access features of OrderedSet. You
-would have to convert it to a list in O(N) to look up the index of an entry or
-look up an entry by its index.
-
-
-## Compatibility
-
-OrderedSet is automatically tested on Python 2.7, 3.4, 3.5, 3.6, and 3.7.
-We've checked more informally that it works on PyPy and PyPy3.
diff --git a/setuptools/_vendor/ordered_set-3.1.1.dist-info/RECORD b/setuptools/_vendor/ordered_set-3.1.1.dist-info/RECORD
deleted file mode 100644
index 3c699595fb..0000000000
--- a/setuptools/_vendor/ordered_set-3.1.1.dist-info/RECORD
+++ /dev/null
@@ -1,9 +0,0 @@
-__pycache__/ordered_set.cpython-311.pyc,,
-ordered_set-3.1.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-ordered_set-3.1.1.dist-info/METADATA,sha256=qEaJM9CbGNixB_jvfohisKbXTUjcef6nCCcBJju6f4U,5357
-ordered_set-3.1.1.dist-info/MIT-LICENSE,sha256=TvRE7qUSUBcd0ols7wgNf3zDEEJWW7kv7WDRySrMBBE,1071
-ordered_set-3.1.1.dist-info/RECORD,,
-ordered_set-3.1.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-ordered_set-3.1.1.dist-info/WHEEL,sha256=a-zpFRIJzOq5QfuhBzbhiA1eHTzNCJn8OdRvhdNX0Rk,110
-ordered_set-3.1.1.dist-info/top_level.txt,sha256=NTY2_aDi1Do9fl3Z9EmWPxasFkUeW2dzO2D3RDx5CfM,12
-ordered_set.py,sha256=dbaCcs27dyN9gnMWGF5nA_BrVn6Q-NrjKYJpV9_fgBs,15130
diff --git a/setuptools/_vendor/ordered_set-3.1.1.dist-info/WHEEL b/setuptools/_vendor/ordered_set-3.1.1.dist-info/WHEEL
deleted file mode 100644
index f771c29b87..0000000000
--- a/setuptools/_vendor/ordered_set-3.1.1.dist-info/WHEEL
+++ /dev/null
@@ -1,6 +0,0 @@
-Wheel-Version: 1.0
-Generator: bdist_wheel (0.40.0)
-Root-Is-Purelib: true
-Tag: py2-none-any
-Tag: py3-none-any
-
diff --git a/setuptools/_vendor/ordered_set-3.1.1.dist-info/top_level.txt b/setuptools/_vendor/ordered_set-3.1.1.dist-info/top_level.txt
deleted file mode 100644
index 1c191eef52..0000000000
--- a/setuptools/_vendor/ordered_set-3.1.1.dist-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-ordered_set
diff --git a/setuptools/_vendor/ordered_set.py b/setuptools/_vendor/ordered_set.py
deleted file mode 100644
index 14876000de..0000000000
--- a/setuptools/_vendor/ordered_set.py
+++ /dev/null
@@ -1,488 +0,0 @@
-"""
-An OrderedSet is a custom MutableSet that remembers its order, so that every
-entry has an index that can be looked up.
-
-Based on a recipe originally posted to ActiveState Recipes by Raymond Hettiger,
-and released under the MIT license.
-"""
-import itertools as it
-from collections import deque
-
-try:
-    # Python 3
-    from collections.abc import MutableSet, Sequence
-except ImportError:
-    # Python 2.7
-    from collections import MutableSet, Sequence
-
-SLICE_ALL = slice(None)
-__version__ = "3.1"
-
-
-def is_iterable(obj):
-    """
-    Are we being asked to look up a list of things, instead of a single thing?
-    We check for the `__iter__` attribute so that this can cover types that
-    don't have to be known by this module, such as NumPy arrays.
-
-    Strings, however, should be considered as atomic values to look up, not
-    iterables. The same goes for tuples, since they are immutable and therefore
-    valid entries.
-
-    We don't need to check for the Python 2 `unicode` type, because it doesn't
-    have an `__iter__` attribute anyway.
-    """
-    return (
-        hasattr(obj, "__iter__")
-        and not isinstance(obj, str)
-        and not isinstance(obj, tuple)
-    )
-
-
-class OrderedSet(MutableSet, Sequence):
-    """
-    An OrderedSet is a custom MutableSet that remembers its order, so that
-    every entry has an index that can be looked up.
-
-    Example:
-        >>> OrderedSet([1, 1, 2, 3, 2])
-        OrderedSet([1, 2, 3])
-    """
-
-    def __init__(self, iterable=None):
-        self.items = []
-        self.map = {}
-        if iterable is not None:
-            self |= iterable
-
-    def __len__(self):
-        """
-        Returns the number of unique elements in the ordered set
-
-        Example:
-            >>> len(OrderedSet([]))
-            0
-            >>> len(OrderedSet([1, 2]))
-            2
-        """
-        return len(self.items)
-
-    def __getitem__(self, index):
-        """
-        Get the item at a given index.
-
-        If `index` is a slice, you will get back that slice of items, as a
-        new OrderedSet.
-
-        If `index` is a list or a similar iterable, you'll get a list of
-        items corresponding to those indices. This is similar to NumPy's
-        "fancy indexing". The result is not an OrderedSet because you may ask
-        for duplicate indices, and the number of elements returned should be
-        the number of elements asked for.
-
-        Example:
-            >>> oset = OrderedSet([1, 2, 3])
-            >>> oset[1]
-            2
-        """
-        if isinstance(index, slice) and index == SLICE_ALL:
-            return self.copy()
-        elif is_iterable(index):
-            return [self.items[i] for i in index]
-        elif hasattr(index, "__index__") or isinstance(index, slice):
-            result = self.items[index]
-            if isinstance(result, list):
-                return self.__class__(result)
-            else:
-                return result
-        else:
-            raise TypeError("Don't know how to index an OrderedSet by %r" % index)
-
-    def copy(self):
-        """
-        Return a shallow copy of this object.
-
-        Example:
-            >>> this = OrderedSet([1, 2, 3])
-            >>> other = this.copy()
-            >>> this == other
-            True
-            >>> this is other
-            False
-        """
-        return self.__class__(self)
-
-    def __getstate__(self):
-        if len(self) == 0:
-            # The state can't be an empty list.
-            # We need to return a truthy value, or else __setstate__ won't be run.
-            #
-            # This could have been done more gracefully by always putting the state
-            # in a tuple, but this way is backwards- and forwards- compatible with
-            # previous versions of OrderedSet.
-            return (None,)
-        else:
-            return list(self)
-
-    def __setstate__(self, state):
-        if state == (None,):
-            self.__init__([])
-        else:
-            self.__init__(state)
-
-    def __contains__(self, key):
-        """
-        Test if the item is in this ordered set
-
-        Example:
-            >>> 1 in OrderedSet([1, 3, 2])
-            True
-            >>> 5 in OrderedSet([1, 3, 2])
-            False
-        """
-        return key in self.map
-
-    def add(self, key):
-        """
-        Add `key` as an item to this OrderedSet, then return its index.
-
-        If `key` is already in the OrderedSet, return the index it already
-        had.
-
-        Example:
-            >>> oset = OrderedSet()
-            >>> oset.append(3)
-            0
-            >>> print(oset)
-            OrderedSet([3])
-        """
-        if key not in self.map:
-            self.map[key] = len(self.items)
-            self.items.append(key)
-        return self.map[key]
-
-    append = add
-
-    def update(self, sequence):
-        """
-        Update the set with the given iterable sequence, then return the index
-        of the last element inserted.
-
-        Example:
-            >>> oset = OrderedSet([1, 2, 3])
-            >>> oset.update([3, 1, 5, 1, 4])
-            4
-            >>> print(oset)
-            OrderedSet([1, 2, 3, 5, 4])
-        """
-        item_index = None
-        try:
-            for item in sequence:
-                item_index = self.add(item)
-        except TypeError:
-            raise ValueError(
-                "Argument needs to be an iterable, got %s" % type(sequence)
-            )
-        return item_index
-
-    def index(self, key):
-        """
-        Get the index of a given entry, raising an IndexError if it's not
-        present.
-
-        `key` can be an iterable of entries that is not a string, in which case
-        this returns a list of indices.
-
-        Example:
-            >>> oset = OrderedSet([1, 2, 3])
-            >>> oset.index(2)
-            1
-        """
-        if is_iterable(key):
-            return [self.index(subkey) for subkey in key]
-        return self.map[key]
-
-    # Provide some compatibility with pd.Index
-    get_loc = index
-    get_indexer = index
-
-    def pop(self):
-        """
-        Remove and return the last element from the set.
-
-        Raises KeyError if the set is empty.
-
-        Example:
-            >>> oset = OrderedSet([1, 2, 3])
-            >>> oset.pop()
-            3
-        """
-        if not self.items:
-            raise KeyError("Set is empty")
-
-        elem = self.items[-1]
-        del self.items[-1]
-        del self.map[elem]
-        return elem
-
-    def discard(self, key):
-        """
-        Remove an element.  Do not raise an exception if absent.
-
-        The MutableSet mixin uses this to implement the .remove() method, which
-        *does* raise an error when asked to remove a non-existent item.
-
-        Example:
-            >>> oset = OrderedSet([1, 2, 3])
-            >>> oset.discard(2)
-            >>> print(oset)
-            OrderedSet([1, 3])
-            >>> oset.discard(2)
-            >>> print(oset)
-            OrderedSet([1, 3])
-        """
-        if key in self:
-            i = self.map[key]
-            del self.items[i]
-            del self.map[key]
-            for k, v in self.map.items():
-                if v >= i:
-                    self.map[k] = v - 1
-
-    def clear(self):
-        """
-        Remove all items from this OrderedSet.
-        """
-        del self.items[:]
-        self.map.clear()
-
-    def __iter__(self):
-        """
-        Example:
-            >>> list(iter(OrderedSet([1, 2, 3])))
-            [1, 2, 3]
-        """
-        return iter(self.items)
-
-    def __reversed__(self):
-        """
-        Example:
-            >>> list(reversed(OrderedSet([1, 2, 3])))
-            [3, 2, 1]
-        """
-        return reversed(self.items)
-
-    def __repr__(self):
-        if not self:
-            return "%s()" % (self.__class__.__name__,)
-        return "%s(%r)" % (self.__class__.__name__, list(self))
-
-    def __eq__(self, other):
-        """
-        Returns true if the containers have the same items. If `other` is a
-        Sequence, then order is checked, otherwise it is ignored.
-
-        Example:
-            >>> oset = OrderedSet([1, 3, 2])
-            >>> oset == [1, 3, 2]
-            True
-            >>> oset == [1, 2, 3]
-            False
-            >>> oset == [2, 3]
-            False
-            >>> oset == OrderedSet([3, 2, 1])
-            False
-        """
-        # In Python 2 deque is not a Sequence, so treat it as one for
-        # consistent behavior with Python 3.
-        if isinstance(other, (Sequence, deque)):
-            # Check that this OrderedSet contains the same elements, in the
-            # same order, as the other object.
-            return list(self) == list(other)
-        try:
-            other_as_set = set(other)
-        except TypeError:
-            # If `other` can't be converted into a set, it's not equal.
-            return False
-        else:
-            return set(self) == other_as_set
-
-    def union(self, *sets):
-        """
-        Combines all unique items.
-        Each items order is defined by its first appearance.
-
-        Example:
-            >>> oset = OrderedSet.union(OrderedSet([3, 1, 4, 1, 5]), [1, 3], [2, 0])
-            >>> print(oset)
-            OrderedSet([3, 1, 4, 5, 2, 0])
-            >>> oset.union([8, 9])
-            OrderedSet([3, 1, 4, 5, 2, 0, 8, 9])
-            >>> oset | {10}
-            OrderedSet([3, 1, 4, 5, 2, 0, 10])
-        """
-        cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet
-        containers = map(list, it.chain([self], sets))
-        items = it.chain.from_iterable(containers)
-        return cls(items)
-
-    def __and__(self, other):
-        # the parent implementation of this is backwards
-        return self.intersection(other)
-
-    def intersection(self, *sets):
-        """
-        Returns elements in common between all sets. Order is defined only
-        by the first set.
-
-        Example:
-            >>> oset = OrderedSet.intersection(OrderedSet([0, 1, 2, 3]), [1, 2, 3])
-            >>> print(oset)
-            OrderedSet([1, 2, 3])
-            >>> oset.intersection([2, 4, 5], [1, 2, 3, 4])
-            OrderedSet([2])
-            >>> oset.intersection()
-            OrderedSet([1, 2, 3])
-        """
-        cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet
-        if sets:
-            common = set.intersection(*map(set, sets))
-            items = (item for item in self if item in common)
-        else:
-            items = self
-        return cls(items)
-
-    def difference(self, *sets):
-        """
-        Returns all elements that are in this set but not the others.
-
-        Example:
-            >>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]))
-            OrderedSet([1, 3])
-            >>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]), OrderedSet([3]))
-            OrderedSet([1])
-            >>> OrderedSet([1, 2, 3]) - OrderedSet([2])
-            OrderedSet([1, 3])
-            >>> OrderedSet([1, 2, 3]).difference()
-            OrderedSet([1, 2, 3])
-        """
-        cls = self.__class__
-        if sets:
-            other = set.union(*map(set, sets))
-            items = (item for item in self if item not in other)
-        else:
-            items = self
-        return cls(items)
-
-    def issubset(self, other):
-        """
-        Report whether another set contains this set.
-
-        Example:
-            >>> OrderedSet([1, 2, 3]).issubset({1, 2})
-            False
-            >>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})
-            True
-            >>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})
-            False
-        """
-        if len(self) > len(other):  # Fast check for obvious cases
-            return False
-        return all(item in other for item in self)
-
-    def issuperset(self, other):
-        """
-        Report whether this set contains another set.
-
-        Example:
-            >>> OrderedSet([1, 2]).issuperset([1, 2, 3])
-            False
-            >>> OrderedSet([1, 2, 3, 4]).issuperset({1, 2, 3})
-            True
-            >>> OrderedSet([1, 4, 3, 5]).issuperset({1, 2, 3})
-            False
-        """
-        if len(self) < len(other):  # Fast check for obvious cases
-            return False
-        return all(item in self for item in other)
-
-    def symmetric_difference(self, other):
-        """
-        Return the symmetric difference of two OrderedSets as a new set.
-        That is, the new set will contain all elements that are in exactly
-        one of the sets.
-
-        Their order will be preserved, with elements from `self` preceding
-        elements from `other`.
-
-        Example:
-            >>> this = OrderedSet([1, 4, 3, 5, 7])
-            >>> other = OrderedSet([9, 7, 1, 3, 2])
-            >>> this.symmetric_difference(other)
-            OrderedSet([4, 5, 9, 2])
-        """
-        cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet
-        diff1 = cls(self).difference(other)
-        diff2 = cls(other).difference(self)
-        return diff1.union(diff2)
-
-    def _update_items(self, items):
-        """
-        Replace the 'items' list of this OrderedSet with a new one, updating
-        self.map accordingly.
-        """
-        self.items = items
-        self.map = {item: idx for (idx, item) in enumerate(items)}
-
-    def difference_update(self, *sets):
-        """
-        Update this OrderedSet to remove items from one or more other sets.
-
-        Example:
-            >>> this = OrderedSet([1, 2, 3])
-            >>> this.difference_update(OrderedSet([2, 4]))
-            >>> print(this)
-            OrderedSet([1, 3])
-
-            >>> this = OrderedSet([1, 2, 3, 4, 5])
-            >>> this.difference_update(OrderedSet([2, 4]), OrderedSet([1, 4, 6]))
-            >>> print(this)
-            OrderedSet([3, 5])
-        """
-        items_to_remove = set()
-        for other in sets:
-            items_to_remove |= set(other)
-        self._update_items([item for item in self.items if item not in items_to_remove])
-
-    def intersection_update(self, other):
-        """
-        Update this OrderedSet to keep only items in another set, preserving
-        their order in this set.
-
-        Example:
-            >>> this = OrderedSet([1, 4, 3, 5, 7])
-            >>> other = OrderedSet([9, 7, 1, 3, 2])
-            >>> this.intersection_update(other)
-            >>> print(this)
-            OrderedSet([1, 3, 7])
-        """
-        other = set(other)
-        self._update_items([item for item in self.items if item in other])
-
-    def symmetric_difference_update(self, other):
-        """
-        Update this OrderedSet to remove items from another set, then
-        add items from the other set that were not present in this set.
-
-        Example:
-            >>> this = OrderedSet([1, 4, 3, 5, 7])
-            >>> other = OrderedSet([9, 7, 1, 3, 2])
-            >>> this.symmetric_difference_update(other)
-            >>> print(this)
-            OrderedSet([4, 5, 9, 2])
-        """
-        items_to_add = [item for item in other if item not in self]
-        items_to_remove = set(other)
-        self._update_items(
-            [item for item in self.items if item not in items_to_remove] + items_to_add
-        )
diff --git a/setuptools/_vendor/packaging-23.1.dist-info/INSTALLER b/setuptools/_vendor/packaging-23.1.dist-info/INSTALLER
deleted file mode 100644
index a1b589e38a..0000000000
--- a/setuptools/_vendor/packaging-23.1.dist-info/INSTALLER
+++ /dev/null
@@ -1 +0,0 @@
-pip
diff --git a/setuptools/_vendor/packaging-23.1.dist-info/LICENSE b/setuptools/_vendor/packaging-23.1.dist-info/LICENSE
deleted file mode 100644
index 6f62d44e4e..0000000000
--- a/setuptools/_vendor/packaging-23.1.dist-info/LICENSE
+++ /dev/null
@@ -1,3 +0,0 @@
-This 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.
diff --git a/setuptools/_vendor/packaging-23.1.dist-info/LICENSE.APACHE b/setuptools/_vendor/packaging-23.1.dist-info/LICENSE.APACHE
deleted file mode 100644
index f433b1a53f..0000000000
--- a/setuptools/_vendor/packaging-23.1.dist-info/LICENSE.APACHE
+++ /dev/null
@@ -1,177 +0,0 @@
-
-                                 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
diff --git a/setuptools/_vendor/packaging-23.1.dist-info/LICENSE.BSD b/setuptools/_vendor/packaging-23.1.dist-info/LICENSE.BSD
deleted file mode 100644
index 42ce7b75c9..0000000000
--- a/setuptools/_vendor/packaging-23.1.dist-info/LICENSE.BSD
+++ /dev/null
@@ -1,23 +0,0 @@
-Copyright (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.
diff --git a/setuptools/_vendor/packaging-23.1.dist-info/METADATA b/setuptools/_vendor/packaging-23.1.dist-info/METADATA
deleted file mode 100644
index c43882a826..0000000000
--- a/setuptools/_vendor/packaging-23.1.dist-info/METADATA
+++ /dev/null
@@ -1,99 +0,0 @@
-Metadata-Version: 2.1
-Name: packaging
-Version: 23.1
-Summary: Core utilities for Python packages
-Author-email: Donald Stufft 
-Requires-Python: >=3.7
-Description-Content-Type: text/x-rst
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: Apache Software License
-Classifier: License :: OSI Approved :: BSD License
-Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3 :: Only
-Classifier: Programming Language :: Python :: 3.7
-Classifier: Programming Language :: Python :: 3.8
-Classifier: Programming Language :: Python :: 3.9
-Classifier: Programming Language :: Python :: 3.10
-Classifier: Programming Language :: Python :: 3.11
-Classifier: Programming Language :: Python :: Implementation :: CPython
-Classifier: Programming Language :: Python :: Implementation :: PyPy
-Classifier: Typing :: Typed
-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, utilities.
-
-Documentation
--------------
-
-The `documentation`_ provides information and the API for the following:
-
-- Version Handling
-- Specifiers
-- Markers
-- Requirements
-- Tags
-- Utilities
-
-Installation
-------------
-
-Use ``pip`` to install these utilities::
-
-    pip install packaging
-
-Discussion
-----------
-
-If you run into bugs, you can file them in our `issue tracker`_.
-
-You can also join ``#pypa`` on Freenode to ask questions or get involved.
-
-
-.. _`documentation`: https://packaging.pypa.io/
-.. _`issue tracker`: https://github.com/pypa/packaging/issues
-
-
-Code of Conduct
----------------
-
-Everyone interacting in the packaging project's codebases, issue trackers, chat
-rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
-
-.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
-
-Contributing
-------------
-
-The ``CONTRIBUTING.rst`` file outlines how to contribute to this project as
-well as how to report a potential security issue. The documentation for this
-project also covers information about `project development`_ and `security`_.
-
-.. _`project development`: https://packaging.pypa.io/en/latest/development/
-.. _`security`: https://packaging.pypa.io/en/latest/security/
-
-Project History
----------------
-
-Please review the ``CHANGELOG.rst`` file or the `Changelog documentation`_ for
-recent changes and project history.
-
-.. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/
-
diff --git a/setuptools/_vendor/packaging-23.1.dist-info/RECORD b/setuptools/_vendor/packaging-23.1.dist-info/RECORD
deleted file mode 100644
index e240a8408d..0000000000
--- a/setuptools/_vendor/packaging-23.1.dist-info/RECORD
+++ /dev/null
@@ -1,37 +0,0 @@
-packaging-23.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-packaging-23.1.dist-info/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197
-packaging-23.1.dist-info/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
-packaging-23.1.dist-info/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344
-packaging-23.1.dist-info/METADATA,sha256=JnduJDlxs2IVeB-nIqAC3-HyNcPhP_MADd9_k_MjmaI,3082
-packaging-23.1.dist-info/RECORD,,
-packaging-23.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-packaging-23.1.dist-info/WHEEL,sha256=rSgq_JpHF9fHR1lx53qwg_1-2LypZE_qmcuXbVUq948,81
-packaging/__init__.py,sha256=kYVZSmXT6CWInT4UJPDtrSQBAZu8fMuFBxpv5GsDTLk,501
-packaging/__pycache__/__init__.cpython-311.pyc,,
-packaging/__pycache__/_elffile.cpython-311.pyc,,
-packaging/__pycache__/_manylinux.cpython-311.pyc,,
-packaging/__pycache__/_musllinux.cpython-311.pyc,,
-packaging/__pycache__/_parser.cpython-311.pyc,,
-packaging/__pycache__/_structures.cpython-311.pyc,,
-packaging/__pycache__/_tokenizer.cpython-311.pyc,,
-packaging/__pycache__/markers.cpython-311.pyc,,
-packaging/__pycache__/metadata.cpython-311.pyc,,
-packaging/__pycache__/requirements.cpython-311.pyc,,
-packaging/__pycache__/specifiers.cpython-311.pyc,,
-packaging/__pycache__/tags.cpython-311.pyc,,
-packaging/__pycache__/utils.cpython-311.pyc,,
-packaging/__pycache__/version.cpython-311.pyc,,
-packaging/_elffile.py,sha256=hbmK8OD6Z7fY6hwinHEUcD1by7czkGiNYu7ShnFEk2k,3266
-packaging/_manylinux.py,sha256=ESGrDEVmBc8jYTtdZRAWiLk72lOzAKWeezFgoJ_MuBc,8926
-packaging/_musllinux.py,sha256=mvPk7FNjjILKRLIdMxR7IvJ1uggLgCszo-L9rjfpi0M,2524
-packaging/_parser.py,sha256=KJQkBh_Xbfb-qsB560YIEItrTpCZaOh4_YMfBtd5XIY,10194
-packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431
-packaging/_tokenizer.py,sha256=alCtbwXhOFAmFGZ6BQ-wCTSFoRAJ2z-ysIf7__MTJ_k,5292
-packaging/markers.py,sha256=eH-txS2zq1HdNpTd9LcZUcVIwewAiNU0grmq5wjKnOk,8208
-packaging/metadata.py,sha256=PjELMLxKG_iu3HWjKAOdKhuNrHfWgpdTF2Q4nObsZeM,16397
-packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-packaging/requirements.py,sha256=hJzvtJyAvENc_VfwfhnOZV1851-VW8JCGh-R96NE4Pc,3287
-packaging/specifiers.py,sha256=ZOpqL_w_Kj6ZF_OWdliQUzhEyHlDbi6989kr-sF5GHs,39206
-packaging/tags.py,sha256=_1gLX8h1SgpjAdYCP9XqU37zRjXtU5ZliGy3IM-WcSM,18106
-packaging/utils.py,sha256=es0cCezKspzriQ-3V88h3yJzxz028euV2sUwM61kE-o,4355
-packaging/version.py,sha256=2NH3E57hzRhn0BV9boUBvgPsxlTqLJeI0EpYQoNvGi0,16326
diff --git a/setuptools/_vendor/packaging-26.0.dist-info/INSTALLER b/setuptools/_vendor/packaging-26.0.dist-info/INSTALLER
new file mode 100644
index 0000000000..5c69047b2e
--- /dev/null
+++ b/setuptools/_vendor/packaging-26.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/pkg_resources/_vendor/packaging-23.1.dist-info/METADATA b/setuptools/_vendor/packaging-26.0.dist-info/METADATA
similarity index 85%
rename from pkg_resources/_vendor/packaging-23.1.dist-info/METADATA
rename to setuptools/_vendor/packaging-26.0.dist-info/METADATA
index c43882a826..3200e601f9 100644
--- a/pkg_resources/_vendor/packaging-23.1.dist-info/METADATA
+++ b/setuptools/_vendor/packaging-26.0.dist-info/METADATA
@@ -1,25 +1,29 @@
-Metadata-Version: 2.1
+Metadata-Version: 2.4
 Name: packaging
-Version: 23.1
+Version: 26.0
 Summary: Core utilities for Python packages
 Author-email: Donald Stufft 
-Requires-Python: >=3.7
+Requires-Python: >=3.8
 Description-Content-Type: text/x-rst
+License-Expression: Apache-2.0 OR BSD-2-Clause
 Classifier: Development Status :: 5 - Production/Stable
 Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: Apache Software License
-Classifier: License :: OSI Approved :: BSD License
 Classifier: Programming Language :: Python
 Classifier: Programming Language :: Python :: 3
 Classifier: Programming Language :: Python :: 3 :: Only
-Classifier: Programming Language :: Python :: 3.7
 Classifier: Programming Language :: Python :: 3.8
 Classifier: Programming Language :: Python :: 3.9
 Classifier: Programming Language :: Python :: 3.10
 Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
 Classifier: Programming Language :: Python :: Implementation :: CPython
 Classifier: Programming Language :: Python :: Implementation :: PyPy
 Classifier: Typing :: Typed
+License-File: LICENSE
+License-File: LICENSE.APACHE
+License-File: LICENSE.BSD
 Project-URL: Documentation, https://packaging.pypa.io/
 Project-URL: Source, https://github.com/pypa/packaging
 
@@ -38,7 +42,7 @@ 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, utilities.
+markers, requirements, tags, metadata, lockfiles, utilities.
 
 Documentation
 -------------
@@ -50,6 +54,8 @@ The `documentation`_ provides information and the API for the following:
 - Markers
 - Requirements
 - Tags
+- Metadata
+- Lockfiles
 - Utilities
 
 Installation
@@ -59,6 +65,8 @@ Use ``pip`` to install these utilities::
 
     pip install packaging
 
+The ``packaging`` library uses calendar-based versioning (``YY.N``).
+
 Discussion
 ----------
 
diff --git a/setuptools/_vendor/packaging-26.0.dist-info/RECORD b/setuptools/_vendor/packaging-26.0.dist-info/RECORD
new file mode 100644
index 0000000000..38cdeafd21
--- /dev/null
+++ b/setuptools/_vendor/packaging-26.0.dist-info/RECORD
@@ -0,0 +1,26 @@
+packaging-26.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+packaging-26.0.dist-info/METADATA,sha256=M2K7fWom2iliuo2qpHhc0LrKwhq6kIoRlcyPWVgKJlo,3309
+packaging-26.0.dist-info/RECORD,,
+packaging-26.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+packaging-26.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
+packaging-26.0.dist-info/licenses/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197
+packaging-26.0.dist-info/licenses/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
+packaging-26.0.dist-info/licenses/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344
+packaging/__init__.py,sha256=y4lVbpeBzCGk-IPDw5BGBZ_b0P3ukEEJZAbGYc6Ey8c,494
+packaging/_elffile.py,sha256=-sKkptYqzYw2-x3QByJa5mB4rfPWu1pxkZHRx1WAFCY,3211
+packaging/_manylinux.py,sha256=Hf6nB0cOrayEs96-p3oIXAgGnFquv20DO5l-o2_Xnv0,9559
+packaging/_musllinux.py,sha256=Z6swjH3MA7XS3qXnmMN7QPhqP3fnoYI0eQ18e9-HgAE,2707
+packaging/_parser.py,sha256=U_DajsEx2VoC_F46fSVV3hDKNCWoQYkPkasO3dld0ig,10518
+packaging/_structures.py,sha256=Hn49Ta8zV9Wo8GiCL8Nl2ARZY983Un3pruZGVNldPwE,1514
+packaging/_tokenizer.py,sha256=M8EwNIdXeL9NMFuFrQtiOKwjka_xFx8KjRQnfE8O_z8,5421
+packaging/licenses/__init__.py,sha256=TwXLHZCXwSgdFwRLPxW602T6mSieunSFHM6fp8pgW78,5819
+packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122
+packaging/markers.py,sha256=ZX-cLvW1S3cZcEc0fHI4z7zSx5U2T19yMpDP_mE-CYw,12771
+packaging/metadata.py,sha256=CWVZpN_HfoYMSSDuCP7igOvGgqA9AOmpW8f3qTisfnc,39360
+packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+packaging/pylock.py,sha256=-R1uNfJ4PaLto7Mg62YsGOHgvskuiIEqPwxOywl42Jk,22537
+packaging/requirements.py,sha256=PMCAWD8aNMnVD-6uZMedhBuAVX2573eZ4yPBLXmz04I,2870
+packaging/specifiers.py,sha256=EPNPimY_zFivthv1vdjZYz5IqkKGsnKR2yKh-EVyvZw,40797
+packaging/tags.py,sha256=cXLV1pJD3UtJlDg7Wz3zrfdQhRZqr8jumSAKKAAd2xE,22856
+packaging/utils.py,sha256=N4c6oZzFJy6klTZ3AnkNz7sSkJesuFWPp68LA3B5dAo,5040
+packaging/version.py,sha256=7XWlL2IDYLwDYC0ht6cFEhapLwLWbmyo4rb7sEFj0x8,23272
diff --git a/setuptools/_vendor/jaraco.text-3.7.0.dist-info/REQUESTED b/setuptools/_vendor/packaging-26.0.dist-info/REQUESTED
similarity index 100%
rename from setuptools/_vendor/jaraco.text-3.7.0.dist-info/REQUESTED
rename to setuptools/_vendor/packaging-26.0.dist-info/REQUESTED
diff --git a/setuptools/_vendor/packaging-23.1.dist-info/WHEEL b/setuptools/_vendor/packaging-26.0.dist-info/WHEEL
similarity index 71%
rename from setuptools/_vendor/packaging-23.1.dist-info/WHEEL
rename to setuptools/_vendor/packaging-26.0.dist-info/WHEEL
index db4a255f3a..d8b9936dad 100644
--- a/setuptools/_vendor/packaging-23.1.dist-info/WHEEL
+++ b/setuptools/_vendor/packaging-26.0.dist-info/WHEEL
@@ -1,4 +1,4 @@
 Wheel-Version: 1.0
-Generator: flit 3.8.0
+Generator: flit 3.12.0
 Root-Is-Purelib: true
 Tag: py3-none-any
diff --git a/pkg_resources/_vendor/packaging-23.1.dist-info/LICENSE b/setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE
similarity index 100%
rename from pkg_resources/_vendor/packaging-23.1.dist-info/LICENSE
rename to setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE
diff --git a/pkg_resources/_vendor/packaging-23.1.dist-info/LICENSE.APACHE b/setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE.APACHE
similarity index 100%
rename from pkg_resources/_vendor/packaging-23.1.dist-info/LICENSE.APACHE
rename to setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE.APACHE
diff --git a/pkg_resources/_vendor/packaging-23.1.dist-info/LICENSE.BSD b/setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE.BSD
similarity index 100%
rename from pkg_resources/_vendor/packaging-23.1.dist-info/LICENSE.BSD
rename to setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE.BSD
diff --git a/setuptools/_vendor/packaging/__init__.py b/setuptools/_vendor/packaging/__init__.py
index 13cadc7f04..21695a74b5 100644
--- a/setuptools/_vendor/packaging/__init__.py
+++ b/setuptools/_vendor/packaging/__init__.py
@@ -6,10 +6,10 @@
 __summary__ = "Core utilities for Python packages"
 __uri__ = "https://github.com/pypa/packaging"
 
-__version__ = "23.1"
+__version__ = "26.0"
 
 __author__ = "Donald Stufft and individual contributors"
 __email__ = "donald@stufft.io"
 
 __license__ = "BSD-2-Clause or Apache-2.0"
-__copyright__ = "2014-2019 %s" % __author__
+__copyright__ = f"2014 {__author__}"
diff --git a/setuptools/_vendor/packaging/_elffile.py b/setuptools/_vendor/packaging/_elffile.py
index 6fb19b30bb..497b064521 100644
--- a/setuptools/_vendor/packaging/_elffile.py
+++ b/setuptools/_vendor/packaging/_elffile.py
@@ -4,14 +4,15 @@
 This provides a class ``ELFFile`` that parses an ELF executable in a similar
 interface to ``ZipFile``. Only the read interface is implemented.
 
-Based on: https://gist.github.com/lyssdod/f51579ae8d93c8657a5564aefc2ffbca
 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, Optional, Tuple
+from typing import IO
 
 
 class ELFInvalid(ValueError):
@@ -46,8 +47,8 @@ def __init__(self, f: IO[bytes]) -> None:
 
         try:
             ident = self._read("16B")
-        except struct.error:
-            raise ELFInvalid("unable to parse identification")
+        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}")
@@ -65,11 +66,10 @@ def __init__(self, f: IO[bytes]) -> None:
                 (2, 1): ("HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)),  # 64-bit MSB.
             }[(self.capacity, self.encoding)]
-        except KeyError:
+        except KeyError as e:
             raise ELFInvalid(
-                f"unrecognized capacity ({self.capacity}) or "
-                f"encoding ({self.encoding})"
-            )
+                f"unrecognized capacity ({self.capacity}) or encoding ({self.encoding})"
+            ) from e
 
         try:
             (
@@ -87,11 +87,11 @@ def __init__(self, f: IO[bytes]) -> None:
         except struct.error as e:
             raise ELFInvalid("unable to parse machine and section information") from e
 
-    def _read(self, fmt: str) -> Tuple[int, ...]:
+    def _read(self, fmt: str) -> tuple[int, ...]:
         return struct.unpack(fmt, self._f.read(struct.calcsize(fmt)))
 
     @property
-    def interpreter(self) -> Optional[str]:
+    def interpreter(self) -> str | None:
         """
         The path recorded in the ``PT_INTERP`` section header.
         """
diff --git a/setuptools/_vendor/packaging/_manylinux.py b/setuptools/_vendor/packaging/_manylinux.py
index 449c655be6..0e79e8a882 100644
--- a/setuptools/_vendor/packaging/_manylinux.py
+++ b/setuptools/_vendor/packaging/_manylinux.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
 import collections
 import contextlib
 import functools
@@ -5,7 +7,7 @@
 import re
 import sys
 import warnings
-from typing import Dict, Generator, Iterator, NamedTuple, Optional, Tuple
+from typing import Generator, Iterator, NamedTuple, Sequence
 
 from ._elffile import EIClass, EIData, ELFFile, EMachine
 
@@ -13,11 +15,21 @@
 EF_ARM_ABI_VER5 = 0x05000000
 EF_ARM_ABI_FLOAT_HARD = 0x00000400
 
+_ALLOWED_ARCHS = {
+    "x86_64",
+    "aarch64",
+    "ppc64",
+    "ppc64le",
+    "s390x",
+    "loongarch64",
+    "riscv64",
+}
+
 
 # `os.PathLike` not a generic type until Python 3.9, so sticking with `str`
 # as the type for `path` until then.
 @contextlib.contextmanager
-def _parse_elf(path: str) -> Generator[Optional[ELFFile], None, None]:
+def _parse_elf(path: str) -> Generator[ELFFile | None, None, None]:
     try:
         with open(path, "rb") as f:
             yield ELFFile(f)
@@ -50,12 +62,12 @@ def _is_linux_i686(executable: str) -> bool:
         )
 
 
-def _have_compatible_abi(executable: str, arch: str) -> bool:
-    if arch == "armv7l":
+def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool:
+    if "armv7l" in archs:
         return _is_linux_armhf(executable)
-    if arch == "i686":
+    if "i686" in archs:
         return _is_linux_i686(executable)
-    return arch in {"x86_64", "aarch64", "ppc64", "ppc64le", "s390x"}
+    return any(arch in _ALLOWED_ARCHS for arch in archs)
 
 
 # If glibc ever changes its major version, we need to know what the last
@@ -63,7 +75,7 @@ def _have_compatible_abi(executable: str, arch: str) -> bool:
 # 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)
+_LAST_GLIBC_MINOR: dict[int, int] = collections.defaultdict(lambda: 50)
 
 
 class _GLibCVersion(NamedTuple):
@@ -71,7 +83,7 @@ class _GLibCVersion(NamedTuple):
     minor: int
 
 
-def _glibc_version_string_confstr() -> Optional[str]:
+def _glibc_version_string_confstr() -> str | None:
     """
     Primary implementation of glibc_version_string using os.confstr.
     """
@@ -81,7 +93,7 @@ def _glibc_version_string_confstr() -> Optional[str]:
     # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183
     try:
         # Should be a string like "glibc 2.17".
-        version_string: str = getattr(os, "confstr")("CS_GNU_LIBC_VERSION")
+        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):
@@ -90,12 +102,12 @@ def _glibc_version_string_confstr() -> Optional[str]:
     return version
 
 
-def _glibc_version_string_ctypes() -> Optional[str]:
+def _glibc_version_string_ctypes() -> str | None:
     """
     Fallback implementation of glibc_version_string using ctypes.
     """
     try:
-        import ctypes
+        import ctypes  # noqa: PLC0415
     except ImportError:
         return None
 
@@ -134,12 +146,12 @@ def _glibc_version_string_ctypes() -> Optional[str]:
     return version_str
 
 
-def _glibc_version_string() -> Optional[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) -> Tuple[int, int]:
+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
@@ -150,30 +162,30 @@ def _parse_glibc_version(version_str: str) -> Tuple[int, int]:
     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,"
-            f" got: {version_str}",
+            f"Expected glibc version with 2 components major.minor, got: {version_str}",
             RuntimeWarning,
+            stacklevel=2,
         )
-        return -1, -1
-    return int(m.group("major")), int(m.group("minor"))
+        return _GLibCVersion(-1, -1)
+    return _GLibCVersion(int(m.group("major")), int(m.group("minor")))
 
 
-@functools.lru_cache()
-def _get_glibc_version() -> Tuple[int, int]:
+@functools.lru_cache
+def _get_glibc_version() -> _GLibCVersion:
     version_str = _glibc_version_string()
     if version_str is None:
-        return (-1, -1)
+        return _GLibCVersion(-1, -1)
     return _parse_glibc_version(version_str)
 
 
 # From PEP 513, PEP 600
-def _is_compatible(name: str, arch: str, version: _GLibCVersion) -> bool:
+def _is_compatible(arch: str, version: _GLibCVersion) -> bool:
     sys_glibc = _get_glibc_version()
     if sys_glibc < version:
         return False
     # Check for presence of _manylinux module.
     try:
-        import _manylinux  # noqa
+        import _manylinux  # noqa: PLC0415
     except ImportError:
         return True
     if hasattr(_manylinux, "manylinux_compatible"):
@@ -181,34 +193,45 @@ def _is_compatible(name: str, arch: str, version: _GLibCVersion) -> bool:
         if result is not None:
             return bool(result)
         return True
-    if version == _GLibCVersion(2, 5):
-        if hasattr(_manylinux, "manylinux1_compatible"):
-            return bool(_manylinux.manylinux1_compatible)
-    if version == _GLibCVersion(2, 12):
-        if hasattr(_manylinux, "manylinux2010_compatible"):
-            return bool(_manylinux.manylinux2010_compatible)
-    if version == _GLibCVersion(2, 17):
-        if hasattr(_manylinux, "manylinux2014_compatible"):
-            return bool(_manylinux.manylinux2014_compatible)
+    if version == _GLibCVersion(2, 5) and hasattr(_manylinux, "manylinux1_compatible"):
+        return bool(_manylinux.manylinux1_compatible)
+    if version == _GLibCVersion(2, 12) and hasattr(
+        _manylinux, "manylinux2010_compatible"
+    ):
+        return bool(_manylinux.manylinux2010_compatible)
+    if version == _GLibCVersion(2, 17) and hasattr(
+        _manylinux, "manylinux2014_compatible"
+    ):
+        return bool(_manylinux.manylinux2014_compatible)
     return True
 
 
-_LEGACY_MANYLINUX_MAP = {
+_LEGACY_MANYLINUX_MAP: dict[_GLibCVersion, str] = {
     # CentOS 7 w/ glibc 2.17 (PEP 599)
-    (2, 17): "manylinux2014",
+    _GLibCVersion(2, 17): "manylinux2014",
     # CentOS 6 w/ glibc 2.12 (PEP 571)
-    (2, 12): "manylinux2010",
+    _GLibCVersion(2, 12): "manylinux2010",
     # CentOS 5 w/ glibc 2.5 (PEP 513)
-    (2, 5): "manylinux1",
+    _GLibCVersion(2, 5): "manylinux1",
 }
 
 
-def platform_tags(linux: str, arch: str) -> Iterator[str]:
-    if not _have_compatible_abi(sys.executable, arch):
+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 arch in {"x86_64", "i686"}:
+    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())
@@ -222,19 +245,18 @@ def platform_tags(linux: str, arch: str) -> Iterator[str]:
     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 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)
-            tag = "manylinux_{}_{}".format(*glibc_version)
-            if _is_compatible(tag, arch, glibc_version):
-                yield linux.replace("linux", tag)
-            # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.
-            if glibc_version in _LEGACY_MANYLINUX_MAP:
-                legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version]
-                if _is_compatible(legacy_tag, arch, glibc_version):
-                    yield linux.replace("linux", legacy_tag)
+    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}"
diff --git a/setuptools/_vendor/packaging/_musllinux.py b/setuptools/_vendor/packaging/_musllinux.py
index 706ba600a9..4e8116a79c 100644
--- a/setuptools/_vendor/packaging/_musllinux.py
+++ b/setuptools/_vendor/packaging/_musllinux.py
@@ -4,11 +4,13 @@
 linked against musl, and what musl version is used.
 """
 
+from __future__ import annotations
+
 import functools
 import re
 import subprocess
 import sys
-from typing import Iterator, NamedTuple, Optional
+from typing import Iterator, NamedTuple, Sequence
 
 from ._elffile import ELFFile
 
@@ -18,7 +20,7 @@ class _MuslVersion(NamedTuple):
     minor: int
 
 
-def _parse_musl_version(output: str) -> Optional[_MuslVersion]:
+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
@@ -28,8 +30,8 @@ def _parse_musl_version(output: str) -> Optional[_MuslVersion]:
     return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2)))
 
 
-@functools.lru_cache()
-def _get_musl_version(executable: str) -> Optional[_MuslVersion]:
+@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
@@ -47,24 +49,27 @@ def _get_musl_version(executable: str) -> Optional[_MuslVersion]:
         return None
     if ld is None or "musl" not in ld:
         return None
-    proc = subprocess.run([ld], stderr=subprocess.PIPE, universal_newlines=True)
+    proc = subprocess.run([ld], check=False, stderr=subprocess.PIPE, text=True)
     return _parse_musl_version(proc.stderr)
 
 
-def platform_tags(arch: str) -> Iterator[str]:
+def platform_tags(archs: Sequence[str]) -> Iterator[str]:
     """Generate musllinux tags compatible to the current platform.
 
-    :param arch: Should 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.
+    :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 minor in range(sys_musl.minor, -1, -1):
-        yield f"musllinux_{sys_musl.major}_{minor}_{arch}"
+    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
diff --git a/setuptools/_vendor/packaging/_parser.py b/setuptools/_vendor/packaging/_parser.py
index 5a18b758fe..f6c1f5cd22 100644
--- a/setuptools/_vendor/packaging/_parser.py
+++ b/setuptools/_vendor/packaging/_parser.py
@@ -1,16 +1,20 @@
 """Handwritten parser of dependency specifiers.
 
-The docstring for each __parse_* function contains ENBF-inspired grammar representing
+The docstring for each __parse_* function contains EBNF-inspired grammar representing
 the implementation.
 """
 
+from __future__ import annotations
+
 import ast
-from typing import Any, List, NamedTuple, Optional, Tuple, Union
+from typing import List, Literal, NamedTuple, Sequence, Tuple, Union
 
 from ._tokenizer import DEFAULT_RULES, Tokenizer
 
 
 class Node:
+    __slots__ = ("value",)
+
     def __init__(self, value: str) -> None:
         self.value = value
 
@@ -18,43 +22,46 @@ def __str__(self) -> str:
         return self.value
 
     def __repr__(self) -> str:
-        return f"<{self.__class__.__name__}('{self}')>"
+        return f"<{self.__class__.__name__}({self.value!r})>"
 
     def serialize(self) -> str:
         raise NotImplementedError
 
 
 class Variable(Node):
+    __slots__ = ()
+
     def serialize(self) -> str:
         return str(self)
 
 
 class Value(Node):
+    __slots__ = ()
+
     def serialize(self) -> str:
         return f'"{self}"'
 
 
 class Op(Node):
+    __slots__ = ()
+
     def serialize(self) -> str:
         return str(self)
 
 
+MarkerLogical = Literal["and", "or"]
 MarkerVar = Union[Variable, Value]
 MarkerItem = Tuple[MarkerVar, Op, MarkerVar]
-# MarkerAtom = Union[MarkerItem, List["MarkerAtom"]]
-# MarkerList = List[Union["MarkerList", MarkerAtom, str]]
-# mypy does not support recursive type definition
-# https://github.com/python/mypy/issues/731
-MarkerAtom = Any
-MarkerList = List[Any]
+MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]]
+MarkerList = List[Union["MarkerList", MarkerAtom, MarkerLogical]]
 
 
 class ParsedRequirement(NamedTuple):
     name: str
     url: str
-    extras: List[str]
+    extras: list[str]
     specifier: str
-    marker: Optional[MarkerList]
+    marker: MarkerList | None
 
 
 # --------------------------------------------------------------------------------------
@@ -87,7 +94,7 @@ def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement:
 
 def _parse_requirement_details(
     tokenizer: Tokenizer,
-) -> Tuple[str, str, Optional[MarkerList]]:
+) -> tuple[str, str, MarkerList | None]:
     """
     requirement_details = AT URL (WS requirement_marker?)?
                         | specifier WS? (requirement_marker)?
@@ -113,7 +120,9 @@ def _parse_requirement_details(
             return (url, specifier, marker)
 
         marker = _parse_requirement_marker(
-            tokenizer, span_start=url_start, after="URL and whitespace"
+            tokenizer,
+            span_start=url_start,
+            expected="semicolon (after URL and whitespace)",
         )
     else:
         specifier_start = tokenizer.position
@@ -126,10 +135,10 @@ def _parse_requirement_details(
         marker = _parse_requirement_marker(
             tokenizer,
             span_start=specifier_start,
-            after=(
-                "version specifier"
+            expected=(
+                "comma (within version specifier), semicolon (after version specifier)"
                 if specifier
-                else "name and no valid version specifier"
+                else "semicolon (after name with no version specifier)"
             ),
         )
 
@@ -137,7 +146,7 @@ def _parse_requirement_details(
 
 
 def _parse_requirement_marker(
-    tokenizer: Tokenizer, *, span_start: int, after: str
+    tokenizer: Tokenizer, *, span_start: int, expected: str
 ) -> MarkerList:
     """
     requirement_marker = SEMICOLON marker WS?
@@ -145,8 +154,9 @@ def _parse_requirement_marker(
 
     if not tokenizer.check("SEMICOLON"):
         tokenizer.raise_syntax_error(
-            f"Expected end or semicolon (after {after})",
+            f"Expected {expected} or end",
             span_start=span_start,
+            span_end=None,
         )
     tokenizer.read()
 
@@ -156,7 +166,7 @@ def _parse_requirement_marker(
     return marker
 
 
-def _parse_extras(tokenizer: Tokenizer) -> List[str]:
+def _parse_extras(tokenizer: Tokenizer) -> list[str]:
     """
     extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)?
     """
@@ -175,11 +185,11 @@ def _parse_extras(tokenizer: Tokenizer) -> List[str]:
     return extras
 
 
-def _parse_extras_list(tokenizer: Tokenizer) -> List[str]:
+def _parse_extras_list(tokenizer: Tokenizer) -> list[str]:
     """
     extras_list = identifier (wsp* ',' wsp* identifier)*
     """
-    extras: List[str] = []
+    extras: list[str] = []
 
     if not tokenizer.check("IDENTIFIER"):
         return extras
@@ -252,7 +262,13 @@ def _parse_version_many(tokenizer: Tokenizer) -> str:
 # Recursive descent parser for marker expression
 # --------------------------------------------------------------------------------------
 def parse_marker(source: str) -> MarkerList:
-    return _parse_marker(Tokenizer(source, rules=DEFAULT_RULES))
+    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:
@@ -303,7 +319,7 @@ def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem:
     return (marker_var_left, marker_op, marker_var_right)
 
 
-def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar:
+def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar:  # noqa: RET503
     """
     marker_var = VARIABLE | QUOTED_STRING
     """
@@ -318,10 +334,7 @@ def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar:
 
 
 def process_env_var(env_var: str) -> Variable:
-    if (
-        env_var == "platform_python_implementation"
-        or env_var == "python_implementation"
-    ):
+    if env_var in ("platform_python_implementation", "python_implementation"):
         return Variable("platform_python_implementation")
     else:
         return Variable(env_var)
@@ -348,6 +361,5 @@ def _parse_marker_op(tokenizer: Tokenizer) -> Op:
         return Op(tokenizer.read().text)
     else:
         return tokenizer.raise_syntax_error(
-            "Expected marker operator, one of "
-            "<=, <, !=, ==, >=, >, ~=, ===, in, not in"
+            "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in"
         )
diff --git a/setuptools/_vendor/packaging/_structures.py b/setuptools/_vendor/packaging/_structures.py
index 90a6465f96..225e2eee01 100644
--- a/setuptools/_vendor/packaging/_structures.py
+++ b/setuptools/_vendor/packaging/_structures.py
@@ -2,8 +2,13 @@
 # 2.0, and the BSD License. See the LICENSE file in the root of this repository
 # for complete details.
 
+import typing
 
+
+@typing.final
 class InfinityType:
+    __slots__ = ()
+
     def __repr__(self) -> str:
         return "Infinity"
 
@@ -32,7 +37,10 @@ def __neg__(self: object) -> "NegativeInfinityType":
 Infinity = InfinityType()
 
 
+@typing.final
 class NegativeInfinityType:
+    __slots__ = ()
+
     def __repr__(self) -> str:
         return "-Infinity"
 
diff --git a/setuptools/_vendor/packaging/_tokenizer.py b/setuptools/_vendor/packaging/_tokenizer.py
index dd0d648d49..e6d20dd3f5 100644
--- a/setuptools/_vendor/packaging/_tokenizer.py
+++ b/setuptools/_vendor/packaging/_tokenizer.py
@@ -1,7 +1,9 @@
+from __future__ import annotations
+
 import contextlib
 import re
 from dataclasses import dataclass
-from typing import Dict, Iterator, NoReturn, Optional, Tuple, Union
+from typing import Generator, Mapping, NoReturn
 
 from .specifiers import Specifier
 
@@ -21,7 +23,7 @@ def __init__(
         message: str,
         *,
         source: str,
-        span: Tuple[int, int],
+        span: tuple[int, int],
     ) -> None:
         self.span = span
         self.message = message
@@ -31,16 +33,16 @@ def __init__(
 
     def __str__(self) -> str:
         marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^"
-        return "\n    ".join([self.message, self.source, marker])
+        return f"{self.message}\n    {self.source}\n    {marker}"
 
 
-DEFAULT_RULES: "Dict[str, Union[str, re.Pattern[str]]]" = {
-    "LEFT_PARENTHESIS": r"\(",
-    "RIGHT_PARENTHESIS": r"\)",
-    "LEFT_BRACKET": r"\[",
-    "RIGHT_BRACKET": r"\]",
-    "SEMICOLON": r";",
-    "COMMA": r",",
+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"""
             (
@@ -51,10 +53,10 @@ def __str__(self) -> str:
         """,
         re.VERBOSE,
     ),
-    "OP": r"(===|==|~=|!=|<=|>=|<|>)",
-    "BOOLOP": r"\b(or|and)\b",
-    "IN": r"\bin\b",
-    "NOT": r"\bnot\b",
+    "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(
@@ -66,7 +68,8 @@ def __str__(self) -> str:
                 |platform[._](version|machine|python_implementation)
                 |python_implementation
                 |implementation_(name|version)
-                |extra
+                |extras?
+                |dependency_groups
             )\b
         """,
         re.VERBOSE,
@@ -75,13 +78,13 @@ def __str__(self) -> str:
         Specifier._operator_regex_str + Specifier._version_regex_str,
         re.VERBOSE | re.IGNORECASE,
     ),
-    "AT": r"\@",
-    "URL": r"[^ \t]+",
-    "IDENTIFIER": r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b",
-    "VERSION_PREFIX_TRAIL": r"\.\*",
-    "VERSION_LOCAL_LABEL_TRAIL": r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*",
-    "WS": r"[ \t]+",
-    "END": r"$",
+    "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"$"),
 }
 
 
@@ -96,13 +99,11 @@ def __init__(
         self,
         source: str,
         *,
-        rules: "Dict[str, Union[str, re.Pattern[str]]]",
+        rules: Mapping[str, re.Pattern[str]],
     ) -> None:
         self.source = source
-        self.rules: Dict[str, re.Pattern[str]] = {
-            name: re.compile(pattern) for name, pattern in rules.items()
-        }
-        self.next_token: Optional[Token] = None
+        self.rules = rules
+        self.next_token: Token | None = None
         self.position = 0
 
     def consume(self, name: str) -> None:
@@ -117,9 +118,9 @@ def check(self, name: str, *, peek: bool = False) -> bool:
         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 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]
@@ -154,8 +155,8 @@ def raise_syntax_error(
         self,
         message: str,
         *,
-        span_start: Optional[int] = None,
-        span_end: Optional[int] = None,
+        span_start: int | None = None,
+        span_end: int | None = None,
     ) -> NoReturn:
         """Raise ParserSyntaxError at the given position."""
         span = (
@@ -171,7 +172,7 @@ def raise_syntax_error(
     @contextlib.contextmanager
     def enclosing_tokens(
         self, open_token: str, close_token: str, *, around: str
-    ) -> Iterator[None]:
+    ) -> Generator[None, None, None]:
         if self.check(open_token):
             open_position = self.position
             self.read()
diff --git a/setuptools/_vendor/packaging/licenses/__init__.py b/setuptools/_vendor/packaging/licenses/__init__.py
new file mode 100644
index 0000000000..335b275fa7
--- /dev/null
+++ b/setuptools/_vendor/packaging/licenses/__init__.py
@@ -0,0 +1,147 @@
+#######################################################################################
+#
+# Adapted from:
+#  https://github.com/pypa/hatch/blob/5352e44/backend/src/hatchling/licenses/parse.py
+#
+# MIT License
+#
+# Copyright (c) 2017-present Ofek Lev 
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy of this
+# software and associated documentation files (the "Software"), to deal in the Software
+# without restriction, including without limitation the rights to use, copy, modify,
+# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to the following
+# conditions:
+#
+# The above copyright notice and this permission notice shall be included in all copies
+# or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+#
+# With additional allowance of arbitrary `LicenseRef-` identifiers, not just
+# `LicenseRef-Public-Domain` and `LicenseRef-Proprietary`.
+#
+#######################################################################################
+from __future__ import annotations
+
+import re
+from typing import NewType, cast
+
+from ._spdx import EXCEPTIONS, LICENSES
+
+__all__ = [
+    "InvalidLicenseExpression",
+    "NormalizedLicenseExpression",
+    "canonicalize_license_expression",
+]
+
+license_ref_allowed = re.compile("^[A-Za-z0-9.-]*$")
+
+NormalizedLicenseExpression = NewType("NormalizedLicenseExpression", str)
+
+
+class InvalidLicenseExpression(ValueError):
+    """Raised when a license-expression string is invalid
+
+    >>> canonicalize_license_expression("invalid")
+    Traceback (most recent call last):
+        ...
+    packaging.licenses.InvalidLicenseExpression: Invalid license expression: 'invalid'
+    """
+
+
+def canonicalize_license_expression(
+    raw_license_expression: str,
+) -> NormalizedLicenseExpression:
+    if not raw_license_expression:
+        message = f"Invalid license expression: {raw_license_expression!r}"
+        raise InvalidLicenseExpression(message)
+
+    # Pad any parentheses so tokenization can be achieved by merely splitting on
+    # whitespace.
+    license_expression = raw_license_expression.replace("(", " ( ").replace(")", " ) ")
+    licenseref_prefix = "LicenseRef-"
+    license_refs = {
+        ref.lower(): "LicenseRef-" + ref[len(licenseref_prefix) :]
+        for ref in license_expression.split()
+        if ref.lower().startswith(licenseref_prefix.lower())
+    }
+
+    # Normalize to lower case so we can look up licenses/exceptions
+    # and so boolean operators are Python-compatible.
+    license_expression = license_expression.lower()
+
+    tokens = license_expression.split()
+
+    # Rather than implementing a parenthesis/boolean logic parser, create an
+    # expression that Python can parse. Everything that is not involved with the
+    # grammar itself is replaced with the placeholder `False` and the resultant
+    # expression should become a valid Python expression.
+    python_tokens = []
+    for token in tokens:
+        if token not in {"or", "and", "with", "(", ")"}:
+            python_tokens.append("False")
+        elif token == "with":
+            python_tokens.append("or")
+        elif (
+            token == "("
+            and python_tokens
+            and python_tokens[-1] not in {"or", "and", "("}
+        ) or (token == ")" and python_tokens and python_tokens[-1] == "("):
+            message = f"Invalid license expression: {raw_license_expression!r}"
+            raise InvalidLicenseExpression(message)
+        else:
+            python_tokens.append(token)
+
+    python_expression = " ".join(python_tokens)
+    try:
+        compile(python_expression, "", "eval")
+    except SyntaxError:
+        message = f"Invalid license expression: {raw_license_expression!r}"
+        raise InvalidLicenseExpression(message) from None
+
+    # Take a final pass to check for unknown licenses/exceptions.
+    normalized_tokens = []
+    for token in tokens:
+        if token in {"or", "and", "with", "(", ")"}:
+            normalized_tokens.append(token.upper())
+            continue
+
+        if normalized_tokens and normalized_tokens[-1] == "WITH":
+            if token not in EXCEPTIONS:
+                message = f"Unknown license exception: {token!r}"
+                raise InvalidLicenseExpression(message)
+
+            normalized_tokens.append(EXCEPTIONS[token]["id"])
+        else:
+            if token.endswith("+"):
+                final_token = token[:-1]
+                suffix = "+"
+            else:
+                final_token = token
+                suffix = ""
+
+            if final_token.startswith("licenseref-"):
+                if not license_ref_allowed.match(final_token):
+                    message = f"Invalid licenseref: {final_token!r}"
+                    raise InvalidLicenseExpression(message)
+                normalized_tokens.append(license_refs[final_token] + suffix)
+            else:
+                if final_token not in LICENSES:
+                    message = f"Unknown license: {final_token!r}"
+                    raise InvalidLicenseExpression(message)
+                normalized_tokens.append(LICENSES[final_token]["id"] + suffix)
+
+    normalized_expression = " ".join(normalized_tokens)
+
+    return cast(
+        "NormalizedLicenseExpression",
+        normalized_expression.replace("( ", "(").replace(" )", ")"),
+    )
diff --git a/setuptools/_vendor/packaging/licenses/_spdx.py b/setuptools/_vendor/packaging/licenses/_spdx.py
new file mode 100644
index 0000000000..a277af2822
--- /dev/null
+++ b/setuptools/_vendor/packaging/licenses/_spdx.py
@@ -0,0 +1,799 @@
+
+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},
+}
diff --git a/setuptools/_vendor/packaging/markers.py b/setuptools/_vendor/packaging/markers.py
index 8b98fca723..ca3706fe49 100644
--- a/setuptools/_vendor/packaging/markers.py
+++ b/setuptools/_vendor/packaging/markers.py
@@ -2,33 +2,39 @@
 # 2.0, and the BSD License. See the LICENSE file in the root of this repository
 # for complete details.
 
+from __future__ import annotations
+
 import operator
 import os
 import platform
 import sys
-from typing import Any, Callable, Dict, List, Optional, Tuple, Union
-
-from ._parser import (
-    MarkerAtom,
-    MarkerList,
-    Op,
-    Value,
-    Variable,
-    parse_marker as _parse_marker,
-)
+from typing import AbstractSet, Callable, Literal, Mapping, TypedDict, Union, cast
+
+from ._parser import MarkerAtom, MarkerList, Op, Value, Variable
+from ._parser import parse_marker as _parse_marker
 from ._tokenizer import ParserSyntaxError
 from .specifiers import InvalidSpecifier, Specifier
 from .utils import canonicalize_name
 
 __all__ = [
+    "Environment",
+    "EvaluateContext",
     "InvalidMarker",
+    "Marker",
     "UndefinedComparison",
     "UndefinedEnvironmentName",
-    "Marker",
     "default_environment",
 ]
 
-Operator = Callable[[str, str], bool]
+Operator = Callable[[str, Union[str, AbstractSet[str]]], bool]
+EvaluateContext = Literal["metadata", "lock_file", "requirement"]
+MARKERS_ALLOWING_SET = {"extras", "dependency_groups"}
+MARKERS_REQUIRING_VERSION = {
+    "implementation_version",
+    "platform_release",
+    "python_full_version",
+    "python_version",
+}
 
 
 class InvalidMarker(ValueError):
@@ -50,26 +56,105 @@ class UndefinedEnvironmentName(ValueError):
     """
 
 
-def _normalize_extra_values(results: Any) -> Any:
+class Environment(TypedDict):
+    implementation_name: str
+    """The implementation's identifier, e.g. ``'cpython'``."""
+
+    implementation_version: str
+    """
+    The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or
+    ``'7.3.13'`` for PyPy3.10 v7.3.13.
+    """
+
+    os_name: str
+    """
+    The value of :py:data:`os.name`. The name of the operating system dependent module
+    imported, e.g. ``'posix'``.
+    """
+
+    platform_machine: str
+    """
+    Returns the machine type, e.g. ``'i386'``.
+
+    An empty string if the value cannot be determined.
+    """
+
+    platform_release: str
+    """
+    The system's release, e.g. ``'2.2.0'`` or ``'NT'``.
+
+    An empty string if the value cannot be determined.
+    """
+
+    platform_system: str
+    """
+    The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``.
+
+    An empty string if the value cannot be determined.
+    """
+
+    platform_version: str
+    """
+    The system's release version, e.g. ``'#3 on degas'``.
+
+    An empty string if the value cannot be determined.
+    """
+
+    python_full_version: str
+    """
+    The Python version as string ``'major.minor.patchlevel'``.
+
+    Note that unlike the Python :py:data:`sys.version`, this value will always include
+    the patchlevel (it defaults to 0).
+    """
+
+    platform_python_implementation: str
+    """
+    A string identifying the Python implementation, e.g. ``'CPython'``.
+    """
+
+    python_version: str
+    """The Python version as string ``'major.minor'``."""
+
+    sys_platform: str
+    """
+    This string contains a platform identifier that can be used to append
+    platform-specific components to :py:data:`sys.path`, for instance.
+
+    For Unix systems, except on Linux and AIX, this is the lowercased OS name as
+    returned by ``uname -s`` with the first part of the version as returned by
+    ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python
+    was built.
+    """
+
+
+def _normalize_extras(
+    result: MarkerList | MarkerAtom | str,
+) -> MarkerList | MarkerAtom | str:
+    if not isinstance(result, tuple):
+        return result
+
+    lhs, op, rhs = result
+    if isinstance(lhs, Variable) and lhs.value == "extra":
+        normalized_extra = canonicalize_name(rhs.value)
+        rhs = Value(normalized_extra)
+    elif isinstance(rhs, Variable) and rhs.value == "extra":
+        normalized_extra = canonicalize_name(lhs.value)
+        lhs = Value(normalized_extra)
+    return lhs, op, rhs
+
+
+def _normalize_extra_values(results: MarkerList) -> MarkerList:
     """
     Normalize extra values.
     """
-    if isinstance(results[0], tuple):
-        lhs, op, rhs = results[0]
-        if isinstance(lhs, Variable) and lhs.value == "extra":
-            normalized_extra = canonicalize_name(rhs.value)
-            rhs = Value(normalized_extra)
-        elif isinstance(rhs, Variable) and rhs.value == "extra":
-            normalized_extra = canonicalize_name(lhs.value)
-            lhs = Value(normalized_extra)
-        results[0] = lhs, op, rhs
-    return results
+
+    return [_normalize_extras(r) for r in results]
 
 
 def _format_marker(
-    marker: Union[List[str], MarkerAtom, str], first: Optional[bool] = True
+    marker: list[str] | MarkerAtom | str, first: bool | None = True
 ) -> str:
-
     assert isinstance(marker, (list, tuple, str))
 
     # Sometimes we have a structure like [[...]] which is a single item list
@@ -95,51 +180,62 @@ def _format_marker(
         return marker
 
 
-_operators: Dict[str, Operator] = {
+_operators: dict[str, Operator] = {
     "in": lambda lhs, rhs: lhs in rhs,
     "not in": lambda lhs, rhs: lhs not in rhs,
-    "<": operator.lt,
-    "<=": operator.le,
+    "<": lambda _lhs, _rhs: False,
+    "<=": operator.eq,
     "==": operator.eq,
     "!=": operator.ne,
-    ">=": operator.ge,
-    ">": operator.gt,
+    ">=": operator.eq,
+    ">": lambda _lhs, _rhs: False,
 }
 
 
-def _eval_op(lhs: str, op: Op, rhs: str) -> bool:
-    try:
-        spec = Specifier("".join([op.serialize(), rhs]))
-    except InvalidSpecifier:
-        pass
-    else:
-        return spec.contains(lhs, prereleases=True)
+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: Optional[Operator] = _operators.get(op.serialize())
+    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(*values: str, key: str) -> Tuple[str, ...]:
-    # PEP 685 – Comparison of extra names for optional distribution dependencies
+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":
-        return tuple(canonicalize_name(v) for v in values)
+        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 values
+    return lhs, rhs
 
 
-def _evaluate_markers(markers: MarkerList, environment: Dict[str, str]) -> bool:
-    groups: List[List[bool]] = [[]]
+def _evaluate_markers(
+    markers: MarkerList, environment: dict[str, str | AbstractSet[str]]
+) -> bool:
+    groups: list[list[bool]] = [[]]
 
     for marker in markers:
-        assert isinstance(marker, (list, tuple, str))
-
         if isinstance(marker, list):
             groups[-1].append(_evaluate_markers(marker, environment))
         elif isinstance(marker, tuple):
@@ -154,25 +250,28 @@ def _evaluate_markers(markers: MarkerList, environment: Dict[str, str]) -> bool:
                 environment_key = rhs.value
                 rhs_value = environment[environment_key]
 
+            assert isinstance(lhs_value, str), "lhs must be a string"
             lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key)
-            groups[-1].append(_eval_op(lhs_value, op, rhs_value))
-        else:
-            assert marker in ["and", "or"]
-            if marker == "or":
-                groups.append([])
+            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 = "{0.major}.{0.minor}.{0.micro}".format(info)
+def format_full_version(info: sys._version_info) -> str:
+    version = f"{info.major}.{info.minor}.{info.micro}"
     kind = info.releaselevel
     if kind != "final":
         version += kind[0] + str(info.serial)
     return version
 
 
-def default_environment() -> Dict[str, str]:
+def default_environment() -> Environment:
     iver = format_full_version(sys.implementation.version)
     implementation_name = sys.implementation.name
     return {
@@ -195,6 +294,11 @@ 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:
@@ -220,33 +324,65 @@ def __str__(self) -> str:
         return _format_marker(self._markers)
 
     def __repr__(self) -> str:
-        return f""
+        return f"<{self.__class__.__name__}('{self}')>"
 
     def __hash__(self) -> int:
-        return hash((self.__class__.__name__, str(self)))
+        return hash(str(self))
 
-    def __eq__(self, other: Any) -> bool:
+    def __eq__(self, other: object) -> bool:
         if not isinstance(other, Marker):
             return NotImplemented
 
         return str(self) == str(other)
 
-    def evaluate(self, environment: Optional[Dict[str, str]] = None) -> bool:
+    def evaluate(
+        self,
+        environment: Mapping[str, str | AbstractSet[str]] | None = None,
+        context: EvaluateContext = "metadata",
+    ) -> bool:
         """Evaluate a marker.
 
         Return the boolean from evaluating the given marker against the
         environment. environment is an optional argument to override all or
-        part of the determined environment.
+        part of the determined environment. The *context* parameter specifies what
+        context the markers are being evaluated for, which influences what markers
+        are considered valid. Acceptable values are "metadata" (for core metadata;
+        default), "lock_file", and "requirement" (i.e. all other situations).
 
         The environment is determined from the current Python process.
         """
-        current_environment = default_environment()
-        current_environment["extra"] = ""
+        current_environment = cast(
+            "dict[str, str | AbstractSet[str]]", default_environment()
+        )
+        if context == "lock_file":
+            current_environment.update(
+                extras=frozenset(), dependency_groups=frozenset()
+            )
+        elif context == "metadata":
+            current_environment["extra"] = ""
+
         if environment is not None:
             current_environment.update(environment)
-            # The API used to allow setting extra to None. We need to handle this
-            # case for backwards compatibility.
-            if current_environment["extra"] is None:
-                current_environment["extra"] = ""
+            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)
+        )
 
-        return _evaluate_markers(self._markers, current_environment)
+
+def _repair_python_full_version(
+    env: dict[str, str | AbstractSet[str]],
+) -> dict[str, str | AbstractSet[str]]:
+    """
+    Work around platform.python_version() returning something that is not PEP 440
+    compliant for non-tagged Python builds.
+    """
+    python_full_version = cast("str", env["python_full_version"])
+    if python_full_version.endswith("+"):
+        env["python_full_version"] = f"{python_full_version}local"
+    return env
diff --git a/setuptools/_vendor/packaging/metadata.py b/setuptools/_vendor/packaging/metadata.py
index e76a60c395..253f6b1b7e 100644
--- a/setuptools/_vendor/packaging/metadata.py
+++ b/setuptools/_vendor/packaging/metadata.py
@@ -1,25 +1,63 @@
+from __future__ import annotations
+
 import email.feedparser
 import email.header
 import email.message
 import email.parser
 import email.policy
+import keyword
+import pathlib
 import sys
 import typing
-from typing import Dict, List, Optional, Tuple, Union, cast
+from typing import (
+    Any,
+    Callable,
+    Generic,
+    Literal,
+    TypedDict,
+    cast,
+)
+
+from . import licenses, requirements, specifiers, utils
+from . import version as version_module
+
+if typing.TYPE_CHECKING:
+    from .licenses import NormalizedLicenseExpression
 
-if sys.version_info >= (3, 8):  # pragma: no cover
-    from typing import TypedDict
+T = typing.TypeVar("T")
+
+
+if sys.version_info >= (3, 11):  # pragma: no cover
+    ExceptionGroup = ExceptionGroup  # noqa: F821
 else:  # pragma: no cover
-    if typing.TYPE_CHECKING:
-        from typing_extensions import TypedDict
-    else:
-        try:
-            from typing_extensions import TypedDict
-        except ImportError:
 
-            class TypedDict:
-                def __init_subclass__(*_args, **_kwargs):
-                    pass
+    class ExceptionGroup(Exception):
+        """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11.
+
+        If :external:exc:`ExceptionGroup` is already defined by Python itself,
+        that version is used instead.
+        """
+
+        message: str
+        exceptions: list[Exception]
+
+        def __init__(self, message: str, exceptions: list[Exception]) -> None:
+            self.message = message
+            self.exceptions = exceptions
+
+        def __repr__(self) -> str:
+            return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})"
+
+
+class InvalidMetadata(ValueError):
+    """A metadata field contains invalid data."""
+
+    field: str
+    """The name of the field that contains invalid data."""
+
+    def __init__(self, field: str, message: str) -> None:
+        self.field = field
+        super().__init__(message)
 
 
 # The RawMetadata class attempts to make as few assumptions about the underlying
@@ -33,7 +71,8 @@ class RawMetadata(TypedDict, total=False):
     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.
+    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
@@ -45,54 +84,64 @@ class RawMetadata(TypedDict, total=False):
     metadata_version: str
     name: str
     version: str
-    platforms: List[str]
+    platforms: list[str]
     summary: str
     description: str
-    keywords: List[str]
+    keywords: list[str]
     home_page: str
     author: str
     author_email: str
     license: str
 
     # Metadata 1.1 - PEP 314
-    supported_platforms: List[str]
+    supported_platforms: list[str]
     download_url: str
-    classifiers: List[str]
-    requires: List[str]
-    provides: List[str]
-    obsoletes: List[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_dist: list[str]
+    provides_dist: list[str]
+    obsoletes_dist: list[str]
     requires_python: str
-    requires_external: List[str]
-    project_urls: Dict[str, 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 emiting METADATA with
+    # 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]
+    provides_extra: list[str]
 
     # Metadata 2.2 - PEP 643
-    dynamic: List[str]
+    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 interoptability.
+    # tightened up to provide better interoperability.
+
+    # Metadata 2.4 - PEP 639
+    license_expression: str
+    license_files: list[str]
+
+    # Metadata 2.5 - PEP 794
+    import_names: list[str]
+    import_namespaces: list[str]
 
 
+# 'keywords' is special as it's a string in the core metadata spec, but we
+# represent it as a list.
 _STRING_FIELDS = {
     "author",
     "author_email",
@@ -101,6 +150,7 @@ class RawMetadata(TypedDict, total=False):
     "download_url",
     "home_page",
     "license",
+    "license_expression",
     "maintainer",
     "maintainer_email",
     "metadata_version",
@@ -110,9 +160,10 @@ class RawMetadata(TypedDict, total=False):
     "version",
 }
 
-_LIST_STRING_FIELDS = {
+_LIST_FIELDS = {
     "classifiers",
     "dynamic",
+    "license_files",
     "obsoletes",
     "obsoletes_dist",
     "platforms",
@@ -123,15 +174,21 @@ class RawMetadata(TypedDict, total=False):
     "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-separate keyboards into a list of keywords."""
+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]:
+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:
@@ -147,45 +204,46 @@ def _parse_project_urls(data: List[str]) -> Dict[str, str]:
         # be the missing value, then they'd have multiple '' values that
         # overwrite each other in a accumulating dict.
         #
-        # The other potentional issue is that it's possible to have the
+        # 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 unparseable and add it
+        # thing we can, which is treat the field as unparsable and add it
         # to our list of unparsed fields.
-        parts = [p.strip() for p in pair.split(",", 1)]
-        parts.extend([""] * (max(0, 2 - len(parts))))  # Ensure 2 items
-
+        #
         # 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 = parts
+        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 unparseable, and we can just add the whole thing to our
-            # unparseable data and stop processing it.
+            # 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: Union[bytes, str]) -> str:
+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: str = msg.get_payload()
+        payload = msg.get_payload()
+        assert isinstance(payload, str)
         return payload
     # If our source is a bytes, then we're managing the encoding and we need
     # to deal with it.
     else:
-        bpayload: bytes = msg.get_payload(decode=True)
+        bpayload = msg.get_payload(decode=True)
+        assert isinstance(bpayload, bytes)
         try:
             return bpayload.decode("utf8", "strict")
-        except UnicodeDecodeError:
-            raise ValueError("payload in an invalid encoding")
+        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
@@ -209,8 +267,12 @@ def _get_payload(msg: email.message.Message, source: Union[bytes, str]) -> str:
     "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",
@@ -230,10 +292,50 @@ def _get_payload(msg: email.message.Message, source: Union[bytes, str]) -> str:
     "supported-platform": "supported_platforms",
     "version": "version",
 }
+_RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()}
 
 
-def parse_email(data: Union[bytes, str]) -> Tuple[RawMetadata, Dict[str, List[str]]]:
-    """Parse a distribution's metadata.
+# This class is for writing RFC822 messages
+class RFC822Policy(email.policy.EmailPolicy):
+    """
+    This is :class:`email.policy.EmailPolicy`, but with a simple ``header_store_parse``
+    implementation that handles multi-line values, and some nice defaults.
+    """
+
+    utf8 = True
+    mangle_from_ = False
+    max_line_length = 0
+
+    def header_store_parse(self, name: str, value: str) -> tuple[str, str]:
+        size = len(name) + 2
+        value = value.replace("\n", "\n" + " " * size)
+        return (name, value)
+
+
+# This class is for writing RFC822 messages
+class RFC822Message(email.message.EmailMessage):
+    """
+    This is :class:`email.message.EmailMessage` with two small changes: it defaults to
+    our `RFC822Policy`, and it correctly writes unicode when being called
+    with `bytes()`.
+    """
+
+    def __init__(self) -> None:
+        super().__init__(policy=RFC822Policy())
+
+    def as_bytes(
+        self, unixfrom: bool = False, policy: email.policy.Policy | None = None
+    ) -> bytes:
+        """
+        Return the bytes representation of the message.
+
+        This handles unicode encoding.
+        """
+        return self.as_string(unixfrom, policy=policy).encode("utf-8")
+
+
+def parse_email(data: bytes | str) -> tuple[RawMetadata, dict[str, list[str]]]:
+    """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``).
 
     This function returns a two-item tuple of dicts. The first dict is of
     recognized fields from the core metadata specification. Fields that can be
@@ -248,8 +350,8 @@ def parse_email(data: Union[bytes, str]) -> Tuple[RawMetadata, Dict[str, List[st
     included in this dict.
 
     """
-    raw: Dict[str, Union[str, List[str], Dict[str, str]]] = {}
-    unparsed: Dict[str, List[str]] = {}
+    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)
@@ -259,15 +361,15 @@ def parse_email(data: Union[bytes, str]) -> Tuple[RawMetadata, Dict[str, List[st
     # 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 in frozenset(parsed.keys()):
+    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.lower()
+        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)
+        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
@@ -297,17 +399,17 @@ def parse_email(data: Union[bytes, str]) -> Tuple[RawMetadata, Dict[str, List[st
                 # 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, Optional[str]]] = []
-                for bin, encoding in email.header.decode_header(h):
+                chunks: list[tuple[bytes, str | None]] = []
+                for binary, _encoding in email.header.decode_header(h):
                     try:
-                        bin.decode("utf8", "strict")
+                        binary.decode("utf8", "strict")
                     except UnicodeDecodeError:
                         # Enable mojibake.
                         encoding = "latin1"
                         valid_encoding = False
                     else:
                         encoding = "utf8"
-                    chunks.append((bin, encoding))
+                    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
@@ -346,10 +448,15 @@ def parse_email(data: Union[bytes, str]) -> Tuple[RawMetadata, Dict[str, List[st
         # 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_STRING_FIELDS:
+        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,
@@ -373,7 +480,7 @@ def parse_email(data: Union[bytes, str]) -> Tuple[RawMetadata, Dict[str, List[st
             except KeyError:
                 unparsed[name] = value
         # Nothing that we've done has managed to parse this, so it'll just
-        # throw it in our unparseable data and move on.
+        # throw it in our unparsable data and move on.
         else:
             unparsed[name] = value
 
@@ -385,14 +492,14 @@ def parse_email(data: Union[bytes, str]) -> Tuple[RawMetadata, Dict[str, List[st
         payload = _get_payload(parsed, data)
     except ValueError:
         unparsed.setdefault("description", []).append(
-            parsed.get_payload(decode=isinstance(data, bytes))
+            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 unparseable.
+            # it, and this body move to unparsable.
             if "description" in raw:
-                description_header = cast(str, raw.pop("description"))
+                description_header = cast("str", raw.pop("description"))
                 unparsed.setdefault("description", []).extend(
                     [description_header, payload]
                 )
@@ -405,4 +512,467 @@ def parse_email(data: Union[bytes, str]) -> Tuple[RawMetadata, Dict[str, List[st
     # 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
+    return cast("RawMetadata", raw), unparsed
+
+
+_NOT_FOUND = object()
+
+
+# Keep the two values in sync.
+_VALID_METADATA_VERSIONS = ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"]
+_MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"]
+
+_REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"])
+
+
+class _Validator(Generic[T]):
+    """Validate a metadata field.
+
+    All _process_*() methods correspond to a core metadata field. The method is
+    called with the field's raw value. If the raw value is valid it is returned
+    in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field).
+    If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause
+    as appropriate).
+    """
+
+    name: str
+    raw_name: str
+    added: _MetadataVersion
+
+    def __init__(
+        self,
+        *,
+        added: _MetadataVersion = "1.0",
+    ) -> None:
+        self.added = added
+
+    def __set_name__(self, _owner: Metadata, name: str) -> None:
+        self.name = name
+        self.raw_name = _RAW_TO_EMAIL_MAPPING[name]
+
+    def __get__(self, instance: Metadata, _owner: type[Metadata]) -> T:
+        # With Python 3.8, the caching can be replaced with functools.cached_property().
+        # No need to check the cache as attribute lookup will resolve into the
+        # instance's __dict__ before __get__ is called.
+        cache = instance.__dict__
+        value = instance._raw.get(self.name)
+
+        # To make the _process_* methods easier, we'll check if the value is None
+        # and if this field is NOT a required attribute, and if both of those
+        # things are true, we'll skip the the converter. This will mean that the
+        # converters never have to deal with the None union.
+        if self.name in _REQUIRED_ATTRS or value is not None:
+            try:
+                converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}")
+            except AttributeError:
+                pass
+            else:
+                value = converter(value)
+
+        cache[self.name] = value
+        try:
+            del instance._raw[self.name]  # type: ignore[misc]
+        except KeyError:
+            pass
+
+        return cast("T", value)
+
+    def _invalid_metadata(
+        self, msg: str, cause: Exception | None = None
+    ) -> InvalidMetadata:
+        exc = InvalidMetadata(
+            self.raw_name, msg.format_map({"field": repr(self.raw_name)})
+        )
+        exc.__cause__ = cause
+        return exc
+
+    def _process_metadata_version(self, value: str) -> _MetadataVersion:
+        # Implicitly makes Metadata-Version required.
+        if value not in _VALID_METADATA_VERSIONS:
+            raise self._invalid_metadata(f"{value!r} is not a valid metadata version")
+        return cast("_MetadataVersion", value)
+
+    def _process_name(self, value: str) -> str:
+        if not value:
+            raise self._invalid_metadata("{field} is a required field")
+        # Validate the name as a side-effect.
+        try:
+            utils.canonicalize_name(value, validate=True)
+        except utils.InvalidName as exc:
+            raise self._invalid_metadata(
+                f"{value!r} is invalid for {{field}}", cause=exc
+            ) from exc
+        else:
+            return value
+
+    def _process_version(self, value: str) -> version_module.Version:
+        if not value:
+            raise self._invalid_metadata("{field} is a required field")
+        try:
+            return version_module.parse(value)
+        except version_module.InvalidVersion as exc:
+            raise self._invalid_metadata(
+                f"{value!r} is invalid for {{field}}", cause=exc
+            ) from exc
+
+    def _process_summary(self, value: str) -> str:
+        """Check the field contains no newlines."""
+        if "\n" in value:
+            raise self._invalid_metadata("{field} must be a single line")
+        return value
+
+    def _process_description_content_type(self, value: str) -> str:
+        content_types = {"text/plain", "text/x-rst", "text/markdown"}
+        message = email.message.EmailMessage()
+        message["content-type"] = value
+
+        content_type, parameters = (
+            # Defaults to `text/plain` if parsing failed.
+            message.get_content_type().lower(),
+            message["content-type"].params,
+        )
+        # Check if content-type is valid or defaulted to `text/plain` and thus was
+        # not parseable.
+        if content_type not in content_types or content_type not in value.lower():
+            raise self._invalid_metadata(
+                f"{{field}} must be one of {list(content_types)}, not {value!r}"
+            )
+
+        charset = parameters.get("charset", "UTF-8")
+        if charset != "UTF-8":
+            raise self._invalid_metadata(
+                f"{{field}} can only specify the UTF-8 charset, not {list(charset)}"
+            )
+
+        markdown_variants = {"GFM", "CommonMark"}
+        variant = parameters.get("variant", "GFM")  # Use an acceptable default.
+        if content_type == "text/markdown" and variant not in markdown_variants:
+            raise self._invalid_metadata(
+                f"valid Markdown variants for {{field}} are {list(markdown_variants)}, "
+                f"not {variant!r}",
+            )
+        return value
+
+    def _process_dynamic(self, value: list[str]) -> list[str]:
+        for dynamic_field in map(str.lower, value):
+            if dynamic_field in {"name", "version", "metadata-version"}:
+                raise self._invalid_metadata(
+                    f"{dynamic_field!r} is not allowed as a dynamic field"
+                )
+            elif dynamic_field not in _EMAIL_TO_RAW_MAPPING:
+                raise self._invalid_metadata(
+                    f"{dynamic_field!r} is not a valid dynamic field"
+                )
+        return list(map(str.lower, value))
+
+    def _process_provides_extra(
+        self,
+        value: list[str],
+    ) -> list[utils.NormalizedName]:
+        normalized_names = []
+        try:
+            for name in value:
+                normalized_names.append(utils.canonicalize_name(name, validate=True))
+        except utils.InvalidName as exc:
+            raise self._invalid_metadata(
+                f"{name!r} is invalid for {{field}}", cause=exc
+            ) from exc
+        else:
+            return normalized_names
+
+    def _process_requires_python(self, value: str) -> specifiers.SpecifierSet:
+        try:
+            return specifiers.SpecifierSet(value)
+        except specifiers.InvalidSpecifier as exc:
+            raise self._invalid_metadata(
+                f"{value!r} is invalid for {{field}}", cause=exc
+            ) from exc
+
+    def _process_requires_dist(
+        self,
+        value: list[str],
+    ) -> list[requirements.Requirement]:
+        reqs = []
+        try:
+            for req in value:
+                reqs.append(requirements.Requirement(req))
+        except requirements.InvalidRequirement as exc:
+            raise self._invalid_metadata(
+                f"{req!r} is invalid for {{field}}", cause=exc
+            ) from exc
+        else:
+            return reqs
+
+    def _process_license_expression(self, value: str) -> NormalizedLicenseExpression:
+        try:
+            return licenses.canonicalize_license_expression(value)
+        except ValueError as exc:
+            raise self._invalid_metadata(
+                f"{value!r} is invalid for {{field}}", cause=exc
+            ) from exc
+
+    def _process_license_files(self, value: list[str]) -> list[str]:
+        paths = []
+        for path in value:
+            if ".." in path:
+                raise self._invalid_metadata(
+                    f"{path!r} is invalid for {{field}}, "
+                    "parent directory indicators are not allowed"
+                )
+            if "*" in path:
+                raise self._invalid_metadata(
+                    f"{path!r} is invalid for {{field}}, paths must be resolved"
+                )
+            if (
+                pathlib.PurePosixPath(path).is_absolute()
+                or pathlib.PureWindowsPath(path).is_absolute()
+            ):
+                raise self._invalid_metadata(
+                    f"{path!r} is invalid for {{field}}, paths must be relative"
+                )
+            if pathlib.PureWindowsPath(path).as_posix() != path:
+                raise self._invalid_metadata(
+                    f"{path!r} is invalid for {{field}}, paths must use '/' delimiter"
+                )
+            paths.append(path)
+        return paths
+
+    def _process_import_names(self, value: list[str]) -> list[str]:
+        for import_name in value:
+            name, semicolon, private = import_name.partition(";")
+            name = name.rstrip()
+            for identifier in name.split("."):
+                if not identifier.isidentifier():
+                    raise self._invalid_metadata(
+                        f"{name!r} is invalid for {{field}}; "
+                        f"{identifier!r} is not a valid identifier"
+                    )
+                elif keyword.iskeyword(identifier):
+                    raise self._invalid_metadata(
+                        f"{name!r} is invalid for {{field}}; "
+                        f"{identifier!r} is a keyword"
+                    )
+            if semicolon and private.lstrip() != "private":
+                raise self._invalid_metadata(
+                    f"{import_name!r} is invalid for {{field}}; "
+                    "the only valid option is 'private'"
+                )
+        return value
+
+    _process_import_namespaces = _process_import_names
+
+
+class Metadata:
+    """Representation of distribution metadata.
+
+    Compared to :class:`RawMetadata`, this class provides objects representing
+    metadata fields instead of only using built-in types. Any invalid metadata
+    will cause :exc:`InvalidMetadata` to be raised (with a
+    :py:attr:`~BaseException.__cause__` attribute as appropriate).
+    """
+
+    _raw: RawMetadata
+
+    @classmethod
+    def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> Metadata:
+        """Create an instance from :class:`RawMetadata`.
+
+        If *validate* is true, all metadata will be validated. All exceptions
+        related to validation will be gathered and raised as an :class:`ExceptionGroup`.
+        """
+        ins = cls()
+        ins._raw = data.copy()  # Mutations occur due to caching enriched values.
+
+        if validate:
+            exceptions: list[Exception] = []
+            try:
+                metadata_version = ins.metadata_version
+                metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version)
+            except InvalidMetadata as metadata_version_exc:
+                exceptions.append(metadata_version_exc)
+                metadata_version = None
+
+            # Make sure to check for the fields that are present, the required
+            # fields (so their absence can be reported).
+            fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS
+            # Remove fields that have already been checked.
+            fields_to_check -= {"metadata_version"}
+
+            for key in fields_to_check:
+                try:
+                    if metadata_version:
+                        # Can't use getattr() as that triggers descriptor protocol which
+                        # will fail due to no value for the instance argument.
+                        try:
+                            field_metadata_version = cls.__dict__[key].added
+                        except KeyError:
+                            exc = InvalidMetadata(key, f"unrecognized field: {key!r}")
+                            exceptions.append(exc)
+                            continue
+                        field_age = _VALID_METADATA_VERSIONS.index(
+                            field_metadata_version
+                        )
+                        if field_age > metadata_age:
+                            field = _RAW_TO_EMAIL_MAPPING[key]
+                            exc = InvalidMetadata(
+                                field,
+                                f"{field} introduced in metadata version "
+                                f"{field_metadata_version}, not {metadata_version}",
+                            )
+                            exceptions.append(exc)
+                            continue
+                    getattr(ins, key)
+                except InvalidMetadata as exc:
+                    exceptions.append(exc)
+
+            if exceptions:
+                raise ExceptionGroup("invalid metadata", exceptions)
+
+        return ins
+
+    @classmethod
+    def from_email(cls, data: bytes | str, *, validate: bool = True) -> Metadata:
+        """Parse metadata from email headers.
+
+        If *validate* is true, the metadata will be validated. All exceptions
+        related to validation will be gathered and raised as an :class:`ExceptionGroup`.
+        """
+        raw, unparsed = parse_email(data)
+
+        if validate:
+            exceptions: list[Exception] = []
+            for unparsed_key in unparsed:
+                if unparsed_key in _EMAIL_TO_RAW_MAPPING:
+                    message = f"{unparsed_key!r} has invalid data"
+                else:
+                    message = f"unrecognized field: {unparsed_key!r}"
+                exceptions.append(InvalidMetadata(unparsed_key, message))
+
+            if exceptions:
+                raise ExceptionGroup("unparsed", exceptions)
+
+        try:
+            return cls.from_raw(raw, validate=validate)
+        except ExceptionGroup as exc_group:
+            raise ExceptionGroup(
+                "invalid or unparsed metadata", exc_group.exceptions
+            ) from None
+
+    metadata_version: _Validator[_MetadataVersion] = _Validator()
+    """:external:ref:`core-metadata-metadata-version`
+    (required; validated to be a valid metadata version)"""
+    # `name` is not normalized/typed to NormalizedName so as to provide access to
+    # the original/raw name.
+    name: _Validator[str] = _Validator()
+    """:external:ref:`core-metadata-name`
+    (required; validated using :func:`~packaging.utils.canonicalize_name` and its
+    *validate* parameter)"""
+    version: _Validator[version_module.Version] = _Validator()
+    """:external:ref:`core-metadata-version` (required)"""
+    dynamic: _Validator[list[str] | None] = _Validator(
+        added="2.2",
+    )
+    """:external:ref:`core-metadata-dynamic`
+    (validated against core metadata field names and lowercased)"""
+    platforms: _Validator[list[str] | None] = _Validator()
+    """:external:ref:`core-metadata-platform`"""
+    supported_platforms: _Validator[list[str] | None] = _Validator(added="1.1")
+    """:external:ref:`core-metadata-supported-platform`"""
+    summary: _Validator[str | None] = _Validator()
+    """:external:ref:`core-metadata-summary` (validated to contain no newlines)"""
+    description: _Validator[str | None] = _Validator()  # TODO 2.1: can be in body
+    """:external:ref:`core-metadata-description`"""
+    description_content_type: _Validator[str | None] = _Validator(added="2.1")
+    """:external:ref:`core-metadata-description-content-type` (validated)"""
+    keywords: _Validator[list[str] | None] = _Validator()
+    """:external:ref:`core-metadata-keywords`"""
+    home_page: _Validator[str | None] = _Validator()
+    """:external:ref:`core-metadata-home-page`"""
+    download_url: _Validator[str | None] = _Validator(added="1.1")
+    """:external:ref:`core-metadata-download-url`"""
+    author: _Validator[str | None] = _Validator()
+    """:external:ref:`core-metadata-author`"""
+    author_email: _Validator[str | None] = _Validator()
+    """:external:ref:`core-metadata-author-email`"""
+    maintainer: _Validator[str | None] = _Validator(added="1.2")
+    """:external:ref:`core-metadata-maintainer`"""
+    maintainer_email: _Validator[str | None] = _Validator(added="1.2")
+    """:external:ref:`core-metadata-maintainer-email`"""
+    license: _Validator[str | None] = _Validator()
+    """:external:ref:`core-metadata-license`"""
+    license_expression: _Validator[NormalizedLicenseExpression | None] = _Validator(
+        added="2.4"
+    )
+    """:external:ref:`core-metadata-license-expression`"""
+    license_files: _Validator[list[str] | None] = _Validator(added="2.4")
+    """:external:ref:`core-metadata-license-file`"""
+    classifiers: _Validator[list[str] | None] = _Validator(added="1.1")
+    """:external:ref:`core-metadata-classifier`"""
+    requires_dist: _Validator[list[requirements.Requirement] | None] = _Validator(
+        added="1.2"
+    )
+    """:external:ref:`core-metadata-requires-dist`"""
+    requires_python: _Validator[specifiers.SpecifierSet | None] = _Validator(
+        added="1.2"
+    )
+    """:external:ref:`core-metadata-requires-python`"""
+    # Because `Requires-External` allows for non-PEP 440 version specifiers, we
+    # don't do any processing on the values.
+    requires_external: _Validator[list[str] | None] = _Validator(added="1.2")
+    """:external:ref:`core-metadata-requires-external`"""
+    project_urls: _Validator[dict[str, str] | None] = _Validator(added="1.2")
+    """:external:ref:`core-metadata-project-url`"""
+    # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation
+    # regardless of metadata version.
+    provides_extra: _Validator[list[utils.NormalizedName] | None] = _Validator(
+        added="2.1",
+    )
+    """:external:ref:`core-metadata-provides-extra`"""
+    provides_dist: _Validator[list[str] | None] = _Validator(added="1.2")
+    """:external:ref:`core-metadata-provides-dist`"""
+    obsoletes_dist: _Validator[list[str] | None] = _Validator(added="1.2")
+    """:external:ref:`core-metadata-obsoletes-dist`"""
+    import_names: _Validator[list[str] | None] = _Validator(added="2.5")
+    """:external:ref:`core-metadata-import-name`"""
+    import_namespaces: _Validator[list[str] | None] = _Validator(added="2.5")
+    """:external:ref:`core-metadata-import-namespace`"""
+    requires: _Validator[list[str] | None] = _Validator(added="1.1")
+    """``Requires`` (deprecated)"""
+    provides: _Validator[list[str] | None] = _Validator(added="1.1")
+    """``Provides`` (deprecated)"""
+    obsoletes: _Validator[list[str] | None] = _Validator(added="1.1")
+    """``Obsoletes`` (deprecated)"""
+
+    def as_rfc822(self) -> RFC822Message:
+        """
+        Return an RFC822 message with the metadata.
+        """
+        message = RFC822Message()
+        self._write_metadata(message)
+        return message
+
+    def _write_metadata(self, message: RFC822Message) -> None:
+        """
+        Return an RFC822 message with the metadata.
+        """
+        for name, validator in self.__class__.__dict__.items():
+            if isinstance(validator, _Validator) and name != "description":
+                value = getattr(self, name)
+                email_name = _RAW_TO_EMAIL_MAPPING[name]
+                if value is not None:
+                    if email_name == "project-url":
+                        for label, url in value.items():
+                            message[email_name] = f"{label}, {url}"
+                    elif email_name == "keywords":
+                        message[email_name] = ",".join(value)
+                    elif email_name == "import-name" and value == []:
+                        message[email_name] = ""
+                    elif isinstance(value, list):
+                        for item in value:
+                            message[email_name] = str(item)
+                    else:
+                        message[email_name] = str(value)
+
+        # The description is a special case because it is in the body of the message.
+        if self.description is not None:
+            message.set_payload(self.description)
diff --git a/setuptools/_vendor/packaging/pylock.py b/setuptools/_vendor/packaging/pylock.py
new file mode 100644
index 0000000000..a564f15246
--- /dev/null
+++ b/setuptools/_vendor/packaging/pylock.py
@@ -0,0 +1,635 @@
+from __future__ import annotations
+
+import dataclasses
+import logging
+import re
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from datetime import datetime
+from typing import (
+    TYPE_CHECKING,
+    Any,
+    Callable,
+    Protocol,
+    TypeVar,
+)
+
+from .markers import Marker
+from .specifiers import SpecifierSet
+from .utils import NormalizedName, is_normalized_name
+from .version import Version
+
+if TYPE_CHECKING:  # pragma: no cover
+    from pathlib import Path
+
+    from typing_extensions import Self
+
+_logger = logging.getLogger(__name__)
+
+__all__ = [
+    "Package",
+    "PackageArchive",
+    "PackageDirectory",
+    "PackageSdist",
+    "PackageVcs",
+    "PackageWheel",
+    "Pylock",
+    "PylockUnsupportedVersionError",
+    "PylockValidationError",
+    "is_valid_pylock_path",
+]
+
+_T = TypeVar("_T")
+_T2 = TypeVar("_T2")
+
+
+class _FromMappingProtocol(Protocol):  # pragma: no cover
+    @classmethod
+    def _from_dict(cls, d: Mapping[str, Any]) -> Self: ...
+
+
+_FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol)
+
+
+_PYLOCK_FILE_NAME_RE = re.compile(r"^pylock\.([^.]+)\.toml$")
+
+
+def is_valid_pylock_path(path: Path) -> bool:
+    """Check if the given path is a valid pylock file path."""
+    return path.name == "pylock.toml" or bool(_PYLOCK_FILE_NAME_RE.match(path.name))
+
+
+def _toml_key(key: str) -> str:
+    return key.replace("_", "-")
+
+
+def _toml_value(key: str, value: Any) -> Any:  # noqa: ANN401
+    if isinstance(value, (Version, Marker, SpecifierSet)):
+        return str(value)
+    if isinstance(value, Sequence) and key == "environments":
+        return [str(v) for v in value]
+    return value
+
+
+def _toml_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]:
+    return {
+        _toml_key(key): _toml_value(key, value)
+        for key, value in data
+        if value is not None
+    }
+
+
+def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None:
+    """Get a value from the dictionary and verify it's the expected type."""
+    if (value := d.get(key)) is None:
+        return None
+    if not isinstance(value, expected_type):
+        raise PylockValidationError(
+            f"Unexpected type {type(value).__name__} "
+            f"(expected {expected_type.__name__})",
+            context=key,
+        )
+    return value
+
+
+def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T:
+    """Get a required value from the dictionary and verify it's the expected type."""
+    if (value := _get(d, expected_type, key)) is None:
+        raise _PylockRequiredKeyError(key)
+    return value
+
+
+def _get_sequence(
+    d: Mapping[str, Any], expected_item_type: type[_T], key: str
+) -> Sequence[_T] | None:
+    """Get a list value from the dictionary and verify it's the expected items type."""
+    if (value := _get(d, Sequence, key)) is None:  # type: ignore[type-abstract]
+        return None
+    if isinstance(value, (str, bytes)):
+        # special case: str and bytes are Sequences, but we want to reject it
+        raise PylockValidationError(
+            f"Unexpected type {type(value).__name__} (expected Sequence)",
+            context=key,
+        )
+    for i, item in enumerate(value):
+        if not isinstance(item, expected_item_type):
+            raise PylockValidationError(
+                f"Unexpected type {type(item).__name__} "
+                f"(expected {expected_item_type.__name__})",
+                context=f"{key}[{i}]",
+            )
+    return value
+
+
+def _get_as(
+    d: Mapping[str, Any],
+    expected_type: type[_T],
+    target_type: Callable[[_T], _T2],
+    key: str,
+) -> _T2 | None:
+    """Get a value from the dictionary, verify it's the expected type,
+    and convert to the target type.
+
+    This assumes the target_type constructor accepts the value.
+    """
+    if (value := _get(d, expected_type, key)) is None:
+        return None
+    try:
+        return target_type(value)
+    except Exception as e:
+        raise PylockValidationError(e, context=key) from e
+
+
+def _get_required_as(
+    d: Mapping[str, Any],
+    expected_type: type[_T],
+    target_type: Callable[[_T], _T2],
+    key: str,
+) -> _T2:
+    """Get a required value from the dict, verify it's the expected type,
+    and convert to the target type."""
+    if (value := _get_as(d, expected_type, target_type, key)) is None:
+        raise _PylockRequiredKeyError(key)
+    return value
+
+
+def _get_sequence_as(
+    d: Mapping[str, Any],
+    expected_item_type: type[_T],
+    target_item_type: Callable[[_T], _T2],
+    key: str,
+) -> list[_T2] | None:
+    """Get list value from dictionary and verify expected items type."""
+    if (value := _get_sequence(d, expected_item_type, key)) is None:
+        return None
+    result = []
+    try:
+        for item in value:
+            typed_item = target_item_type(item)
+            result.append(typed_item)
+    except Exception as e:
+        raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e
+    return result
+
+
+def _get_object(
+    d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str
+) -> _FromMappingProtocolT | None:
+    """Get a dictionary value from the dictionary and convert it to a dataclass."""
+    if (value := _get(d, Mapping, key)) is None:  # type: ignore[type-abstract]
+        return None
+    try:
+        return target_type._from_dict(value)
+    except Exception as e:
+        raise PylockValidationError(e, context=key) from e
+
+
+def _get_sequence_of_objects(
+    d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str
+) -> list[_FromMappingProtocolT] | None:
+    """Get a list value from the dictionary and convert its items to a dataclass."""
+    if (value := _get_sequence(d, Mapping, key)) is None:  # type: ignore[type-abstract]
+        return None
+    result: list[_FromMappingProtocolT] = []
+    try:
+        for item in value:
+            typed_item = target_item_type._from_dict(item)
+            result.append(typed_item)
+    except Exception as e:
+        raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e
+    return result
+
+
+def _get_required_sequence_of_objects(
+    d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str
+) -> Sequence[_FromMappingProtocolT]:
+    """Get a required list value from the dictionary and convert its items to a
+    dataclass."""
+    if (result := _get_sequence_of_objects(d, target_item_type, key)) is None:
+        raise _PylockRequiredKeyError(key)
+    return result
+
+
+def _validate_normalized_name(name: str) -> NormalizedName:
+    """Validate that a string is a NormalizedName."""
+    if not is_normalized_name(name):
+        raise PylockValidationError(f"Name {name!r} is not normalized")
+    return NormalizedName(name)
+
+
+def _validate_path_url(path: str | None, url: str | None) -> None:
+    if not path and not url:
+        raise PylockValidationError("path or url must be provided")
+
+
+def _validate_hashes(hashes: Mapping[str, Any]) -> Mapping[str, Any]:
+    if not hashes:
+        raise PylockValidationError("At least one hash must be provided")
+    if not all(isinstance(hash_val, str) for hash_val in hashes.values()):
+        raise PylockValidationError("Hash values must be strings")
+    return hashes
+
+
+class PylockValidationError(Exception):
+    """Raised when when input data is not spec-compliant."""
+
+    context: str | None = None
+    message: str
+
+    def __init__(
+        self,
+        cause: str | Exception,
+        *,
+        context: str | None = None,
+    ) -> None:
+        if isinstance(cause, PylockValidationError):
+            if cause.context:
+                self.context = (
+                    f"{context}.{cause.context}" if context else cause.context
+                )
+            else:
+                self.context = context
+            self.message = cause.message
+        else:
+            self.context = context
+            self.message = str(cause)
+
+    def __str__(self) -> str:
+        if self.context:
+            return f"{self.message} in {self.context!r}"
+        return self.message
+
+
+class _PylockRequiredKeyError(PylockValidationError):
+    def __init__(self, key: str) -> None:
+        super().__init__("Missing required value", context=key)
+
+
+class PylockUnsupportedVersionError(PylockValidationError):
+    """Raised when encountering an unsupported `lock_version`."""
+
+
+@dataclass(frozen=True, init=False)
+class PackageVcs:
+    type: str
+    url: str | None = None
+    path: str | None = None
+    requested_revision: str | None = None
+    commit_id: str  # type: ignore[misc]
+    subdirectory: str | None = None
+
+    def __init__(
+        self,
+        *,
+        type: str,
+        url: str | None = None,
+        path: str | None = None,
+        requested_revision: str | None = None,
+        commit_id: str,
+        subdirectory: str | None = None,
+    ) -> None:
+        # In Python 3.10+ make dataclass kw_only=True and remove __init__
+        object.__setattr__(self, "type", type)
+        object.__setattr__(self, "url", url)
+        object.__setattr__(self, "path", path)
+        object.__setattr__(self, "requested_revision", requested_revision)
+        object.__setattr__(self, "commit_id", commit_id)
+        object.__setattr__(self, "subdirectory", subdirectory)
+
+    @classmethod
+    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
+        package_vcs = cls(
+            type=_get_required(d, str, "type"),
+            url=_get(d, str, "url"),
+            path=_get(d, str, "path"),
+            requested_revision=_get(d, str, "requested-revision"),
+            commit_id=_get_required(d, str, "commit-id"),
+            subdirectory=_get(d, str, "subdirectory"),
+        )
+        _validate_path_url(package_vcs.path, package_vcs.url)
+        return package_vcs
+
+
+@dataclass(frozen=True, init=False)
+class PackageDirectory:
+    path: str
+    editable: bool | None = None
+    subdirectory: str | None = None
+
+    def __init__(
+        self,
+        *,
+        path: str,
+        editable: bool | None = None,
+        subdirectory: str | None = None,
+    ) -> None:
+        # In Python 3.10+ make dataclass kw_only=True and remove __init__
+        object.__setattr__(self, "path", path)
+        object.__setattr__(self, "editable", editable)
+        object.__setattr__(self, "subdirectory", subdirectory)
+
+    @classmethod
+    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
+        return cls(
+            path=_get_required(d, str, "path"),
+            editable=_get(d, bool, "editable"),
+            subdirectory=_get(d, str, "subdirectory"),
+        )
+
+
+@dataclass(frozen=True, init=False)
+class PackageArchive:
+    url: str | None = None
+    path: str | None = None
+    size: int | None = None
+    upload_time: datetime | None = None
+    hashes: Mapping[str, str]  # type: ignore[misc]
+    subdirectory: str | None = None
+
+    def __init__(
+        self,
+        *,
+        url: str | None = None,
+        path: str | None = None,
+        size: int | None = None,
+        upload_time: datetime | None = None,
+        hashes: Mapping[str, str],
+        subdirectory: str | None = None,
+    ) -> None:
+        # In Python 3.10+ make dataclass kw_only=True and remove __init__
+        object.__setattr__(self, "url", url)
+        object.__setattr__(self, "path", path)
+        object.__setattr__(self, "size", size)
+        object.__setattr__(self, "upload_time", upload_time)
+        object.__setattr__(self, "hashes", hashes)
+        object.__setattr__(self, "subdirectory", subdirectory)
+
+    @classmethod
+    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
+        package_archive = cls(
+            url=_get(d, str, "url"),
+            path=_get(d, str, "path"),
+            size=_get(d, int, "size"),
+            upload_time=_get(d, datetime, "upload-time"),
+            hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"),  # type: ignore[type-abstract]
+            subdirectory=_get(d, str, "subdirectory"),
+        )
+        _validate_path_url(package_archive.path, package_archive.url)
+        return package_archive
+
+
+@dataclass(frozen=True, init=False)
+class PackageSdist:
+    name: str | None = None
+    upload_time: datetime | None = None
+    url: str | None = None
+    path: str | None = None
+    size: int | None = None
+    hashes: Mapping[str, str]  # type: ignore[misc]
+
+    def __init__(
+        self,
+        *,
+        name: str | None = None,
+        upload_time: datetime | None = None,
+        url: str | None = None,
+        path: str | None = None,
+        size: int | None = None,
+        hashes: Mapping[str, str],
+    ) -> None:
+        # In Python 3.10+ make dataclass kw_only=True and remove __init__
+        object.__setattr__(self, "name", name)
+        object.__setattr__(self, "upload_time", upload_time)
+        object.__setattr__(self, "url", url)
+        object.__setattr__(self, "path", path)
+        object.__setattr__(self, "size", size)
+        object.__setattr__(self, "hashes", hashes)
+
+    @classmethod
+    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
+        package_sdist = cls(
+            name=_get(d, str, "name"),
+            upload_time=_get(d, datetime, "upload-time"),
+            url=_get(d, str, "url"),
+            path=_get(d, str, "path"),
+            size=_get(d, int, "size"),
+            hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"),  # type: ignore[type-abstract]
+        )
+        _validate_path_url(package_sdist.path, package_sdist.url)
+        return package_sdist
+
+
+@dataclass(frozen=True, init=False)
+class PackageWheel:
+    name: str | None = None
+    upload_time: datetime | None = None
+    url: str | None = None
+    path: str | None = None
+    size: int | None = None
+    hashes: Mapping[str, str]  # type: ignore[misc]
+
+    def __init__(
+        self,
+        *,
+        name: str | None = None,
+        upload_time: datetime | None = None,
+        url: str | None = None,
+        path: str | None = None,
+        size: int | None = None,
+        hashes: Mapping[str, str],
+    ) -> None:
+        # In Python 3.10+ make dataclass kw_only=True and remove __init__
+        object.__setattr__(self, "name", name)
+        object.__setattr__(self, "upload_time", upload_time)
+        object.__setattr__(self, "url", url)
+        object.__setattr__(self, "path", path)
+        object.__setattr__(self, "size", size)
+        object.__setattr__(self, "hashes", hashes)
+
+    @classmethod
+    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
+        package_wheel = cls(
+            name=_get(d, str, "name"),
+            upload_time=_get(d, datetime, "upload-time"),
+            url=_get(d, str, "url"),
+            path=_get(d, str, "path"),
+            size=_get(d, int, "size"),
+            hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"),  # type: ignore[type-abstract]
+        )
+        _validate_path_url(package_wheel.path, package_wheel.url)
+        return package_wheel
+
+
+@dataclass(frozen=True, init=False)
+class Package:
+    name: NormalizedName
+    version: Version | None = None
+    marker: Marker | None = None
+    requires_python: SpecifierSet | None = None
+    dependencies: Sequence[Mapping[str, Any]] | None = None
+    vcs: PackageVcs | None = None
+    directory: PackageDirectory | None = None
+    archive: PackageArchive | None = None
+    index: str | None = None
+    sdist: PackageSdist | None = None
+    wheels: Sequence[PackageWheel] | None = None
+    attestation_identities: Sequence[Mapping[str, Any]] | None = None
+    tool: Mapping[str, Any] | None = None
+
+    def __init__(
+        self,
+        *,
+        name: NormalizedName,
+        version: Version | None = None,
+        marker: Marker | None = None,
+        requires_python: SpecifierSet | None = None,
+        dependencies: Sequence[Mapping[str, Any]] | None = None,
+        vcs: PackageVcs | None = None,
+        directory: PackageDirectory | None = None,
+        archive: PackageArchive | None = None,
+        index: str | None = None,
+        sdist: PackageSdist | None = None,
+        wheels: Sequence[PackageWheel] | None = None,
+        attestation_identities: Sequence[Mapping[str, Any]] | None = None,
+        tool: Mapping[str, Any] | None = None,
+    ) -> None:
+        # In Python 3.10+ make dataclass kw_only=True and remove __init__
+        object.__setattr__(self, "name", name)
+        object.__setattr__(self, "version", version)
+        object.__setattr__(self, "marker", marker)
+        object.__setattr__(self, "requires_python", requires_python)
+        object.__setattr__(self, "dependencies", dependencies)
+        object.__setattr__(self, "vcs", vcs)
+        object.__setattr__(self, "directory", directory)
+        object.__setattr__(self, "archive", archive)
+        object.__setattr__(self, "index", index)
+        object.__setattr__(self, "sdist", sdist)
+        object.__setattr__(self, "wheels", wheels)
+        object.__setattr__(self, "attestation_identities", attestation_identities)
+        object.__setattr__(self, "tool", tool)
+
+    @classmethod
+    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
+        package = cls(
+            name=_get_required_as(d, str, _validate_normalized_name, "name"),
+            version=_get_as(d, str, Version, "version"),
+            requires_python=_get_as(d, str, SpecifierSet, "requires-python"),
+            dependencies=_get_sequence(d, Mapping, "dependencies"),  # type: ignore[type-abstract]
+            marker=_get_as(d, str, Marker, "marker"),
+            vcs=_get_object(d, PackageVcs, "vcs"),
+            directory=_get_object(d, PackageDirectory, "directory"),
+            archive=_get_object(d, PackageArchive, "archive"),
+            index=_get(d, str, "index"),
+            sdist=_get_object(d, PackageSdist, "sdist"),
+            wheels=_get_sequence_of_objects(d, PackageWheel, "wheels"),
+            attestation_identities=_get_sequence(d, Mapping, "attestation-identities"),  # type: ignore[type-abstract]
+            tool=_get(d, Mapping, "tool"),  # type: ignore[type-abstract]
+        )
+        distributions = bool(package.sdist) + len(package.wheels or [])
+        direct_urls = (
+            bool(package.vcs) + bool(package.directory) + bool(package.archive)
+        )
+        if distributions > 0 and direct_urls > 0:
+            raise PylockValidationError(
+                "None of vcs, directory, archive must be set if sdist or wheels are set"
+            )
+        if distributions == 0 and direct_urls != 1:
+            raise PylockValidationError(
+                "Exactly one of vcs, directory, archive must be set "
+                "if sdist and wheels are not set"
+            )
+        try:
+            for i, attestation_identity in enumerate(  # noqa: B007
+                package.attestation_identities or []
+            ):
+                _get_required(attestation_identity, str, "kind")
+        except Exception as e:
+            raise PylockValidationError(
+                e, context=f"attestation-identities[{i}]"
+            ) from e
+        return package
+
+    @property
+    def is_direct(self) -> bool:
+        return not (self.sdist or self.wheels)
+
+
+@dataclass(frozen=True, init=False)
+class Pylock:
+    """A class representing a pylock file."""
+
+    lock_version: Version
+    environments: Sequence[Marker] | None = None
+    requires_python: SpecifierSet | None = None
+    extras: Sequence[NormalizedName] | None = None
+    dependency_groups: Sequence[str] | None = None
+    default_groups: Sequence[str] | None = None
+    created_by: str  # type: ignore[misc]
+    packages: Sequence[Package]  # type: ignore[misc]
+    tool: Mapping[str, Any] | None = None
+
+    def __init__(
+        self,
+        *,
+        lock_version: Version,
+        environments: Sequence[Marker] | None = None,
+        requires_python: SpecifierSet | None = None,
+        extras: Sequence[NormalizedName] | None = None,
+        dependency_groups: Sequence[str] | None = None,
+        default_groups: Sequence[str] | None = None,
+        created_by: str,
+        packages: Sequence[Package],
+        tool: Mapping[str, Any] | None = None,
+    ) -> None:
+        # In Python 3.10+ make dataclass kw_only=True and remove __init__
+        object.__setattr__(self, "lock_version", lock_version)
+        object.__setattr__(self, "environments", environments)
+        object.__setattr__(self, "requires_python", requires_python)
+        object.__setattr__(self, "extras", extras)
+        object.__setattr__(self, "dependency_groups", dependency_groups)
+        object.__setattr__(self, "default_groups", default_groups)
+        object.__setattr__(self, "created_by", created_by)
+        object.__setattr__(self, "packages", packages)
+        object.__setattr__(self, "tool", tool)
+
+    @classmethod
+    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
+        pylock = cls(
+            lock_version=_get_required_as(d, str, Version, "lock-version"),
+            environments=_get_sequence_as(d, str, Marker, "environments"),
+            extras=_get_sequence_as(d, str, _validate_normalized_name, "extras"),
+            dependency_groups=_get_sequence(d, str, "dependency-groups"),
+            default_groups=_get_sequence(d, str, "default-groups"),
+            created_by=_get_required(d, str, "created-by"),
+            requires_python=_get_as(d, str, SpecifierSet, "requires-python"),
+            packages=_get_required_sequence_of_objects(d, Package, "packages"),
+            tool=_get(d, Mapping, "tool"),  # type: ignore[type-abstract]
+        )
+        if not Version("1") <= pylock.lock_version < Version("2"):
+            raise PylockUnsupportedVersionError(
+                f"pylock version {pylock.lock_version} is not supported"
+            )
+        if pylock.lock_version > Version("1.0"):
+            _logger.warning(
+                "pylock minor version %s is not supported", pylock.lock_version
+            )
+        return pylock
+
+    @classmethod
+    def from_dict(cls, d: Mapping[str, Any], /) -> Self:
+        """Create and validate a Pylock instance from a TOML dictionary.
+
+        Raises :class:`PylockValidationError` if the input data is not
+        spec-compliant.
+        """
+        return cls._from_dict(d)
+
+    def to_dict(self) -> Mapping[str, Any]:
+        """Convert the Pylock instance to a TOML dictionary."""
+        return dataclasses.asdict(self, dict_factory=_toml_dict_factory)
+
+    def validate(self) -> None:
+        """Validate the Pylock instance against the specification.
+
+        Raises :class:`PylockValidationError` otherwise."""
+        self.from_dict(self.to_dict())
diff --git a/setuptools/_vendor/packaging/requirements.py b/setuptools/_vendor/packaging/requirements.py
index f34bfa85c8..3079be69bf 100644
--- a/setuptools/_vendor/packaging/requirements.py
+++ b/setuptools/_vendor/packaging/requirements.py
@@ -1,14 +1,15 @@
 # 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 urllib.parse
-from typing import Any, List, Optional, Set
+from typing import Iterator
 
 from ._parser import parse_requirement as _parse_requirement
 from ._tokenizer import ParserSyntaxError
 from .markers import Marker, _normalize_extra_values
 from .specifiers import SpecifierSet
+from .utils import canonicalize_name
 
 
 class InvalidRequirement(ValueError):
@@ -37,57 +38,47 @@ def __init__(self, requirement_string: str) -> None:
             raise InvalidRequirement(str(e)) from e
 
         self.name: str = parsed.name
-        if parsed.url:
-            parsed_url = urllib.parse.urlparse(parsed.url)
-            if parsed_url.scheme == "file":
-                if urllib.parse.urlunparse(parsed_url) != parsed.url:
-                    raise InvalidRequirement("Invalid URL given")
-            elif not (parsed_url.scheme and parsed_url.netloc) or (
-                not parsed_url.scheme and not parsed_url.netloc
-            ):
-                raise InvalidRequirement(f"Invalid URL: {parsed.url}")
-            self.url: Optional[str] = parsed.url
-        else:
-            self.url = None
-        self.extras: Set[str] = set(parsed.extras if parsed.extras else [])
+        self.url: str | None = parsed.url or None
+        self.extras: set[str] = set(parsed.extras or [])
         self.specifier: SpecifierSet = SpecifierSet(parsed.specifier)
-        self.marker: Optional[Marker] = None
+        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 __str__(self) -> str:
-        parts: List[str] = [self.name]
+    def _iter_parts(self, name: str) -> Iterator[str]:
+        yield name
 
         if self.extras:
             formatted_extras = ",".join(sorted(self.extras))
-            parts.append(f"[{formatted_extras}]")
+            yield f"[{formatted_extras}]"
 
         if self.specifier:
-            parts.append(str(self.specifier))
+            yield str(self.specifier)
 
         if self.url:
-            parts.append(f"@ {self.url}")
+            yield f" @ {self.url}"
             if self.marker:
-                parts.append(" ")
+                yield " "
 
         if self.marker:
-            parts.append(f"; {self.marker}")
+            yield f"; {self.marker}"
 
-        return "".join(parts)
+    def __str__(self) -> str:
+        return "".join(self._iter_parts(self.name))
 
     def __repr__(self) -> str:
-        return f""
+        return f"<{self.__class__.__name__}('{self}')>"
 
     def __hash__(self) -> int:
-        return hash((self.__class__.__name__, str(self)))
+        return hash(tuple(self._iter_parts(canonicalize_name(self.name))))
 
-    def __eq__(self, other: Any) -> bool:
+    def __eq__(self, other: object) -> bool:
         if not isinstance(other, Requirement):
             return NotImplemented
 
         return (
-            self.name == other.name
+            canonicalize_name(self.name) == canonicalize_name(other.name)
             and self.extras == other.extras
             and self.specifier == other.specifier
             and self.url == other.url
diff --git a/setuptools/_vendor/packaging/specifiers.py b/setuptools/_vendor/packaging/specifiers.py
index ba8fe37b7f..5d26b0d1ae 100644
--- a/setuptools/_vendor/packaging/specifiers.py
+++ b/setuptools/_vendor/packaging/specifiers.py
@@ -8,35 +8,38 @@
     from packaging.version import Version
 """
 
+from __future__ import annotations
+
 import abc
 import itertools
 import re
-from typing import (
-    Callable,
-    Iterable,
-    Iterator,
-    List,
-    Optional,
-    Set,
-    Tuple,
-    TypeVar,
-    Union,
-)
+from typing import Callable, Final, Iterable, Iterator, TypeVar, Union
 
 from .utils import canonicalize_version
-from .version import Version
+from .version import InvalidVersion, Version
 
 UnparsedVersion = Union[Version, str]
 UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion)
 CallableOperator = Callable[[Version, str], bool]
 
 
-def _coerce_version(version: UnparsedVersion) -> Version:
+def _coerce_version(version: UnparsedVersion) -> Version | None:
     if not isinstance(version, Version):
-        version = Version(version)
+        try:
+            version = Version(version)
+        except InvalidVersion:
+            return None
     return version
 
 
+def _public_version(version: Version) -> Version:
+    return version.__replace__(local=None)
+
+
+def _base_version(version: Version) -> Version:
+    return version.__replace__(pre=None, post=None, dev=None, local=None)
+
+
 class InvalidSpecifier(ValueError):
     """
     Raised when attempting to create a :class:`Specifier` with a specifier
@@ -50,6 +53,14 @@ class InvalidSpecifier(ValueError):
 
 
 class BaseSpecifier(metaclass=abc.ABCMeta):
+    __slots__ = ()
+    __match_args__ = ("_str",)
+
+    @property
+    def _str(self) -> str:
+        """Internal property for match_args"""
+        return str(self)
+
     @abc.abstractmethod
     def __str__(self) -> str:
         """
@@ -74,14 +85,14 @@ def __eq__(self, other: object) -> bool:
 
     @property
     @abc.abstractmethod
-    def prereleases(self) -> Optional[bool]:
+    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
+    @prereleases.setter  # noqa: B027
     def prereleases(self, value: bool) -> None:
         """Setter for :attr:`prereleases`.
 
@@ -89,14 +100,14 @@ def prereleases(self, value: bool) -> None:
         """
 
     @abc.abstractmethod
-    def contains(self, item: str, prereleases: Optional[bool] = None) -> bool:
+    def contains(self, item: str, prereleases: bool | None = None) -> bool:
         """
         Determines if the given item is contained within this specifier.
         """
 
     @abc.abstractmethod
     def filter(
-        self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None
+        self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None
     ) -> Iterator[UnparsedVersionVar]:
         """
         Takes an iterable of items and filters them so that only items which
@@ -114,6 +125,8 @@ class Specifier(BaseSpecifier):
         comma-separated version specifiers (which is what package metadata contains).
     """
 
+    __slots__ = ("_prereleases", "_spec", "_spec_version")
+
     _operator_regex_str = r"""
         (?P(~=|==|!=|<=|>=|<|>|===))
         """
@@ -212,11 +225,11 @@ class Specifier(BaseSpecifier):
         """
 
     _regex = re.compile(
-        r"^\s*" + _operator_regex_str + _version_regex_str + r"\s*$",
+        r"\s*" + _operator_regex_str + _version_regex_str + r"\s*",
         re.VERBOSE | re.IGNORECASE,
     )
 
-    _operators = {
+    _operators: Final = {
         "~=": "compatible",
         "==": "equal",
         "!=": "not_equal",
@@ -227,7 +240,7 @@ class Specifier(BaseSpecifier):
         "===": "arbitrary",
     }
 
-    def __init__(self, spec: str = "", prereleases: Optional[bool] = None) -> None:
+    def __init__(self, spec: str = "", prereleases: bool | None = None) -> None:
         """Initialize a Specifier instance.
 
         :param spec:
@@ -240,11 +253,11 @@ def __init__(self, spec: str = "", prereleases: Optional[bool] = None) -> None:
         :raises InvalidSpecifier:
             If the given specifier is invalid (i.e. bad syntax).
         """
-        match = self._regex.search(spec)
+        match = self._regex.fullmatch(spec)
         if not match:
-            raise InvalidSpecifier(f"Invalid specifier: '{spec}'")
+            raise InvalidSpecifier(f"Invalid specifier: {spec!r}")
 
-        self._spec: Tuple[str, str] = (
+        self._spec: tuple[str, str] = (
             match.group("operator").strip(),
             match.group("version").strip(),
         )
@@ -252,33 +265,62 @@ def __init__(self, spec: str = "", prereleases: Optional[bool] = None) -> None:
         # Store whether or not this Specifier should accept prereleases
         self._prereleases = prereleases
 
-    # https://github.com/python/mypy/pull/13475#pullrequestreview-1079784515
-    @property  # type: ignore[override]
-    def prereleases(self) -> bool:
+        # Specifier version cache
+        self._spec_version: tuple[str, Version] | None = None
+
+    def _get_spec_version(self, version: str) -> Version | None:
+        """One element cache, as only one spec Version is needed per Specifier."""
+        if self._spec_version is not None and self._spec_version[0] == version:
+            return self._spec_version[1]
+
+        version_specifier = _coerce_version(version)
+        if version_specifier is None:
+            return None
+
+        self._spec_version = (version, version_specifier)
+        return version_specifier
+
+    def _require_spec_version(self, version: str) -> Version:
+        """Get spec version, asserting it's valid (not for === operator).
+
+        This method should only be called for operators where version
+        strings are guaranteed to be valid PEP 440 versions (not ===).
+        """
+        spec_version = self._get_spec_version(version)
+        assert spec_version is not None
+        return spec_version
+
+    @property
+    def prereleases(self) -> bool | None:
         # If there is an explicit prereleases set for this, then we'll just
         # blindly use that.
         if self._prereleases is not None:
             return self._prereleases
 
-        # Look at all of our specifiers and determine if they are inclusive
-        # operators, and if they are if they are including an explicit
-        # prerelease.
-        operator, version = self._spec
-        if operator in ["==", ">=", "<=", "~=", "==="]:
-            # The == specifier can include a trailing .*, if it does we
-            # want to remove before parsing.
-            if operator == "==" and version.endswith(".*"):
-                version = version[:-2]
-
-            # Parse the version, and if it is a pre-release than this
-            # specifier allows pre-releases.
-            if Version(version).is_prerelease:
+        # Only the "!=" operator does not imply prereleases when
+        # the version in the specifier is a prerelease.
+        operator, version_str = self._spec
+        if operator != "!=":
+            # The == specifier with trailing .* cannot include prereleases
+            # e.g. "==1.0a1.*" is not valid.
+            if operator == "==" and version_str.endswith(".*"):
+                return False
+
+            # "===" can have arbitrary string versions, so we cannot parse
+            # those, we take prereleases as unknown (None) for those.
+            version = self._get_spec_version(version_str)
+            if version is None:
+                return None
+
+            # For all other operators, use the check if spec Version
+            # object implies pre-releases.
+            if version.is_prerelease:
                 return True
 
         return False
 
     @prereleases.setter
-    def prereleases(self, value: bool) -> None:
+    def prereleases(self, value: bool | None) -> None:
         self._prereleases = value
 
     @property
@@ -328,12 +370,18 @@ def __str__(self) -> str:
         return "{}{}".format(*self._spec)
 
     @property
-    def _canonical_spec(self) -> Tuple[str, str]:
+    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(
-            self._spec[1],
-            strip_trailing_zero=(self._spec[0] != "~="),
+            spec_version, strip_trailing_zero=(operator != "~=")
         )
-        return self._spec[0], canonical_version
+
+        return operator, canonical_version
 
     def __hash__(self) -> int:
         return hash(self._canonical_spec)
@@ -374,7 +422,6 @@ def _get_operator(self, op: str) -> CallableOperator:
         return operator_callable
 
     def _compare_compatible(self, prospective: Version, spec: str) -> bool:
-
         # Compatible releases have an equivalent combination of >= and ==. That
         # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to
         # implement this in terms of the other specifiers instead of
@@ -383,7 +430,7 @@ def _compare_compatible(self, prospective: Version, spec: str) -> bool:
 
         # We want everything but the last item in the version, but we want to
         # ignore suffix segments.
-        prefix = ".".join(
+        prefix = _version_join(
             list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1]
         )
 
@@ -395,22 +442,21 @@ def _compare_compatible(self, prospective: Version, spec: str) -> bool:
         )
 
     def _compare_equal(self, prospective: Version, spec: str) -> bool:
-
         # We need special logic to handle prefix matching
         if spec.endswith(".*"):
             # In the case of prefix matching we want to ignore local segment.
             normalized_prospective = canonicalize_version(
-                prospective.public, strip_trailing_zero=False
+                _public_version(prospective), strip_trailing_zero=False
             )
             # Get the normalized version string ignoring the trailing .*
             normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False)
-            # Split the spec out by dots, and pretend that there is an implicit
-            # dot in between a release segment and a pre-release segment.
+            # Split the spec out by bangs and dots, and pretend that there is
+            # an implicit dot in between a release segment and a pre-release segment.
             split_spec = _version_split(normalized_spec)
 
-            # Split the prospective version out by dots, and pretend that there
-            # is an implicit dot in between a release segment and a pre-release
-            # segment.
+            # Split the prospective version out by bangs and dots, and pretend
+            # that there is an implicit dot in between a release segment and
+            # a pre-release segment.
             split_prospective = _version_split(normalized_prospective)
 
             # 0-pad the prospective version before shortening it to get the correct
@@ -425,13 +471,13 @@ def _compare_equal(self, prospective: Version, spec: str) -> bool:
             return shortened_prospective == split_spec
         else:
             # Convert our spec string into a Version
-            spec_version = Version(spec)
+            spec_version = self._require_spec_version(spec)
 
             # If the specifier does not have a local segment, then we want to
             # act as if the prospective version also does not have a local
             # segment.
             if not spec_version.local:
-                prospective = Version(prospective.public)
+                prospective = _public_version(prospective)
 
             return prospective == spec_version
 
@@ -439,24 +485,21 @@ def _compare_not_equal(self, prospective: Version, spec: str) -> bool:
         return not self._compare_equal(prospective, spec)
 
     def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool:
-
         # NB: Local version identifiers are NOT permitted in the version
         # specifier, so local version labels can be universally removed from
         # the prospective version.
-        return Version(prospective.public) <= Version(spec)
+        return _public_version(prospective) <= self._require_spec_version(spec)
 
     def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool:
-
         # NB: Local version identifiers are NOT permitted in the version
         # specifier, so local version labels can be universally removed from
         # the prospective version.
-        return Version(prospective.public) >= Version(spec)
+        return _public_version(prospective) >= self._require_spec_version(spec)
 
     def _compare_less_than(self, prospective: Version, spec_str: str) -> bool:
-
         # Convert our spec to a Version instance, since we'll want to work with
         # it as a version.
-        spec = Version(spec_str)
+        spec = self._require_spec_version(spec_str)
 
         # Check to see if the prospective version is less than the spec
         # version. If it's not we can short circuit and just return False now
@@ -468,9 +511,12 @@ def _compare_less_than(self, prospective: Version, spec_str: str) -> bool:
         # includes is a pre-release version, that we do not accept pre-release
         # versions for the version mentioned in the specifier (e.g. <3.1 should
         # not match 3.1.dev0, but should match 3.0.dev0).
-        if not spec.is_prerelease and prospective.is_prerelease:
-            if Version(prospective.base_version) == Version(spec.base_version):
-                return False
+        if (
+            not spec.is_prerelease
+            and prospective.is_prerelease
+            and _base_version(prospective) == _base_version(spec)
+        ):
+            return False
 
         # If we've gotten to here, it means that prospective version is both
         # less than the spec version *and* it's not a pre-release of the same
@@ -478,10 +524,9 @@ def _compare_less_than(self, prospective: Version, spec_str: str) -> bool:
         return True
 
     def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool:
-
         # Convert our spec to a Version instance, since we'll want to work with
         # it as a version.
-        spec = Version(spec_str)
+        spec = self._require_spec_version(spec_str)
 
         # Check to see if the prospective version is greater than the spec
         # version. If it's not we can short circuit and just return False now
@@ -493,25 +538,29 @@ def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool:
         # includes is a post-release version, that we do not accept
         # post-release versions for the version mentioned in the specifier
         # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0).
-        if not spec.is_postrelease and prospective.is_postrelease:
-            if Version(prospective.base_version) == Version(spec.base_version):
-                return False
+        if (
+            not spec.is_postrelease
+            and prospective.is_postrelease
+            and _base_version(prospective) == _base_version(spec)
+        ):
+            return False
 
         # Ensure that we do not allow a local version of the version mentioned
         # in the specifier, which is technically greater than, to match.
-        if prospective.local is not None:
-            if Version(prospective.base_version) == Version(spec.base_version):
-                return False
+        if prospective.local is not None and _base_version(
+            prospective
+        ) == _base_version(spec):
+            return False
 
         # If we've gotten to here, it means that prospective version is both
         # greater than the spec version *and* it's not a pre-release of the
         # same version in the spec.
         return True
 
-    def _compare_arbitrary(self, prospective: Version, spec: str) -> bool:
+    def _compare_arbitrary(self, prospective: Version | str, spec: str) -> bool:
         return str(prospective).lower() == str(spec).lower()
 
-    def __contains__(self, item: Union[str, Version]) -> bool:
+    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.
@@ -526,15 +575,13 @@ def __contains__(self, item: Union[str, Version]) -> bool:
         >>> "1.0.0" in Specifier(">=1.2.3")
         False
         >>> "1.3.0a1" in Specifier(">=1.2.3")
-        False
+        True
         >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True)
         True
         """
         return self.contains(item)
 
-    def contains(
-        self, item: UnparsedVersion, prereleases: Optional[bool] = None
-    ) -> bool:
+    def contains(self, item: UnparsedVersion, prereleases: bool | None = None) -> bool:
         """Return whether or not the item is contained in this specifier.
 
         :param item:
@@ -542,8 +589,8 @@ def contains(
             :class:`Version` instance.
         :param prereleases:
             Whether or not to match prereleases with this Specifier. If set to
-            ``None`` (the default), it uses :attr:`prereleases` to determine
-            whether or not prereleases are allowed.
+            ``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
@@ -552,34 +599,17 @@ def contains(
         >>> Specifier(">=1.2.3").contains("1.0.0")
         False
         >>> Specifier(">=1.2.3").contains("1.3.0a1")
-        False
-        >>> Specifier(">=1.2.3", prereleases=True).contains("1.3.0a1")
         True
-        >>> Specifier(">=1.2.3").contains("1.3.0a1", prereleases=True)
+        >>> Specifier(">=1.2.3", prereleases=False).contains("1.3.0a1")
+        False
+        >>> Specifier(">=1.2.3").contains("1.3.0a1")
         True
         """
 
-        # Determine if prereleases are to be allowed or not.
-        if prereleases is None:
-            prereleases = self.prereleases
-
-        # Normalize item to a Version, this allows us to have a shortcut for
-        # "2.0" in Specifier(">=2")
-        normalized_item = _coerce_version(item)
-
-        # Determine if we should be supporting prereleases in this specifier
-        # or not, if we do not support prereleases than we can short circuit
-        # logic if this version is a prereleases.
-        if normalized_item.is_prerelease and not prereleases:
-            return False
-
-        # Actually do the comparison to determine if this item is contained
-        # within this Specifier or not.
-        operator_callable: CallableOperator = self._get_operator(self.operator)
-        return operator_callable(normalized_item, self.version)
+        return bool(list(self.filter([item], prereleases=prereleases)))
 
     def filter(
-        self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None
+        self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None
     ) -> Iterator[UnparsedVersionVar]:
         """Filter items in the given iterable, that match the specifier.
 
@@ -588,13 +618,8 @@ def filter(
             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 be intelligently decide whether to allow
-            prereleases or not (based on the :attr:`prereleases` attribute, and
-            whether the only versions matching are prereleases).
-
-        This method is smarter than just ``filter(Specifier().contains, [...])``
-        because it implements the rule from :pep:`440` that a prerelease item
-        SHOULD be accepted if no other versions match the given specifier.
+            ``None`` (the default), it will follow the recommendation from :pep:`440`
+            and match prereleases if there are no other versions.
 
         >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"]))
         ['1.3']
@@ -607,46 +632,63 @@ def filter(
         >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"]))
         ['1.3', '1.5a1']
         """
+        prereleases_versions = []
+        found_non_prereleases = False
 
-        yielded = False
-        found_prereleases = []
+        # Determine if to include prereleases by default
+        include_prereleases = (
+            prereleases if prereleases is not None else self.prereleases
+        )
 
-        kw = {"prereleases": prereleases if prereleases is not None else True}
+        # Get the matching operator
+        operator_callable = self._get_operator(self.operator)
 
-        # Attempt to iterate over all the values in the iterable and if any of
-        # them match, yield them.
+        # Filter versions
         for version in iterable:
             parsed_version = _coerce_version(version)
-
-            if self.contains(parsed_version, **kw):
-                # If our version is a prerelease, and we were not set to allow
-                # prereleases, then we'll store it for later in case nothing
-                # else matches this specifier.
-                if parsed_version.is_prerelease and not (
-                    prereleases or self.prereleases
+            if parsed_version is None:
+                # === operator can match arbitrary (non-version) strings
+                if self.operator == "===" and self._compare_arbitrary(
+                    version, self.version
                 ):
-                    found_prereleases.append(version)
-                # Either this is not a prerelease, or we should have been
-                # accepting prereleases from the beginning.
-                else:
-                    yielded = True
                     yield version
+            elif operator_callable(parsed_version, self.version):
+                # If it's not a prerelease or prereleases are allowed, yield it directly
+                if not parsed_version.is_prerelease or include_prereleases:
+                    found_non_prereleases = True
+                    yield version
+                # Otherwise collect prereleases for potential later use
+                elif prereleases is None and self._prereleases is not False:
+                    prereleases_versions.append(version)
 
-        # Now that we've iterated over everything, determine if we've yielded
-        # any values, and if we have not and we have any prereleases stored up
-        # then we will go ahead and yield the prereleases.
-        if not yielded and found_prereleases:
-            for version in found_prereleases:
-                yield version
+        # If no non-prereleases were found and prereleases weren't
+        # explicitly forbidden, yield the collected prereleases
+        if (
+            not found_non_prereleases
+            and prereleases is None
+            and self._prereleases is not False
+        ):
+            yield from prereleases_versions
 
 
-_prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$")
+_prefix_regex = re.compile(r"([0-9]+)((?:a|b|c|rc)[0-9]+)")
 
 
-def _version_split(version: str) -> List[str]:
-    result: List[str] = []
-    for item in version.split("."):
-        match = _prefix_regex.search(item)
+def _version_split(version: str) -> list[str]:
+    """Split version into components.
+
+    The split components are intended for version comparison. The logic does
+    not attempt to retain the original version string, so joining the
+    components back with :func:`_version_join` may not produce the original
+    version string.
+    """
+    result: list[str] = []
+
+    epoch, _, rest = version.rpartition("!")
+    result.append(epoch or "0")
+
+    for item in rest.split("."):
+        match = _prefix_regex.fullmatch(item)
         if match:
             result.extend(match.groups())
         else:
@@ -654,13 +696,24 @@ def _version_split(version: str) -> List[str]:
     return result
 
 
+def _version_join(components: list[str]) -> str:
+    """Join split version components into a version string.
+
+    This function assumes the input came from :func:`_version_split`, where the
+    first component must be the epoch (either empty or numeric), and all other
+    components numeric.
+    """
+    epoch, *rest = components
+    return f"{epoch}!{'.'.join(rest)}"
+
+
 def _is_not_suffix(segment: str) -> bool:
     return not any(
         segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post")
     )
 
 
-def _pad_version(left: List[str], right: List[str]) -> Tuple[List[str], List[str]]:
+def _pad_version(left: list[str], right: list[str]) -> tuple[list[str], list[str]]:
     left_split, right_split = [], []
 
     # Get the release segment of our versions
@@ -675,7 +728,10 @@ def _pad_version(left: List[str], right: List[str]) -> Tuple[List[str], List[str
     left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0])))
     right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0])))
 
-    return (list(itertools.chain(*left_split)), list(itertools.chain(*right_split)))
+    return (
+        list(itertools.chain.from_iterable(left_split)),
+        list(itertools.chain.from_iterable(right_split)),
+    )
 
 
 class SpecifierSet(BaseSpecifier):
@@ -685,14 +741,20 @@ class SpecifierSet(BaseSpecifier):
     specifiers (``>=3.0,!=3.1``), or no specifier at all.
     """
 
+    __slots__ = ("_prereleases", "_specs")
+
     def __init__(
-        self, specifiers: str = "", prereleases: Optional[bool] = None
+        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
@@ -703,25 +765,24 @@ def __init__(
             raised.
         """
 
-        # Split on `,` to break each individual specifier into it's own item, and
-        # strip each item to remove leading/trailing whitespace.
-        split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()]
+        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()]
 
-        # Parsed each individual specifier, attempting first to make it a
-        # Specifier.
-        parsed: Set[Specifier] = set()
-        for specifier in split_specifiers:
-            parsed.add(Specifier(specifier))
-
-        # Turn our parsed specifiers into a frozen set and save them for later.
-        self._specs = frozenset(parsed)
+            # Make each individual specifier a Specifier and save in a frozen set
+            # for later.
+            self._specs = frozenset(map(Specifier, split_specifiers))
+        else:
+            # Save the supplied specifiers in a frozen set.
+            self._specs = frozenset(specifiers)
 
         # Store our prereleases value so we can use it later to determine if
         # we accept prereleases or not.
         self._prereleases = prereleases
 
     @property
-    def prereleases(self) -> Optional[bool]:
+    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:
@@ -735,10 +796,13 @@ def prereleases(self) -> Optional[bool]:
 
         # Otherwise we'll see if any of the given specifiers accept
         # prereleases, if any of them do we'll return True, otherwise False.
-        return any(s.prereleases for s in self._specs)
+        if any(s.prereleases for s in self._specs):
+            return True
+
+        return None
 
     @prereleases.setter
-    def prereleases(self, value: bool) -> None:
+    def prereleases(self, value: bool | None) -> None:
         self._prereleases = value
 
     def __repr__(self) -> str:
@@ -778,7 +842,7 @@ def __str__(self) -> str:
     def __hash__(self) -> int:
         return hash(self._specs)
 
-    def __and__(self, other: Union["SpecifierSet", str]) -> "SpecifierSet":
+    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.
@@ -798,14 +862,13 @@ def __and__(self, other: Union["SpecifierSet", str]) -> "SpecifierSet":
 
         if self._prereleases is None and other._prereleases is not None:
             specifier._prereleases = other._prereleases
-        elif self._prereleases is not None and other._prereleases is None:
-            specifier._prereleases = self._prereleases
-        elif self._prereleases == other._prereleases:
+        elif (
+            self._prereleases is not None and other._prereleases is None
+        ) or self._prereleases == other._prereleases:
             specifier._prereleases = self._prereleases
         else:
             raise ValueError(
-                "Cannot combine SpecifierSets with True and False prerelease "
-                "overrides."
+                "Cannot combine SpecifierSets with True and False prerelease overrides."
             )
 
         return specifier
@@ -865,7 +928,7 @@ def __contains__(self, item: UnparsedVersion) -> bool:
         >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1")
         False
         >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1")
-        False
+        True
         >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)
         True
         """
@@ -874,8 +937,8 @@ def __contains__(self, item: UnparsedVersion) -> bool:
     def contains(
         self,
         item: UnparsedVersion,
-        prereleases: Optional[bool] = None,
-        installed: Optional[bool] = None,
+        prereleases: bool | None = None,
+        installed: bool | None = None,
     ) -> bool:
         """Return whether or not the item is contained in this SpecifierSet.
 
@@ -884,8 +947,11 @@ def contains(
             :class:`Version` instance.
         :param prereleases:
             Whether or not to match prereleases with this SpecifierSet. If set to
-            ``None`` (the default), it uses :attr:`prereleases` to determine
-            whether or not prereleases are allowed.
+            ``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
@@ -894,42 +960,22 @@ def contains(
         >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1")
         False
         >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1")
-        False
-        >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True).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
         """
-        # Ensure that our item is a Version instance.
-        if not isinstance(item, Version):
-            item = Version(item)
-
-        # 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:
-            prereleases = self.prereleases
-
-        # We can determine if we're going to allow pre-releases by looking to
-        # see if any of the underlying items supports them. If none of them do
-        # and this item is a pre-release then we do not allow it and we can
-        # short circuit that here.
-        # Note: This means that 1.0.dev1 would not be contained in something
-        #       like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0
-        if not prereleases and item.is_prerelease:
-            return False
+        version = _coerce_version(item)
 
-        if installed and item.is_prerelease:
-            item = Version(item.base_version)
+        if version is not None and installed and version.is_prerelease:
+            prereleases = True
 
-        # We simply dispatch to the underlying specs here to make sure that the
-        # given version is contained within all of them.
-        # Note: This use of all() here means that an empty set of specifiers
-        #       will always return True, this is an explicit design decision.
-        return all(s.contains(item, prereleases=prereleases) for s in self._specs)
+        check_item = item if version is None else version
+        return bool(list(self.filter([check_item], prereleases=prereleases)))
 
     def filter(
-        self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None
+        self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None
     ) -> Iterator[UnparsedVersionVar]:
         """Filter items in the given iterable, that match the specifiers in this set.
 
@@ -938,20 +984,15 @@ def filter(
             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 be intelligently decide whether to allow
-            prereleases or not (based on the :attr:`prereleases` attribute, and
-            whether the only versions matching are prereleases).
-
-        This method is smarter than just ``filter(SpecifierSet(...).contains, [...])``
-        because it implements the rule from :pep:`440` that a prerelease item
-        SHOULD be accepted if no other versions match the given specifier.
+            ``None`` (the default), it will follow the recommendation from :pep:`440`
+            and match prereleases if there are no other versions.
 
         >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"]))
         ['1.3']
         >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")]))
         ['1.3', ]
         >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"]))
-        []
+        ['1.5a1']
         >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True))
         ['1.3', '1.5a1']
         >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"]))
@@ -972,37 +1013,56 @@ def filter(
         # 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:
+        if prereleases is None and self.prereleases is not None:
             prereleases = self.prereleases
 
         # If we have any specifiers, then we want to wrap our iterable in the
         # filter method for each one, this will act as a logical AND amongst
         # each specifier.
         if self._specs:
+            # When prereleases is None, we need to let all versions through
+            # the individual filters, then decide about prereleases at the end
+            # based on whether any non-prereleases matched ALL specs.
             for spec in self._specs:
-                iterable = spec.filter(iterable, prereleases=bool(prereleases))
-            return iter(iterable)
-        # If we do not have any specifiers, then we need to have a rough filter
-        # which will filter out any pre-releases, unless there are no final
-        # releases.
+                iterable = spec.filter(
+                    iterable, prereleases=True if prereleases is None else prereleases
+                )
+
+            if prereleases is not None:
+                # If we have a forced prereleases value,
+                # we can immediately return the iterator.
+                return iter(iterable)
         else:
-            filtered: List[UnparsedVersionVar] = []
-            found_prereleases: List[UnparsedVersionVar] = []
-
-            for item in iterable:
-                parsed_version = _coerce_version(item)
-
-                # Store any item which is a pre-release for later unless we've
-                # already found a final version or we are accepting prereleases
-                if parsed_version.is_prerelease and not prereleases:
-                    if not filtered:
-                        found_prereleases.append(item)
-                else:
-                    filtered.append(item)
-
-            # If we've found no items except for pre-releases, then we'll go
-            # ahead and use the pre-releases
-            if not filtered and found_prereleases and prereleases is None:
-                return iter(found_prereleases)
-
-            return iter(filtered)
+            # Handle empty SpecifierSet cases where prereleases is not None.
+            if prereleases is True:
+                return iter(iterable)
+
+            if prereleases is False:
+                return (
+                    item
+                    for item in iterable
+                    if (version := _coerce_version(item)) is None
+                    or not version.is_prerelease
+                )
+
+        # Finally if prereleases is None, apply PEP 440 logic:
+        # exclude prereleases unless there are no final releases that matched.
+        filtered_items: list[UnparsedVersionVar] = []
+        found_prereleases: list[UnparsedVersionVar] = []
+        found_final_release = False
+
+        for item in iterable:
+            parsed_version = _coerce_version(item)
+            # Arbitrary strings are always included as it is not
+            # possible to determine if they are prereleases,
+            # and they have already passed all specifiers.
+            if parsed_version is None:
+                filtered_items.append(item)
+                found_prereleases.append(item)
+            elif parsed_version.is_prerelease:
+                found_prereleases.append(item)
+            else:
+                filtered_items.append(item)
+                found_final_release = True
+
+        return iter(filtered_items if found_final_release else found_prereleases)
diff --git a/setuptools/_vendor/packaging/tags.py b/setuptools/_vendor/packaging/tags.py
index 76d243414d..5ef27c897a 100644
--- a/setuptools/_vendor/packaging/tags.py
+++ b/setuptools/_vendor/packaging/tags.py
@@ -2,22 +2,22 @@
 # 2.0, and the BSD License. See the LICENSE file in the root of this repository
 # for complete details.
 
+from __future__ import annotations
+
 import logging
 import platform
+import re
+import struct
 import subprocess
 import sys
 import sysconfig
 from importlib.machinery import EXTENSION_SUFFIXES
 from typing import (
-    Dict,
-    FrozenSet,
+    Any,
     Iterable,
     Iterator,
-    List,
-    Optional,
     Sequence,
     Tuple,
-    Union,
     cast,
 )
 
@@ -26,9 +26,9 @@
 logger = logging.getLogger(__name__)
 
 PythonVersion = Sequence[int]
-MacVersion = Tuple[int, int]
+AppleVersion = Tuple[int, int]
 
-INTERPRETER_SHORT_NAMES: Dict[str, str] = {
+INTERPRETER_SHORT_NAMES: dict[str, str] = {
     "python": "py",  # Generic.
     "cpython": "cp",
     "pypy": "pp",
@@ -37,7 +37,7 @@
 }
 
 
-_32_BIT_INTERPRETER = sys.maxsize <= 2**32
+_32_BIT_INTERPRETER = struct.calcsize("P") == 4
 
 
 class Tag:
@@ -48,7 +48,7 @@ class Tag:
     is also supported.
     """
 
-    __slots__ = ["_interpreter", "_abi", "_platform", "_hash"]
+    __slots__ = ["_abi", "_hash", "_interpreter", "_platform"]
 
     def __init__(self, interpreter: str, abi: str, platform: str) -> None:
         self._interpreter = interpreter.lower()
@@ -93,8 +93,15 @@ def __str__(self) -> str:
     def __repr__(self) -> str:
         return f"<{self} @ {id(self)}>"
 
+    def __setstate__(self, state: tuple[None, dict[str, Any]]) -> None:
+        # The cached _hash is wrong when unpickling.
+        _, slots = state
+        for k, v in slots.items():
+            setattr(self, k, v)
+        self._hash = hash((self._interpreter, self._abi, self._platform))
+
 
-def parse_tag(tag: str) -> FrozenSet[Tag]:
+def parse_tag(tag: str) -> frozenset[Tag]:
     """
     Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances.
 
@@ -110,8 +117,8 @@ def parse_tag(tag: str) -> FrozenSet[Tag]:
     return frozenset(tags)
 
 
-def _get_config_var(name: str, warn: bool = False) -> Union[int, str, None]:
-    value: Union[int, str, None] = sysconfig.get_config_var(name)
+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
@@ -123,20 +130,37 @@ def _normalize_string(string: str) -> str:
     return string.replace(".", "_").replace("-", "_").replace(" ", "_")
 
 
-def _abi3_applies(python_version: PythonVersion) -> bool:
+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.
+    PEP 384 was first implemented in Python 3.2. The threaded (`--disable-gil`)
+    builds do not support abi3.
     """
-    return len(python_version) > 1 and tuple(python_version) >= (3, 2)
+    return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading
 
 
-def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> List[str]:
+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])
-    debug = pymalloc = ucs4 = ""
+    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
@@ -145,6 +169,8 @@ def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> List[str]:
     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:
@@ -158,20 +184,15 @@ def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> List[str]:
     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}")
-    abis.insert(
-        0,
-        "cp{version}{debug}{pymalloc}{ucs4}".format(
-            version=version, debug=debug, pymalloc=pymalloc, ucs4=ucs4
-        ),
-    )
+        abis.append(f"cp{version}{threading}")
+    abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}")
     return abis
 
 
 def cpython_tags(
-    python_version: Optional[PythonVersion] = None,
-    abis: Optional[Iterable[str]] = None,
-    platforms: Optional[Iterable[str]] = None,
+    python_version: PythonVersion | None = None,
+    abis: Iterable[str] | None = None,
+    platforms: Iterable[str] | None = None,
     *,
     warn: bool = False,
 ) -> Iterator[Tag]:
@@ -196,36 +217,35 @@ def cpython_tags(
     interpreter = f"cp{_version_nodot(python_version[:2])}"
 
     if abis is None:
-        if len(python_version) > 1:
-            abis = _cpython_abis(python_version, warn)
-        else:
-            abis = []
+        abis = _cpython_abis(python_version, warn) if len(python_version) > 1 else []
     abis = list(abis)
     # 'abi3' and 'none' are explicitly handled later.
     for explicit_abi in ("abi3", "none"):
         try:
             abis.remove(explicit_abi)
-        except ValueError:
+        except ValueError:  # noqa: PERF203
             pass
 
     platforms = list(platforms or platform_tags())
     for abi in abis:
         for platform_ in platforms:
             yield Tag(interpreter, abi, platform_)
-    if _abi3_applies(python_version):
+
+    threading = _is_threaded_cpython(abis)
+    use_abi3 = _abi3_applies(python_version, threading)
+    if use_abi3:
         yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms)
     yield from (Tag(interpreter, "none", platform_) for platform_ in platforms)
 
-    if _abi3_applies(python_version):
+    if use_abi3:
         for minor_version in range(python_version[1] - 1, 1, -1):
             for platform_ in platforms:
-                interpreter = "cp{version}".format(
-                    version=_version_nodot((python_version[0], minor_version))
-                )
+                version = _version_nodot((python_version[0], minor_version))
+                interpreter = f"cp{version}"
                 yield Tag(interpreter, "abi3", platform_)
 
 
-def _generic_abi() -> List[str]:
+def _generic_abi() -> list[str]:
     """
     Return the ABI tag based on EXT_SUFFIX.
     """
@@ -267,9 +287,9 @@ def _generic_abi() -> List[str]:
 
 
 def generic_tags(
-    interpreter: Optional[str] = None,
-    abis: Optional[Iterable[str]] = None,
-    platforms: Optional[Iterable[str]] = None,
+    interpreter: str | None = None,
+    abis: Iterable[str] | None = None,
+    platforms: Iterable[str] | None = None,
     *,
     warn: bool = False,
 ) -> Iterator[Tag]:
@@ -284,11 +304,8 @@ def generic_tags(
     if not interpreter:
         interp_name = interpreter_name()
         interp_version = interpreter_version(warn=warn)
-        interpreter = "".join([interp_name, interp_version])
-    if abis is None:
-        abis = _generic_abi()
-    else:
-        abis = list(abis)
+        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")
@@ -313,9 +330,9 @@ def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]:
 
 
 def compatible_tags(
-    python_version: Optional[PythonVersion] = None,
-    interpreter: Optional[str] = None,
-    platforms: Optional[Iterable[str]] = None,
+    python_version: PythonVersion | None = None,
+    interpreter: str | None = None,
+    platforms: Iterable[str] | None = None,
 ) -> Iterator[Tag]:
     """
     Yields the sequence of tags that are compatible with a specific version of Python.
@@ -347,7 +364,7 @@ def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str:
     return "i386"
 
 
-def _mac_binary_formats(version: MacVersion, cpu_arch: str) -> List[str]:
+def _mac_binary_formats(version: AppleVersion, cpu_arch: str) -> list[str]:
     formats = [cpu_arch]
     if cpu_arch == "x86_64":
         if version < (10, 4):
@@ -380,7 +397,7 @@ def _mac_binary_formats(version: MacVersion, cpu_arch: str) -> List[str]:
 
 
 def mac_platforms(
-    version: Optional[MacVersion] = None, arch: Optional[str] = None
+    version: AppleVersion | None = None, arch: str | None = None
 ) -> Iterator[str]:
     """
     Yields the platform tags for a macOS system.
@@ -392,7 +409,7 @@ def mac_platforms(
     """
     version_str, _, cpu_arch = platform.mac_ver()
     if version is None:
-        version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2])))
+        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.
@@ -406,37 +423,32 @@ def mac_platforms(
                 check=True,
                 env={"SYSTEM_VERSION_COMPAT": "0"},
                 stdout=subprocess.PIPE,
-                universal_newlines=True,
+                text=True,
             ).stdout
-            version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2])))
-    else:
-        version = version
+            version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2])))
+
     if arch is None:
         arch = _mac_arch(cpu_arch)
-    else:
-        arch = arch
 
-    if (10, 0) <= version and version < (11, 0):
+    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 = 10, minor_version
+            compat_version = major_version, minor_version
             binary_formats = _mac_binary_formats(compat_version, arch)
             for binary_format in binary_formats:
-                yield "macosx_{major}_{minor}_{binary_format}".format(
-                    major=10, minor=minor_version, binary_format=binary_format
-                )
+                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, 0
+            compat_version = major_version, minor_version
             binary_formats = _mac_binary_formats(compat_version, arch)
             for binary_format in binary_formats:
-                yield "macosx_{major}_{minor}_{binary_format}".format(
-                    major=major_version, minor=0, binary_format=binary_format
-                )
+                yield f"macosx_{major_version}_{minor_version}_{binary_format}"
 
     if version >= (11, 0):
         # Mac OS 11 on x86_64 is compatible with binaries from previous releases.
@@ -446,38 +458,131 @@ def mac_platforms(
         # 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 = 10, minor_version
+                compat_version = major_version, minor_version
                 binary_formats = _mac_binary_formats(compat_version, arch)
                 for binary_format in binary_formats:
-                    yield "macosx_{major}_{minor}_{binary_format}".format(
-                        major=compat_version[0],
-                        minor=compat_version[1],
-                        binary_format=binary_format,
-                    )
+                    yield f"macosx_{major_version}_{minor_version}_{binary_format}"
         else:
             for minor_version in range(16, 3, -1):
-                compat_version = 10, minor_version
+                compat_version = major_version, minor_version
                 binary_format = "universal2"
-                yield "macosx_{major}_{minor}_{binary_format}".format(
-                    major=compat_version[0],
-                    minor=compat_version[1],
-                    binary_format=binary_format,
-                )
+                yield f"macosx_{major_version}_{minor_version}_{binary_format}"
+
+
+def ios_platforms(
+    version: AppleVersion | None = None, multiarch: str | None = None
+) -> Iterator[str]:
+    """
+    Yields the platform tags for an iOS system.
+
+    :param version: A two-item tuple specifying the iOS version to generate
+        platform tags for. Defaults to the current iOS version.
+    :param multiarch: The CPU architecture+ABI to generate platform tags for -
+        (the value used by `sys.implementation._multiarch` e.g.,
+        `arm64_iphoneos` or `x84_64_iphonesimulator`). Defaults to the current
+        multiarch value.
+    """
+    if version is None:
+        # if iOS is the current platform, ios_ver *must* be defined. However,
+        # it won't exist for CPython versions before 3.13, which causes a mypy
+        # error.
+        _, release, _, _ = platform.ios_ver()  # type: ignore[attr-defined, unused-ignore]
+        version = cast("AppleVersion", tuple(map(int, release.split(".")[:2])))
+
+    if multiarch is None:
+        multiarch = sys.implementation._multiarch
+    multiarch = multiarch.replace("-", "_")
+
+    ios_platform_template = "ios_{major}_{minor}_{multiarch}"
+
+    # Consider any iOS major.minor version from the version requested, down to
+    # 12.0. 12.0 is the first iOS version that is known to have enough features
+    # to support CPython. Consider every possible minor release up to X.9. There
+    # highest the minor has ever gone is 8 (14.8 and 15.8) but having some extra
+    # candidates that won't ever match doesn't really hurt, and it saves us from
+    # having to keep an explicit list of known iOS versions in the code. Return
+    # the results descending order of version number.
+
+    # If the requested major version is less than 12, there won't be any matches.
+    if version[0] < 12:
+        return
+
+    # Consider the actual X.Y version that was requested.
+    yield ios_platform_template.format(
+        major=version[0], minor=version[1], multiarch=multiarch
+    )
+
+    # Consider every minor version from X.0 to the minor version prior to the
+    # version requested by the platform.
+    for minor in range(version[1] - 1, -1, -1):
+        yield ios_platform_template.format(
+            major=version[0], minor=minor, multiarch=multiarch
+        )
+
+    for major in range(version[0] - 1, 11, -1):
+        for minor in range(9, -1, -1):
+            yield ios_platform_template.format(
+                major=major, minor=minor, multiarch=multiarch
+            )
+
+
+def android_platforms(
+    api_level: int | None = None, abi: str | None = None
+) -> Iterator[str]:
+    """
+    Yields the :attr:`~Tag.platform` tags for Android. If this function is invoked on
+    non-Android platforms, the ``api_level`` and ``abi`` arguments are required.
+
+    :param int api_level: The maximum `API level
+        `__ to return. Defaults
+        to the current system's version, as returned by ``platform.android_ver``.
+    :param str abi: The `Android ABI `__,
+        e.g. ``arm64_v8a``. Defaults to the current system's ABI , as returned by
+        ``sysconfig.get_platform``. Hyphens and periods will be replaced with
+        underscores.
+    """
+    if platform.system() != "Android" and (api_level is None or abi is None):
+        raise TypeError(
+            "on non-Android platforms, the api_level and abi arguments are required"
+        )
+
+    if api_level is None:
+        # Python 3.13 was the first version to return platform.system() == "Android",
+        # and also the first version to define platform.android_ver().
+        api_level = platform.android_ver().api_level  # type: ignore[attr-defined]
+
+    if abi is None:
+        abi = sysconfig.get_platform().split("-")[-1]
+    abi = _normalize_string(abi)
+
+    # 16 is the minimum API level known to have enough features to support CPython
+    # without major patching. Yield every API level from the maximum down to the
+    # minimum, inclusive.
+    min_api_level = 16
+    for ver in range(api_level, min_api_level - 1, -1):
+        yield f"android_{ver}_{abi}"
 
 
 def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]:
     linux = _normalize_string(sysconfig.get_platform())
+    if not linux.startswith("linux_"):
+        # we should never be here, just yield the sysconfig one and return
+        yield linux
+        return
     if is_32bit:
         if linux == "linux_x86_64":
             linux = "linux_i686"
         elif linux == "linux_aarch64":
-            linux = "linux_armv7l"
+            linux = "linux_armv8l"
     _, arch = linux.split("_", 1)
-    yield from _manylinux.platform_tags(linux, arch)
-    yield from _musllinux.platform_tags(arch)
-    yield linux
+    archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch])
+    yield from _manylinux.platform_tags(archs)
+    yield from _musllinux.platform_tags(archs)
+    for arch in archs:
+        yield f"linux_{arch}"
 
 
 def _generic_platforms() -> Iterator[str]:
@@ -490,6 +595,10 @@ def platform_tags() -> Iterator[str]:
     """
     if platform.system() == "Darwin":
         return mac_platforms()
+    elif platform.system() == "iOS":
+        return ios_platforms()
+    elif platform.system() == "Android":
+        return android_platforms()
     elif platform.system() == "Linux":
         return _linux_platforms()
     else:
@@ -512,11 +621,7 @@ def interpreter_version(*, warn: bool = False) -> str:
     Returns the version of the running interpreter.
     """
     version = _get_config_var("py_version_nodot", warn=warn)
-    if version:
-        version = str(version)
-    else:
-        version = _version_nodot(sys.version_info[:2])
-    return version
+    return str(version) if version else _version_nodot(sys.version_info[:2])
 
 
 def _version_nodot(version: PythonVersion) -> str:
diff --git a/setuptools/_vendor/packaging/utils.py b/setuptools/_vendor/packaging/utils.py
index 33c613b749..c41c8137f2 100644
--- a/setuptools/_vendor/packaging/utils.py
+++ b/setuptools/_vendor/packaging/utils.py
@@ -2,16 +2,24 @@
 # 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 FrozenSet, NewType, Tuple, Union, cast
+from typing import NewType, Tuple, Union, cast
 
 from .tags import Tag, parse_tag
-from .version import InvalidVersion, Version
+from .version import InvalidVersion, Version, _TrimmedRelease
 
 BuildTag = Union[Tuple[()], Tuple[int, str]]
 NormalizedName = NewType("NormalizedName", str)
 
 
+class InvalidName(ValueError):
+    """
+    An invalid distribution name; users should refer to the packaging user guide.
+    """
+
+
 class InvalidWheelFilename(ValueError):
     """
     An invalid wheel filename was found, users should refer to PEP 427.
@@ -24,102 +32,104 @@ class InvalidSdistFilename(ValueError):
     """
 
 
-_canonicalize_regex = re.compile(r"[-_.]+")
+# Core metadata spec for `Name`
+_validate_regex = re.compile(r"[A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9]", re.IGNORECASE)
+_normalized_regex = re.compile(r"[a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9]")
 # PEP 427: The build number must start with a digit.
 _build_tag_regex = re.compile(r"(\d+)(.*)")
 
 
-def canonicalize_name(name: str) -> NormalizedName:
-    # This is taken from PEP 503.
-    value = _canonicalize_regex.sub("-", name).lower()
-    return cast(NormalizedName, value)
+def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName:
+    if validate and not _validate_regex.fullmatch(name):
+        raise InvalidName(f"name is invalid: {name!r}")
+    # Ensure all ``.`` and ``_`` are ``-``
+    # Emulates ``re.sub(r"[-_.]+", "-", name).lower()`` from PEP 503
+    # Much faster than re, and even faster than str.translate
+    value = name.lower().replace("_", "-").replace(".", "-")
+    # Condense repeats (faster than regex)
+    while "--" in value:
+        value = value.replace("--", "-")
+    return cast("NormalizedName", value)
+
+
+def is_normalized_name(name: str) -> bool:
+    return _normalized_regex.fullmatch(name) is not None
 
 
 def canonicalize_version(
-    version: Union[Version, str], *, strip_trailing_zero: bool = True
+    version: Version | str, *, strip_trailing_zero: bool = True
 ) -> str:
     """
-    This is very similar to Version.__str__, but has one subtle difference
-    with the way it handles the release segment.
-    """
-    if isinstance(version, str):
-        try:
-            parsed = Version(version)
-        except InvalidVersion:
-            # Legacy versions cannot be normalized
-            return version
-    else:
-        parsed = version
-
-    parts = []
+    Return a canonical form of a version as a string.
 
-    # Epoch
-    if parsed.epoch != 0:
-        parts.append(f"{parsed.epoch}!")
+    >>> canonicalize_version('1.0.1')
+    '1.0.1'
 
-    # Release segment
-    release_segment = ".".join(str(x) for x in parsed.release)
-    if strip_trailing_zero:
-        # NB: This strips trailing '.0's to normalize
-        release_segment = re.sub(r"(\.0)+$", "", release_segment)
-    parts.append(release_segment)
+    Per PEP 625, versions may have multiple canonical forms, differing
+    only by trailing zeros.
 
-    # Pre-release
-    if parsed.pre is not None:
-        parts.append("".join(str(x) for x in parsed.pre))
+    >>> canonicalize_version('1.0.0')
+    '1'
+    >>> canonicalize_version('1.0.0', strip_trailing_zero=False)
+    '1.0.0'
 
-    # Post-release
-    if parsed.post is not None:
-        parts.append(f".post{parsed.post}")
+    Invalid versions are returned unaltered.
 
-    # Development release
-    if parsed.dev is not None:
-        parts.append(f".dev{parsed.dev}")
-
-    # Local version segment
-    if parsed.local is not None:
-        parts.append(f"+{parsed.local}")
-
-    return "".join(parts)
+    >>> canonicalize_version('foo bar baz')
+    'foo bar baz'
+    """
+    if isinstance(version, str):
+        try:
+            version = Version(version)
+        except InvalidVersion:
+            return str(version)
+    return str(_TrimmedRelease(version) if strip_trailing_zero else version)
 
 
 def parse_wheel_filename(
     filename: str,
-) -> Tuple[NormalizedName, Version, BuildTag, FrozenSet[Tag]]:
+) -> tuple[NormalizedName, Version, BuildTag, frozenset[Tag]]:
     if not filename.endswith(".whl"):
         raise InvalidWheelFilename(
-            f"Invalid wheel filename (extension must be '.whl'): {filename}"
+            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}"
+            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
+    # See PEP 427 for the rules on escaping the project name.
     if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None:
-        raise InvalidWheelFilename(f"Invalid project name: {filename}")
+        raise InvalidWheelFilename(f"Invalid project name: {filename!r}")
     name = canonicalize_name(name_part)
-    version = Version(parts[1])
+
+    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}'"
+                f"Invalid build number: {build_part} in {filename!r}"
             )
-        build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2)))
+        build = cast("BuildTag", (int(build_match.group(1)), build_match.group(2)))
     else:
         build = ()
     tags = parse_tag(parts[-1])
     return (name, version, build, tags)
 
 
-def parse_sdist_filename(filename: str) -> Tuple[NormalizedName, Version]:
+def parse_sdist_filename(filename: str) -> tuple[NormalizedName, Version]:
     if filename.endswith(".tar.gz"):
         file_stem = filename[: -len(".tar.gz")]
     elif filename.endswith(".zip"):
@@ -127,15 +137,22 @@ def parse_sdist_filename(filename: str) -> Tuple[NormalizedName, Version]:
     else:
         raise InvalidSdistFilename(
             f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):"
-            f" {filename}"
+            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}")
+        raise InvalidSdistFilename(f"Invalid sdist filename: {filename!r}")
 
     name = canonicalize_name(name_part)
-    version = Version(version_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)
diff --git a/setuptools/_vendor/packaging/version.py b/setuptools/_vendor/packaging/version.py
index b30e8cbf84..1206c462d4 100644
--- a/setuptools/_vendor/packaging/version.py
+++ b/setuptools/_vendor/packaging/version.py
@@ -7,40 +7,91 @@
     from packaging.version import parse, Version
 """
 
-import collections
-import itertools
+from __future__ import annotations
+
 import re
-from typing import Any, Callable, Optional, SupportsInt, Tuple, Union
+import sys
+import typing
+from typing import (
+    Any,
+    Callable,
+    Literal,
+    NamedTuple,
+    SupportsInt,
+    Tuple,
+    TypedDict,
+    Union,
+)
 
 from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType
 
-__all__ = ["VERSION_PATTERN", "parse", "Version", "InvalidVersion"]
-
-InfiniteTypes = Union[InfinityType, NegativeInfinityType]
-PrePostDevType = Union[InfiniteTypes, Tuple[str, int]]
-SubLocalType = Union[InfiniteTypes, int, str]
-LocalType = 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: object) -> object:
+            @functools.wraps(func)
+            def wrapper(*args: object, **kwargs: object) -> object:
+                warnings.warn(
+                    message,
+                    category=DeprecationWarning,
+                    stacklevel=2,
+                )
+                return func(*args, **kwargs)
+
+            return wrapper
+
+        return decorator
+
+
+_LETTER_NORMALIZATION = {
+    "alpha": "a",
+    "beta": "b",
+    "c": "rc",
+    "pre": "rc",
+    "preview": "rc",
+    "rev": "post",
+    "r": "post",
+}
+
+__all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "parse"]
+
+LocalType = Tuple[Union[int, str], ...]
+
+CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]]
+CmpLocalType = Union[
     NegativeInfinityType,
-    Tuple[
-        Union[
-            SubLocalType,
-            Tuple[SubLocalType, str],
-            Tuple[NegativeInfinityType, SubLocalType],
-        ],
-        ...,
-    ],
+    Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...],
 ]
 CmpKey = Tuple[
-    int, Tuple[int, ...], PrePostDevType, PrePostDevType, PrePostDevType, LocalType
+    int,
+    Tuple[int, ...],
+    CmpPrePostDevType,
+    CmpPrePostDevType,
+    CmpPrePostDevType,
+    CmpLocalType,
 ]
 VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool]
 
-_Version = collections.namedtuple(
-    "_Version", ["epoch", "release", "dev", "pre", "post", "local"]
-)
 
+class _VersionReplace(TypedDict, total=False):
+    epoch: int | None
+    release: tuple[int, ...] | None
+    pre: tuple[Literal["a", "b", "rc"], int] | None
+    post: int | None
+    dev: int | None
+    local: str | None
 
-def parse(version: str) -> "Version":
+
+def parse(version: str) -> Version:
     """Parse the given version string.
 
     >>> parse('1.0.dev1')
@@ -63,7 +114,15 @@ class InvalidVersion(ValueError):
 
 
 class _BaseVersion:
-    _key: Tuple[Any, ...]
+    __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)
@@ -71,13 +130,13 @@ def __hash__(self) -> int:
     # 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:
+    def __lt__(self, other: _BaseVersion) -> bool:
         if not isinstance(other, _BaseVersion):
             return NotImplemented
 
         return self._key < other._key
 
-    def __le__(self, other: "_BaseVersion") -> bool:
+    def __le__(self, other: _BaseVersion) -> bool:
         if not isinstance(other, _BaseVersion):
             return NotImplemented
 
@@ -89,13 +148,13 @@ def __eq__(self, other: object) -> bool:
 
         return self._key == other._key
 
-    def __ge__(self, other: "_BaseVersion") -> bool:
+    def __ge__(self, other: _BaseVersion) -> bool:
         if not isinstance(other, _BaseVersion):
             return NotImplemented
 
         return self._key >= other._key
 
-    def __gt__(self, other: "_BaseVersion") -> bool:
+    def __gt__(self, other: _BaseVersion) -> bool:
         if not isinstance(other, _BaseVersion):
             return NotImplemented
 
@@ -110,38 +169,56 @@ def __ne__(self, other: object) -> bool:
 
 # 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?
+    v?+                                                   # optional leading v
     (?:
-        (?:(?P[0-9]+)!)?                           # epoch
-        (?P[0-9]+(?:\.[0-9]+)*)                  # release segment
+        (?:(?P[0-9]+)!)?+                          # epoch
+        (?P[0-9]+(?:\.[0-9]+)*+)                 # release segment
         (?P
                                          # pre-release
-            [-_\.]?
-            (?P(a|b|c|rc|alpha|beta|pre|preview))
-            [-_\.]?
+            [._-]?+
+            (?Palpha|a|beta|b|preview|pre|c|rc)
+            [._-]?+
             (?P[0-9]+)?
-        )?
+        )?+
         (?P                                         # post release
             (?:-(?P[0-9]+))
             |
             (?:
-                [-_\.]?
+                [._-]?
                 (?Ppost|rev|r)
-                [-_\.]?
+                [._-]?
                 (?P[0-9]+)?
             )
-        )?
+        )?+
         (?P                                          # dev release
-            [-_\.]?
+            [._-]?+
             (?Pdev)
-            [-_\.]?
+            [._-]?+
             (?P[0-9]+)?
-        )?
+        )?+
     )
-    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
+    (?:\+
+        (?P                                        # local version
+            [a-z0-9]+
+            (?:[._-][a-z0-9]+)*+
+        )
+    )?+
 """
 
-VERSION_PATTERN = _VERSION_PATTERN
+_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.
 
@@ -154,6 +231,82 @@ def __ne__(self, other: object) -> bool:
 """
 
 
+# Validation pattern for local version in replace()
+_LOCAL_PATTERN = re.compile(r"[a-z0-9]+(?:[._-][a-z0-9]+)*", re.IGNORECASE)
+
+
+def _validate_epoch(value: object, /) -> int:
+    epoch = value or 0
+    if isinstance(epoch, int) and epoch >= 0:
+        return epoch
+    msg = f"epoch must be non-negative integer, got {epoch}"
+    raise InvalidVersion(msg)
+
+
+def _validate_release(value: object, /) -> tuple[int, ...]:
+    release = (0,) if value is None else value
+    if (
+        isinstance(release, tuple)
+        and len(release) > 0
+        and all(isinstance(i, int) and i >= 0 for i in release)
+    ):
+        return release
+    msg = f"release must be a non-empty tuple of non-negative integers, got {release}"
+    raise InvalidVersion(msg)
+
+
+def _validate_pre(value: object, /) -> tuple[Literal["a", "b", "rc"], int] | None:
+    if value is None:
+        return value
+    if (
+        isinstance(value, tuple)
+        and len(value) == 2
+        and value[0] in ("a", "b", "rc")
+        and isinstance(value[1], int)
+        and value[1] >= 0
+    ):
+        return value
+    msg = f"pre must be a tuple of ('a'|'b'|'rc', non-negative int), got {value}"
+    raise InvalidVersion(msg)
+
+
+def _validate_post(value: object, /) -> tuple[Literal["post"], int] | None:
+    if value is None:
+        return value
+    if isinstance(value, int) and value >= 0:
+        return ("post", value)
+    msg = f"post must be non-negative integer, got {value}"
+    raise InvalidVersion(msg)
+
+
+def _validate_dev(value: object, /) -> tuple[Literal["dev"], int] | None:
+    if value is None:
+        return value
+    if isinstance(value, int) and value >= 0:
+        return ("dev", value)
+    msg = f"dev must be non-negative integer, got {value}"
+    raise InvalidVersion(msg)
+
+
+def _validate_local(value: object, /) -> LocalType | None:
+    if value is None:
+        return value
+    if isinstance(value, str) and _LOCAL_PATTERN.fullmatch(value):
+        return _parse_local_version(value)
+    msg = f"local must be a valid version string, got {value!r}"
+    raise InvalidVersion(msg)
+
+
+# Backward compatibility for internals before 26.0. Do not use.
+class _Version(NamedTuple):
+    epoch: int
+    release: tuple[int, ...]
+    dev: tuple[str, int] | None
+    pre: tuple[str, int] | None
+    post: tuple[str, int] | None
+    local: LocalType | None
+
+
 class Version(_BaseVersion):
     """This class abstracts handling of a project's versions.
 
@@ -178,8 +331,19 @@ class Version(_BaseVersion):
     True
     """
 
-    _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
-    _key: CmpKey
+    __slots__ = ("_dev", "_epoch", "_key_cache", "_local", "_post", "_pre", "_release")
+    __match_args__ = ("_str",)
+
+    _regex = re.compile(r"\s*" + VERSION_PATTERN + r"\s*", re.VERBOSE | re.IGNORECASE)
+
+    _epoch: int
+    _release: tuple[int, ...]
+    _dev: tuple[str, int] | None
+    _pre: tuple[str, int] | None
+    _post: tuple[str, int] | None
+    _local: LocalType | None
+
+    _key_cache: CmpKey | None
 
     def __init__(self, version: str) -> None:
         """Initialize a Version object.
@@ -191,34 +355,86 @@ def __init__(self, version: str) -> None:
             If the ``version`` does not conform to PEP 440 in any way then this
             exception will be raised.
         """
-
         # Validate the version and parse it into pieces
-        match = self._regex.search(version)
+        match = self._regex.fullmatch(version)
         if not match:
-            raise InvalidVersion(f"Invalid version: '{version}'")
-
-        # Store the parsed out pieces of the version
-        self._version = _Version(
-            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
-            release=tuple(int(i) for i in match.group("release").split(".")),
-            pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
-            post=_parse_letter_version(
-                match.group("post_l"), match.group("post_n1") or match.group("post_n2")
-            ),
-            dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
-            local=_parse_local_version(match.group("local")),
+            raise InvalidVersion(f"Invalid version: {version!r}")
+        self._epoch = int(match.group("epoch")) if match.group("epoch") else 0
+        self._release = tuple(map(int, match.group("release").split(".")))
+        self._pre = _parse_letter_version(match.group("pre_l"), match.group("pre_n"))
+        self._post = _parse_letter_version(
+            match.group("post_l"), match.group("post_n1") or match.group("post_n2")
         )
+        self._dev = _parse_letter_version(match.group("dev_l"), match.group("dev_n"))
+        self._local = _parse_local_version(match.group("local"))
+
+        # Key which will be used for sorting
+        self._key_cache = None
+
+    def __replace__(self, **kwargs: Unpack[_VersionReplace]) -> Self:
+        epoch = _validate_epoch(kwargs["epoch"]) if "epoch" in kwargs else self._epoch
+        release = (
+            _validate_release(kwargs["release"])
+            if "release" in kwargs
+            else self._release
+        )
+        pre = _validate_pre(kwargs["pre"]) if "pre" in kwargs else self._pre
+        post = _validate_post(kwargs["post"]) if "post" in kwargs else self._post
+        dev = _validate_dev(kwargs["dev"]) if "dev" in kwargs else self._dev
+        local = _validate_local(kwargs["local"]) if "local" in kwargs else self._local
+
+        if (
+            epoch == self._epoch
+            and release == self._release
+            and pre == self._pre
+            and post == self._post
+            and dev == self._dev
+            and local == self._local
+        ):
+            return self
+
+        new_version = self.__class__.__new__(self.__class__)
+        new_version._key_cache = None
+        new_version._epoch = epoch
+        new_version._release = release
+        new_version._pre = pre
+        new_version._post = post
+        new_version._dev = dev
+        new_version._local = local
+
+        return new_version
+
+    @property
+    def _key(self) -> CmpKey:
+        if self._key_cache is None:
+            self._key_cache = _cmpkey(
+                self._epoch,
+                self._release,
+                self._pre,
+                self._post,
+                self._dev,
+                self._local,
+            )
+        return self._key_cache
 
-        # Generate a key which will be used for sorting
-        self._key = _cmpkey(
-            self._version.epoch,
-            self._version.release,
-            self._version.pre,
-            self._version.post,
-            self._version.dev,
-            self._version.local,
+    @property
+    @_deprecated("Version._version is private and will be removed soon")
+    def _version(self) -> _Version:
+        return _Version(
+            self._epoch, self._release, self._dev, self._pre, self._post, self._local
         )
 
+    @_version.setter
+    @_deprecated("Version._version is private and will be removed soon")
+    def _version(self, value: _Version) -> None:
+        self._epoch = value.epoch
+        self._release = value.release
+        self._dev = value.dev
+        self._pre = value.pre
+        self._post = value.post
+        self._local = value.local
+        self._key_cache = None
+
     def __repr__(self) -> str:
         """A representation of the Version that shows all internal state.
 
@@ -228,37 +444,40 @@ def __repr__(self) -> str:
         return f""
 
     def __str__(self) -> str:
-        """A string representation of the version that can be rounded-tripped.
+        """A string representation of the version that can be round-tripped.
 
         >>> str(Version("1.0a5"))
         '1.0a5'
         """
-        parts = []
+        # This is a hot function, so not calling self.base_version
+        version = ".".join(map(str, self.release))
 
         # Epoch
-        if self.epoch != 0:
-            parts.append(f"{self.epoch}!")
-
-        # Release segment
-        parts.append(".".join(str(x) for x in self.release))
+        if self.epoch:
+            version = f"{self.epoch}!{version}"
 
         # Pre-release
         if self.pre is not None:
-            parts.append("".join(str(x) for x in self.pre))
+            version += "".join(map(str, self.pre))
 
         # Post-release
         if self.post is not None:
-            parts.append(f".post{self.post}")
+            version += f".post{self.post}"
 
         # Development release
         if self.dev is not None:
-            parts.append(f".dev{self.dev}")
+            version += f".dev{self.dev}"
 
         # Local version segment
         if self.local is not None:
-            parts.append(f"+{self.local}")
+            version += f"+{self.local}"
+
+        return version
 
-        return "".join(parts)
+    @property
+    def _str(self) -> str:
+        """Internal property for match_args"""
+        return str(self)
 
     @property
     def epoch(self) -> int:
@@ -269,11 +488,10 @@ def epoch(self) -> int:
         >>> Version("1!2.0.0").epoch
         1
         """
-        _epoch: int = self._version.epoch
-        return _epoch
+        return self._epoch
 
     @property
-    def release(self) -> Tuple[int, ...]:
+    def release(self) -> tuple[int, ...]:
         """The components of the "release" segment of the version.
 
         >>> Version("1.2.3").release
@@ -286,11 +504,10 @@ def release(self) -> Tuple[int, ...]:
         Includes trailing zeroes but not the epoch or any pre-release / development /
         post-release suffixes.
         """
-        _release: Tuple[int, ...] = self._version.release
-        return _release
+        return self._release
 
     @property
-    def pre(self) -> Optional[Tuple[str, int]]:
+    def pre(self) -> tuple[str, int] | None:
         """The pre-release segment of the version.
 
         >>> print(Version("1.2.3").pre)
@@ -302,11 +519,10 @@ def pre(self) -> Optional[Tuple[str, int]]:
         >>> Version("1.2.3rc1").pre
         ('rc', 1)
         """
-        _pre: Optional[Tuple[str, int]] = self._version.pre
-        return _pre
+        return self._pre
 
     @property
-    def post(self) -> Optional[int]:
+    def post(self) -> int | None:
         """The post-release number of the version.
 
         >>> print(Version("1.2.3").post)
@@ -314,10 +530,10 @@ def post(self) -> Optional[int]:
         >>> Version("1.2.3.post1").post
         1
         """
-        return self._version.post[1] if self._version.post else None
+        return self._post[1] if self._post else None
 
     @property
-    def dev(self) -> Optional[int]:
+    def dev(self) -> int | None:
         """The development number of the version.
 
         >>> print(Version("1.2.3").dev)
@@ -325,10 +541,10 @@ def dev(self) -> Optional[int]:
         >>> Version("1.2.3.dev1").dev
         1
         """
-        return self._version.dev[1] if self._version.dev else None
+        return self._dev[1] if self._dev else None
 
     @property
-    def local(self) -> Optional[str]:
+    def local(self) -> str | None:
         """The local version segment of the version.
 
         >>> print(Version("1.2.3").local)
@@ -336,8 +552,8 @@ def local(self) -> Optional[str]:
         >>> Version("1.2.3+abc").local
         'abc'
         """
-        if self._version.local:
-            return ".".join(str(x) for x in self._version.local)
+        if self._local:
+            return ".".join(str(x) for x in self._local)
         else:
             return None
 
@@ -349,8 +565,8 @@ def public(self) -> str:
         '1.2.3'
         >>> Version("1.2.3+abc").public
         '1.2.3'
-        >>> Version("1.2.3+abc.dev1").public
-        '1.2.3'
+        >>> Version("1!1.2.3dev1+abc").public
+        '1!1.2.3.dev1'
         """
         return str(self).split("+", 1)[0]
 
@@ -362,22 +578,14 @@ def base_version(self) -> str:
         '1.2.3'
         >>> Version("1.2.3+abc").base_version
         '1.2.3'
-        >>> Version("1!1.2.3+abc.dev1").base_version
+        >>> 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.
         """
-        parts = []
-
-        # Epoch
-        if self.epoch != 0:
-            parts.append(f"{self.epoch}!")
-
-        # Release segment
-        parts.append(".".join(str(x) for x in self.release))
-
-        return "".join(parts)
+        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:
@@ -450,38 +658,60 @@ def micro(self) -> int:
         return self.release[2] if len(self.release) >= 3 else 0
 
 
-def _parse_letter_version(
-    letter: str, number: Union[str, bytes, SupportsInt]
-) -> Optional[Tuple[str, int]]:
+class _TrimmedRelease(Version):
+    __slots__ = ()
 
-    if letter:
-        # We consider there to be an implicit 0 in a pre-release if there is
-        # not a numeral associated with it.
-        if number is None:
-            number = 0
+    def __init__(self, version: str | Version) -> None:
+        if isinstance(version, Version):
+            self._epoch = version._epoch
+            self._release = version._release
+            self._dev = version._dev
+            self._pre = version._pre
+            self._post = version._post
+            self._local = version._local
+            self._key_cache = version._key_cache
+            return
+        super().__init__(version)  # pragma: no cover
+
+    @property
+    def release(self) -> tuple[int, ...]:
+        """
+        Release segment without any trailing zeros.
 
+        >>> _TrimmedRelease('1.0.0').release
+        (1,)
+        >>> _TrimmedRelease('0.0').release
+        (0,)
+        """
+        # This leaves one 0.
+        rel = super().release
+        len_release = len(rel)
+        i = len_release
+        while i > 1 and rel[i - 1] == 0:
+            i -= 1
+        return rel if i == len_release else rel[:i]
+
+
+def _parse_letter_version(
+    letter: str | None, number: str | bytes | SupportsInt | None
+) -> tuple[str, int] | None:
+    if letter:
         # We normalize any letters to their lower case form
         letter = letter.lower()
 
         # We consider some words to be alternate spellings of other words and
         # in those cases we want to normalize the spellings to our preferred
         # spelling.
-        if letter == "alpha":
-            letter = "a"
-        elif letter == "beta":
-            letter = "b"
-        elif letter in ["c", "pre", "preview"]:
-            letter = "rc"
-        elif letter in ["rev", "r"]:
-            letter = "post"
-
-        return letter, int(number)
-    if not letter and number:
+        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)
-        letter = "post"
-
-        return letter, int(number)
+        return "post", int(number)
 
     return None
 
@@ -489,7 +719,7 @@ def _parse_letter_version(
 _local_version_separators = re.compile(r"[\._-]")
 
 
-def _parse_local_version(local: str) -> Optional[LocalType]:
+def _parse_local_version(local: str | None) -> LocalType | None:
     """
     Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
     """
@@ -503,28 +733,26 @@ def _parse_local_version(local: str) -> Optional[LocalType]:
 
 def _cmpkey(
     epoch: int,
-    release: Tuple[int, ...],
-    pre: Optional[Tuple[str, int]],
-    post: Optional[Tuple[str, int]],
-    dev: Optional[Tuple[str, int]],
-    local: Optional[Tuple[SubLocalType]],
+    release: tuple[int, ...],
+    pre: tuple[str, int] | None,
+    post: tuple[str, int] | None,
+    dev: tuple[str, int] | None,
+    local: LocalType | None,
 ) -> CmpKey:
-
     # When we compare a release version, we want to compare it with all of the
-    # trailing zeros removed. So we'll use a reverse the list, drop all the now
-    # leading zeros until we come to something non zero, then take the rest
-    # re-reverse it back into the correct order and make it a tuple and use
-    # that for our sorting key.
-    _release = tuple(
-        reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
-    )
+    # trailing zeros removed. We will use this for our sorting key.
+    len_release = len(release)
+    i = len_release
+    while i and release[i - 1] == 0:
+        i -= 1
+    _release = release if i == len_release else release[:i]
 
     # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
     # We'll do this by abusing the pre segment, but we _only_ want to do this
     # if there is not a pre or a post segment. If we have one of those then
     # the normal sorting rules will handle this case correctly.
     if pre is None and post is None and dev is not None:
-        _pre: PrePostDevType = NegativeInfinity
+        _pre: CmpPrePostDevType = NegativeInfinity
     # Versions without a pre-release (except as noted above) should sort after
     # those with one.
     elif pre is None:
@@ -534,21 +762,21 @@ def _cmpkey(
 
     # Versions without a post segment should sort before those with one.
     if post is None:
-        _post: PrePostDevType = NegativeInfinity
+        _post: CmpPrePostDevType = NegativeInfinity
 
     else:
         _post = post
 
     # Versions without a development segment should sort after those with one.
     if dev is None:
-        _dev: PrePostDevType = Infinity
+        _dev: CmpPrePostDevType = Infinity
 
     else:
         _dev = dev
 
     if local is None:
         # Versions without a local segment should sort before those with one.
-        _local: LocalType = NegativeInfinity
+        _local: CmpLocalType = NegativeInfinity
     else:
         # Versions with a local segment need that segment parsed to implement
         # the sorting rules in PEP440.
diff --git a/setuptools/_vendor/platformdirs-4.4.0.dist-info/INSTALLER b/setuptools/_vendor/platformdirs-4.4.0.dist-info/INSTALLER
new file mode 100644
index 0000000000..5c69047b2e
--- /dev/null
+++ b/setuptools/_vendor/platformdirs-4.4.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/pkg_resources/_vendor/platformdirs-2.6.2.dist-info/METADATA b/setuptools/_vendor/platformdirs-4.4.0.dist-info/METADATA
similarity index 64%
rename from pkg_resources/_vendor/platformdirs-2.6.2.dist-info/METADATA
rename to setuptools/_vendor/platformdirs-4.4.0.dist-info/METADATA
index 608afde321..6b0908fb70 100644
--- a/pkg_resources/_vendor/platformdirs-2.6.2.dist-info/METADATA
+++ b/setuptools/_vendor/platformdirs-4.4.0.dist-info/METADATA
@@ -1,49 +1,57 @@
-Metadata-Version: 2.1
+Metadata-Version: 2.4
 Name: platformdirs
-Version: 2.6.2
-Summary: A small Python package for determining appropriate platform-specific dirs, e.g. a "user data dir".
+Version: 4.4.0
+Summary: A small Python package for determining appropriate platform-specific dirs, e.g. a `user data dir`.
+Project-URL: Changelog, https://github.com/tox-dev/platformdirs/releases
 Project-URL: Documentation, https://platformdirs.readthedocs.io
-Project-URL: Homepage, https://github.com/platformdirs/platformdirs
-Project-URL: Source, https://github.com/platformdirs/platformdirs
-Project-URL: Tracker, https://github.com/platformdirs/platformdirs/issues
+Project-URL: Homepage, https://github.com/tox-dev/platformdirs
+Project-URL: Source, https://github.com/tox-dev/platformdirs
+Project-URL: Tracker, https://github.com/tox-dev/platformdirs/issues
 Maintainer-email: Bernát Gábor , Julian Berman , Ofek Lev , Ronny Pfannschmidt 
+License-Expression: MIT
 License-File: LICENSE
-Keywords: application,cache,directory,log,user
+Keywords: appdirs,application,cache,directory,log,user
 Classifier: Development Status :: 5 - Production/Stable
 Classifier: Intended Audience :: Developers
 Classifier: License :: OSI Approved :: MIT License
 Classifier: Operating System :: OS Independent
 Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 3
 Classifier: Programming Language :: Python :: 3 :: Only
-Classifier: Programming Language :: Python :: 3.7
-Classifier: Programming Language :: Python :: 3.8
 Classifier: Programming Language :: Python :: 3.9
 Classifier: Programming Language :: Python :: 3.10
 Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
 Classifier: Programming Language :: Python :: Implementation :: CPython
 Classifier: Programming Language :: Python :: Implementation :: PyPy
 Classifier: Topic :: Software Development :: Libraries :: Python Modules
-Requires-Python: >=3.7
-Requires-Dist: typing-extensions>=4.4; python_version < '3.8'
+Requires-Python: >=3.9
 Provides-Extra: docs
-Requires-Dist: furo>=2022.12.7; extra == 'docs'
-Requires-Dist: proselint>=0.13; extra == 'docs'
-Requires-Dist: sphinx-autodoc-typehints>=1.19.5; extra == 'docs'
-Requires-Dist: sphinx>=5.3; extra == 'docs'
+Requires-Dist: furo>=2024.8.6; extra == 'docs'
+Requires-Dist: proselint>=0.14; extra == 'docs'
+Requires-Dist: sphinx-autodoc-typehints>=3; extra == 'docs'
+Requires-Dist: sphinx>=8.1.3; extra == 'docs'
 Provides-Extra: test
 Requires-Dist: appdirs==1.4.4; extra == 'test'
-Requires-Dist: covdefaults>=2.2.2; extra == 'test'
-Requires-Dist: pytest-cov>=4; extra == 'test'
-Requires-Dist: pytest-mock>=3.10; extra == 'test'
-Requires-Dist: pytest>=7.2; extra == 'test'
+Requires-Dist: covdefaults>=2.3; extra == 'test'
+Requires-Dist: pytest-cov>=6; extra == 'test'
+Requires-Dist: pytest-mock>=3.14; extra == 'test'
+Requires-Dist: pytest>=8.3.4; extra == 'test'
+Provides-Extra: type
+Requires-Dist: mypy>=1.14.1; extra == 'type'
 Description-Content-Type: text/x-rst
 
 The problem
 ===========
 
-.. image:: https://github.com/platformdirs/platformdirs/workflows/Test/badge.svg
-   :target: https://github.com/platformdirs/platformdirs/actions?query=workflow%3ATest
+.. image:: https://badge.fury.io/py/platformdirs.svg
+   :target: https://badge.fury.io/py/platformdirs
+.. image:: https://img.shields.io/pypi/pyversions/platformdirs.svg
+   :target: https://pypi.python.org/pypi/platformdirs/
+.. image:: https://github.com/tox-dev/platformdirs/actions/workflows/check.yaml/badge.svg
+   :target: https://github.com/platformdirs/platformdirs/actions
+.. image:: https://static.pepy.tech/badge/platformdirs/month
+   :target: https://pepy.tech/project/platformdirs
 
 When writing desktop application, finding the right location to store user data
 and configuration varies per platform. Even for single-platform apps, there
@@ -53,7 +61,7 @@ For example, if running on macOS, you should use::
 
     ~/Library/Application Support/
 
-If on Windows (at least English Win XP) that should be::
+If on Windows (at least English Win) that should be::
 
     C:\Documents and Settings\\Application Data\Local Settings\\
 
@@ -82,6 +90,11 @@ This kind of thing is what the ``platformdirs`` package is for.
 - site config dir (``site_config_dir``)
 - user log dir (``user_log_dir``)
 - user documents dir (``user_documents_dir``)
+- user downloads dir (``user_downloads_dir``)
+- user pictures dir (``user_pictures_dir``)
+- user videos dir (``user_videos_dir``)
+- user music dir (``user_music_dir``)
+- user desktop dir (``user_desktop_dir``)
 - user runtime dir (``user_runtime_dir``)
 
 And also:
@@ -101,18 +114,32 @@ On macOS:
     >>> appauthor = "Acme"
     >>> user_data_dir(appname, appauthor)
     '/Users/trentm/Library/Application Support/SuperApp'
-    >>> site_data_dir(appname, appauthor)
-    '/Library/Application Support/SuperApp'
+    >>> user_config_dir(appname, appauthor)
+    '/Users/trentm/Library/Application Support/SuperApp'
     >>> user_cache_dir(appname, appauthor)
     '/Users/trentm/Library/Caches/SuperApp'
+    >>> site_data_dir(appname, appauthor)
+    '/Library/Application Support/SuperApp'
+    >>> site_config_dir(appname, appauthor)
+    '/Library/Application Support/SuperApp'
     >>> user_log_dir(appname, appauthor)
     '/Users/trentm/Library/Logs/SuperApp'
     >>> user_documents_dir()
     '/Users/trentm/Documents'
+    >>> user_downloads_dir()
+    '/Users/trentm/Downloads'
+    >>> user_pictures_dir()
+    '/Users/trentm/Pictures'
+    >>> user_videos_dir()
+    '/Users/trentm/Movies'
+    >>> user_music_dir()
+    '/Users/trentm/Music'
+    >>> user_desktop_dir()
+    '/Users/trentm/Desktop'
     >>> user_runtime_dir(appname, appauthor)
     '/Users/trentm/Library/Caches/TemporaryItems/SuperApp'
 
-On Windows 7:
+On Windows:
 
 .. code-block:: pycon
 
@@ -123,12 +150,28 @@ On Windows 7:
     'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp'
     >>> user_data_dir(appname, appauthor, roaming=True)
     'C:\\Users\\trentm\\AppData\\Roaming\\Acme\\SuperApp'
+    >>> user_config_dir(appname, appauthor)
+    'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp'
     >>> user_cache_dir(appname, appauthor)
     'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Cache'
+    >>> site_data_dir(appname, appauthor)
+    'C:\\ProgramData\\Acme\\SuperApp'
+    >>> site_config_dir(appname, appauthor)
+    'C:\\ProgramData\\Acme\\SuperApp'
     >>> user_log_dir(appname, appauthor)
     'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Logs'
     >>> user_documents_dir()
     'C:\\Users\\trentm\\Documents'
+    >>> user_downloads_dir()
+    'C:\\Users\\trentm\\Downloads'
+    >>> user_pictures_dir()
+    'C:\\Users\\trentm\\Pictures'
+    >>> user_videos_dir()
+    'C:\\Users\\trentm\\Videos'
+    >>> user_music_dir()
+    'C:\\Users\\trentm\\Music'
+    >>> user_desktop_dir()
+    'C:\\Users\\trentm\\Desktop'
     >>> user_runtime_dir(appname, appauthor)
     'C:\\Users\\trentm\\AppData\\Local\\Temp\\Acme\\SuperApp'
 
@@ -141,25 +184,35 @@ On Linux:
     >>> appauthor = "Acme"
     >>> user_data_dir(appname, appauthor)
     '/home/trentm/.local/share/SuperApp'
+    >>> user_config_dir(appname)
+    '/home/trentm/.config/SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    '/home/trentm/.cache/SuperApp'
     >>> site_data_dir(appname, appauthor)
     '/usr/local/share/SuperApp'
     >>> site_data_dir(appname, appauthor, multipath=True)
     '/usr/local/share/SuperApp:/usr/share/SuperApp'
-    >>> user_cache_dir(appname, appauthor)
-    '/home/trentm/.cache/SuperApp'
-    >>> user_log_dir(appname, appauthor)
-    '/home/trentm/.cache/SuperApp/log'
-    >>> user_config_dir(appname)
-    '/home/trentm/.config/SuperApp'
-    >>> user_documents_dir()
-    '/home/trentm/Documents'
-    >>> user_runtime_dir(appname, appauthor)
-    '/run/user/{os.getuid()}/SuperApp'
     >>> site_config_dir(appname)
     '/etc/xdg/SuperApp'
     >>> os.environ["XDG_CONFIG_DIRS"] = "/etc:/usr/local/etc"
     >>> site_config_dir(appname, multipath=True)
     '/etc/SuperApp:/usr/local/etc/SuperApp'
+    >>> user_log_dir(appname, appauthor)
+    '/home/trentm/.local/state/SuperApp/log'
+    >>> user_documents_dir()
+    '/home/trentm/Documents'
+    >>> user_downloads_dir()
+    '/home/trentm/Downloads'
+    >>> user_pictures_dir()
+    '/home/trentm/Pictures'
+    >>> user_videos_dir()
+    '/home/trentm/Videos'
+    >>> user_music_dir()
+    '/home/trentm/Music'
+    >>> user_desktop_dir()
+    '/home/trentm/Desktop'
+    >>> user_runtime_dir(appname, appauthor)
+    '/run/user/{os.getuid()}/SuperApp'
 
 On Android::
 
@@ -168,14 +221,28 @@ On Android::
     >>> appauthor = "Acme"
     >>> user_data_dir(appname, appauthor)
     '/data/data/com.myApp/files/SuperApp'
+    >>> user_config_dir(appname)
+    '/data/data/com.myApp/shared_prefs/SuperApp'
     >>> user_cache_dir(appname, appauthor)
     '/data/data/com.myApp/cache/SuperApp'
+    >>> site_data_dir(appname, appauthor)
+    '/data/data/com.myApp/files/SuperApp'
+    >>> site_config_dir(appname)
+    '/data/data/com.myApp/shared_prefs/SuperApp'
     >>> user_log_dir(appname, appauthor)
     '/data/data/com.myApp/cache/SuperApp/log'
-    >>> user_config_dir(appname)
-    '/data/data/com.myApp/shared_prefs/SuperApp'
     >>> user_documents_dir()
     '/storage/emulated/0/Documents'
+    >>> user_downloads_dir()
+    '/storage/emulated/0/Downloads'
+    >>> user_pictures_dir()
+    '/storage/emulated/0/Pictures'
+    >>> user_videos_dir()
+    '/storage/emulated/0/DCIM/Camera'
+    >>> user_music_dir()
+    '/storage/emulated/0/Music'
+    >>> user_desktop_dir()
+    '/storage/emulated/0/Desktop'
     >>> user_runtime_dir(appname, appauthor)
     '/data/data/com.myApp/cache/SuperApp/tmp'
 
@@ -195,14 +262,30 @@ apps also support ``XDG_*`` environment variables.
     >>> dirs = PlatformDirs("SuperApp", "Acme")
     >>> dirs.user_data_dir
     '/Users/trentm/Library/Application Support/SuperApp'
+    >>> dirs.user_config_dir
+    '/Users/trentm/Library/Application Support/SuperApp'
+    >>> dirs.user_cache_dir
+    '/Users/trentm/Library/Caches/SuperApp'
     >>> dirs.site_data_dir
     '/Library/Application Support/SuperApp'
+    >>> dirs.site_config_dir
+    '/Library/Application Support/SuperApp'
     >>> dirs.user_cache_dir
     '/Users/trentm/Library/Caches/SuperApp'
     >>> dirs.user_log_dir
     '/Users/trentm/Library/Logs/SuperApp'
     >>> dirs.user_documents_dir
     '/Users/trentm/Documents'
+    >>> dirs.user_downloads_dir
+    '/Users/trentm/Downloads'
+    >>> dirs.user_pictures_dir
+    '/Users/trentm/Pictures'
+    >>> dirs.user_videos_dir
+    '/Users/trentm/Movies'
+    >>> dirs.user_music_dir
+    '/Users/trentm/Music'
+    >>> dirs.user_desktop_dir
+    '/Users/trentm/Desktop'
     >>> dirs.user_runtime_dir
     '/Users/trentm/Library/Caches/TemporaryItems/SuperApp'
 
@@ -217,14 +300,28 @@ dirs::
     >>> dirs = PlatformDirs("SuperApp", "Acme", version="1.0")
     >>> dirs.user_data_dir
     '/Users/trentm/Library/Application Support/SuperApp/1.0'
-    >>> dirs.site_data_dir
-    '/Library/Application Support/SuperApp/1.0'
+    >>> dirs.user_config_dir
+    '/Users/trentm/Library/Application Support/SuperApp/1.0'
     >>> dirs.user_cache_dir
     '/Users/trentm/Library/Caches/SuperApp/1.0'
+    >>> dirs.site_data_dir
+    '/Library/Application Support/SuperApp/1.0'
+    >>> dirs.site_config_dir
+    '/Library/Application Support/SuperApp/1.0'
     >>> dirs.user_log_dir
     '/Users/trentm/Library/Logs/SuperApp/1.0'
     >>> dirs.user_documents_dir
     '/Users/trentm/Documents'
+    >>> dirs.user_downloads_dir
+    '/Users/trentm/Downloads'
+    >>> dirs.user_pictures_dir
+    '/Users/trentm/Pictures'
+    >>> dirs.user_videos_dir
+    '/Users/trentm/Movies'
+    >>> dirs.user_music_dir
+    '/Users/trentm/Music'
+    >>> dirs.user_desktop_dir
+    '/Users/trentm/Desktop'
     >>> dirs.user_runtime_dir
     '/Users/trentm/Library/Caches/TemporaryItems/SuperApp/1.0'
 
diff --git a/setuptools/_vendor/platformdirs-4.4.0.dist-info/RECORD b/setuptools/_vendor/platformdirs-4.4.0.dist-info/RECORD
new file mode 100644
index 0000000000..09572f1780
--- /dev/null
+++ b/setuptools/_vendor/platformdirs-4.4.0.dist-info/RECORD
@@ -0,0 +1,15 @@
+platformdirs-4.4.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+platformdirs-4.4.0.dist-info/METADATA,sha256=u8UhbV9Md7-8VyJyZNUuZrzN5xzPeedeGmBG0CnTAiM,12831
+platformdirs-4.4.0.dist-info/RECORD,,
+platformdirs-4.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+platformdirs-4.4.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
+platformdirs-4.4.0.dist-info/licenses/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089
+platformdirs/__init__.py,sha256=iORRy6_lZ9tXLvO0W6fJPn8QV7F532ivl-f2WGmabBc,22284
+platformdirs/__main__.py,sha256=HnsUQHpiBaiTxwcmwVw-nFaPdVNZtQIdi1eWDtI-MzI,1493
+platformdirs/android.py,sha256=r0DshVBf-RO1jXJGX8C4Til7F1XWt-bkdWMgmvEiaYg,9013
+platformdirs/api.py,sha256=wPHOlwOsfz2oqQZ6A2FcCu5kEAj-JondzoNOHYFQ0h8,9281
+platformdirs/macos.py,sha256=0XoOgin1NK7Qki7iskD-oS8xKxw6bXgoKEgdqpCRAFQ,6322
+platformdirs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+platformdirs/unix.py,sha256=WZmkUA--L3JNRGmz32s35YfoD3ica6xKIPdCV_HhLcs,10458
+platformdirs/version.py,sha256=i31fi3nNO19D2FdSx8aldD7IFLSqm2YrAo6SmkV0FLM,704
+platformdirs/windows.py,sha256=IFpiohUBwxPtCzlyKwNtxyW4Jk8haa6W8o59mfrDXVo,10125
diff --git a/setuptools/_vendor/more_itertools-8.8.0.dist-info/REQUESTED b/setuptools/_vendor/platformdirs-4.4.0.dist-info/REQUESTED
similarity index 100%
rename from setuptools/_vendor/more_itertools-8.8.0.dist-info/REQUESTED
rename to setuptools/_vendor/platformdirs-4.4.0.dist-info/REQUESTED
diff --git a/pkg_resources/_vendor/platformdirs-2.6.2.dist-info/WHEEL b/setuptools/_vendor/platformdirs-4.4.0.dist-info/WHEEL
similarity index 67%
rename from pkg_resources/_vendor/platformdirs-2.6.2.dist-info/WHEEL
rename to setuptools/_vendor/platformdirs-4.4.0.dist-info/WHEEL
index 6d803659b7..12228d414b 100644
--- a/pkg_resources/_vendor/platformdirs-2.6.2.dist-info/WHEEL
+++ b/setuptools/_vendor/platformdirs-4.4.0.dist-info/WHEEL
@@ -1,4 +1,4 @@
 Wheel-Version: 1.0
-Generator: hatchling 1.11.1
+Generator: hatchling 1.27.0
 Root-Is-Purelib: true
 Tag: py3-none-any
diff --git a/pkg_resources/_vendor/platformdirs-2.6.2.dist-info/licenses/LICENSE b/setuptools/_vendor/platformdirs-4.4.0.dist-info/licenses/LICENSE
similarity index 100%
rename from pkg_resources/_vendor/platformdirs-2.6.2.dist-info/licenses/LICENSE
rename to setuptools/_vendor/platformdirs-4.4.0.dist-info/licenses/LICENSE
diff --git a/setuptools/_vendor/platformdirs/__init__.py b/setuptools/_vendor/platformdirs/__init__.py
new file mode 100644
index 0000000000..02daa5914a
--- /dev/null
+++ b/setuptools/_vendor/platformdirs/__init__.py
@@ -0,0 +1,631 @@
+"""
+Utilities for determining application-specific dirs.
+
+See  for details and usage.
+
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+from typing import TYPE_CHECKING
+
+from .api import PlatformDirsABC
+from .version import __version__
+from .version import __version_tuple__ as __version_info__
+
+if TYPE_CHECKING:
+    from pathlib import Path
+    from typing import Literal
+
+if sys.platform == "win32":
+    from platformdirs.windows import Windows as _Result
+elif sys.platform == "darwin":
+    from platformdirs.macos import MacOS as _Result
+else:
+    from platformdirs.unix import Unix as _Result
+
+
+def _set_platform_dir_class() -> type[PlatformDirsABC]:
+    if os.getenv("ANDROID_DATA") == "/data" and os.getenv("ANDROID_ROOT") == "/system":
+        if os.getenv("SHELL") or os.getenv("PREFIX"):
+            return _Result
+
+        from platformdirs.android import _android_folder  # noqa: PLC0415
+
+        if _android_folder() is not None:
+            from platformdirs.android import Android  # noqa: PLC0415
+
+            return Android  # return to avoid redefinition of a result
+
+    return _Result
+
+
+if TYPE_CHECKING:
+    # Work around mypy issue: https://github.com/python/mypy/issues/10962
+    PlatformDirs = _Result
+else:
+    PlatformDirs = _set_platform_dir_class()  #: Currently active platform
+AppDirs = PlatformDirs  #: Backwards compatibility with appdirs
+
+
+def user_data_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: data directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_data_dir
+
+
+def site_data_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param multipath: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: data directory shared by users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_data_dir
+
+
+def user_config_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: config directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_config_dir
+
+
+def site_config_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param multipath: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: config directory shared by the users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_config_dir
+
+
+def user_cache_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: cache directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_cache_dir
+
+
+def site_cache_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: cache directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_cache_dir
+
+
+def user_state_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: state directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_state_dir
+
+
+def user_log_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: log directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_log_dir
+
+
+def user_documents_dir() -> str:
+    """:returns: documents directory tied to the user"""
+    return PlatformDirs().user_documents_dir
+
+
+def user_downloads_dir() -> str:
+    """:returns: downloads directory tied to the user"""
+    return PlatformDirs().user_downloads_dir
+
+
+def user_pictures_dir() -> str:
+    """:returns: pictures directory tied to the user"""
+    return PlatformDirs().user_pictures_dir
+
+
+def user_videos_dir() -> str:
+    """:returns: videos directory tied to the user"""
+    return PlatformDirs().user_videos_dir
+
+
+def user_music_dir() -> str:
+    """:returns: music directory tied to the user"""
+    return PlatformDirs().user_music_dir
+
+
+def user_desktop_dir() -> str:
+    """:returns: desktop directory tied to the user"""
+    return PlatformDirs().user_desktop_dir
+
+
+def user_runtime_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: runtime directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_runtime_dir
+
+
+def site_runtime_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: runtime directory shared by users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_runtime_dir
+
+
+def user_data_path(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: data path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_data_path
+
+
+def site_data_path(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param multipath: See `multipath `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: data path shared by users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_data_path
+
+
+def user_config_path(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: config path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_config_path
+
+
+def site_config_path(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param multipath: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: config path shared by the users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_config_path
+
+
+def site_cache_path(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: cache directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_cache_path
+
+
+def user_cache_path(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: cache path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_cache_path
+
+
+def user_state_path(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: state path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_state_path
+
+
+def user_log_path(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: log path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_log_path
+
+
+def user_documents_path() -> Path:
+    """:returns: documents a path tied to the user"""
+    return PlatformDirs().user_documents_path
+
+
+def user_downloads_path() -> Path:
+    """:returns: downloads path tied to the user"""
+    return PlatformDirs().user_downloads_path
+
+
+def user_pictures_path() -> Path:
+    """:returns: pictures path tied to the user"""
+    return PlatformDirs().user_pictures_path
+
+
+def user_videos_path() -> Path:
+    """:returns: videos path tied to the user"""
+    return PlatformDirs().user_videos_path
+
+
+def user_music_path() -> Path:
+    """:returns: music path tied to the user"""
+    return PlatformDirs().user_music_path
+
+
+def user_desktop_path() -> Path:
+    """:returns: desktop path tied to the user"""
+    return PlatformDirs().user_desktop_path
+
+
+def user_runtime_path(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: runtime path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_runtime_path
+
+
+def site_runtime_path(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: runtime path shared by users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_runtime_path
+
+
+__all__ = [
+    "AppDirs",
+    "PlatformDirs",
+    "PlatformDirsABC",
+    "__version__",
+    "__version_info__",
+    "site_cache_dir",
+    "site_cache_path",
+    "site_config_dir",
+    "site_config_path",
+    "site_data_dir",
+    "site_data_path",
+    "site_runtime_dir",
+    "site_runtime_path",
+    "user_cache_dir",
+    "user_cache_path",
+    "user_config_dir",
+    "user_config_path",
+    "user_data_dir",
+    "user_data_path",
+    "user_desktop_dir",
+    "user_desktop_path",
+    "user_documents_dir",
+    "user_documents_path",
+    "user_downloads_dir",
+    "user_downloads_path",
+    "user_log_dir",
+    "user_log_path",
+    "user_music_dir",
+    "user_music_path",
+    "user_pictures_dir",
+    "user_pictures_path",
+    "user_runtime_dir",
+    "user_runtime_path",
+    "user_state_dir",
+    "user_state_path",
+    "user_videos_dir",
+    "user_videos_path",
+]
diff --git a/setuptools/_vendor/platformdirs/__main__.py b/setuptools/_vendor/platformdirs/__main__.py
new file mode 100644
index 0000000000..922c521358
--- /dev/null
+++ b/setuptools/_vendor/platformdirs/__main__.py
@@ -0,0 +1,55 @@
+"""Main entry point."""
+
+from __future__ import annotations
+
+from platformdirs import PlatformDirs, __version__
+
+PROPS = (
+    "user_data_dir",
+    "user_config_dir",
+    "user_cache_dir",
+    "user_state_dir",
+    "user_log_dir",
+    "user_documents_dir",
+    "user_downloads_dir",
+    "user_pictures_dir",
+    "user_videos_dir",
+    "user_music_dir",
+    "user_runtime_dir",
+    "site_data_dir",
+    "site_config_dir",
+    "site_cache_dir",
+    "site_runtime_dir",
+)
+
+
+def main() -> None:
+    """Run the main entry point."""
+    app_name = "MyApp"
+    app_author = "MyCompany"
+
+    print(f"-- platformdirs {__version__} --")  # noqa: T201
+
+    print("-- app dirs (with optional 'version')")  # noqa: T201
+    dirs = PlatformDirs(app_name, app_author, version="1.0")
+    for prop in PROPS:
+        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
+
+    print("\n-- app dirs (without optional 'version')")  # noqa: T201
+    dirs = PlatformDirs(app_name, app_author)
+    for prop in PROPS:
+        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
+
+    print("\n-- app dirs (without optional 'appauthor')")  # noqa: T201
+    dirs = PlatformDirs(app_name)
+    for prop in PROPS:
+        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
+
+    print("\n-- app dirs (with disabled 'appauthor')")  # noqa: T201
+    dirs = PlatformDirs(app_name, appauthor=False)
+    for prop in PROPS:
+        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
+
+
+if __name__ == "__main__":
+    main()
diff --git a/setuptools/_vendor/platformdirs/android.py b/setuptools/_vendor/platformdirs/android.py
new file mode 100644
index 0000000000..92efc852d3
--- /dev/null
+++ b/setuptools/_vendor/platformdirs/android.py
@@ -0,0 +1,249 @@
+"""Android."""
+
+from __future__ import annotations
+
+import os
+import re
+import sys
+from functools import lru_cache
+from typing import TYPE_CHECKING, cast
+
+from .api import PlatformDirsABC
+
+
+class Android(PlatformDirsABC):
+    """
+    Follows the guidance `from here `_.
+
+    Makes use of the `appname `, `version
+    `, `ensure_exists `.
+
+    """
+
+    @property
+    def user_data_dir(self) -> str:
+        """:return: data directory tied to the user, e.g. ``/data/user///files/``"""
+        return self._append_app_name_and_version(cast("str", _android_folder()), "files")
+
+    @property
+    def site_data_dir(self) -> str:
+        """:return: data directory shared by users, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def user_config_dir(self) -> str:
+        """
+        :return: config directory tied to the user, e.g. \
+        ``/data/user///shared_prefs/``
+        """
+        return self._append_app_name_and_version(cast("str", _android_folder()), "shared_prefs")
+
+    @property
+    def site_config_dir(self) -> str:
+        """:return: config directory shared by the users, same as `user_config_dir`"""
+        return self.user_config_dir
+
+    @property
+    def user_cache_dir(self) -> str:
+        """:return: cache directory tied to the user, e.g.,``/data/user///cache/``"""
+        return self._append_app_name_and_version(cast("str", _android_folder()), "cache")
+
+    @property
+    def site_cache_dir(self) -> str:
+        """:return: cache directory shared by users, same as `user_cache_dir`"""
+        return self.user_cache_dir
+
+    @property
+    def user_state_dir(self) -> str:
+        """:return: state directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def user_log_dir(self) -> str:
+        """
+        :return: log directory tied to the user, same as `user_cache_dir` if not opinionated else ``log`` in it,
+          e.g. ``/data/user///cache//log``
+        """
+        path = self.user_cache_dir
+        if self.opinion:
+            path = os.path.join(path, "log")  # noqa: PTH118
+        return path
+
+    @property
+    def user_documents_dir(self) -> str:
+        """:return: documents directory tied to the user e.g. ``/storage/emulated/0/Documents``"""
+        return _android_documents_folder()
+
+    @property
+    def user_downloads_dir(self) -> str:
+        """:return: downloads directory tied to the user e.g. ``/storage/emulated/0/Downloads``"""
+        return _android_downloads_folder()
+
+    @property
+    def user_pictures_dir(self) -> str:
+        """:return: pictures directory tied to the user e.g. ``/storage/emulated/0/Pictures``"""
+        return _android_pictures_folder()
+
+    @property
+    def user_videos_dir(self) -> str:
+        """:return: videos directory tied to the user e.g. ``/storage/emulated/0/DCIM/Camera``"""
+        return _android_videos_folder()
+
+    @property
+    def user_music_dir(self) -> str:
+        """:return: music directory tied to the user e.g. ``/storage/emulated/0/Music``"""
+        return _android_music_folder()
+
+    @property
+    def user_desktop_dir(self) -> str:
+        """:return: desktop directory tied to the user e.g. ``/storage/emulated/0/Desktop``"""
+        return "/storage/emulated/0/Desktop"
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """
+        :return: runtime directory tied to the user, same as `user_cache_dir` if not opinionated else ``tmp`` in it,
+          e.g. ``/data/user///cache//tmp``
+        """
+        path = self.user_cache_dir
+        if self.opinion:
+            path = os.path.join(path, "tmp")  # noqa: PTH118
+        return path
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """:return: runtime directory shared by users, same as `user_runtime_dir`"""
+        return self.user_runtime_dir
+
+
+@lru_cache(maxsize=1)
+def _android_folder() -> str | None:  # noqa: C901
+    """:return: base folder for the Android OS or None if it cannot be found"""
+    result: str | None = None
+    # type checker isn't happy with our "import android", just don't do this when type checking see
+    # https://stackoverflow.com/a/61394121
+    if not TYPE_CHECKING:
+        try:
+            # First try to get a path to android app using python4android (if available)...
+            from android import mActivity  # noqa: PLC0415
+
+            context = cast("android.content.Context", mActivity.getApplicationContext())  # noqa: F821
+            result = context.getFilesDir().getParentFile().getAbsolutePath()
+        except Exception:  # noqa: BLE001
+            result = None
+    if result is None:
+        try:
+            # ...and fall back to using plain pyjnius, if python4android isn't available or doesn't deliver any useful
+            # result...
+            from jnius import autoclass  # noqa: PLC0415
+
+            context = autoclass("android.content.Context")
+            result = context.getFilesDir().getParentFile().getAbsolutePath()
+        except Exception:  # noqa: BLE001
+            result = None
+    if result is None:
+        # and if that fails, too, find an android folder looking at path on the sys.path
+        # warning: only works for apps installed under /data, not adopted storage etc.
+        pattern = re.compile(r"/data/(data|user/\d+)/(.+)/files")
+        for path in sys.path:
+            if pattern.match(path):
+                result = path.split("/files")[0]
+                break
+        else:
+            result = None
+    if result is None:
+        # one last try: find an android folder looking at path on the sys.path taking adopted storage paths into
+        # account
+        pattern = re.compile(r"/mnt/expand/[a-fA-F0-9-]{36}/(data|user/\d+)/(.+)/files")
+        for path in sys.path:
+            if pattern.match(path):
+                result = path.split("/files")[0]
+                break
+        else:
+            result = None
+    return result
+
+
+@lru_cache(maxsize=1)
+def _android_documents_folder() -> str:
+    """:return: documents folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        documents_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DOCUMENTS).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        documents_dir = "/storage/emulated/0/Documents"
+
+    return documents_dir
+
+
+@lru_cache(maxsize=1)
+def _android_downloads_folder() -> str:
+    """:return: downloads folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        downloads_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        downloads_dir = "/storage/emulated/0/Downloads"
+
+    return downloads_dir
+
+
+@lru_cache(maxsize=1)
+def _android_pictures_folder() -> str:
+    """:return: pictures folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        pictures_dir: str = context.getExternalFilesDir(environment.DIRECTORY_PICTURES).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        pictures_dir = "/storage/emulated/0/Pictures"
+
+    return pictures_dir
+
+
+@lru_cache(maxsize=1)
+def _android_videos_folder() -> str:
+    """:return: videos folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        videos_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DCIM).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        videos_dir = "/storage/emulated/0/DCIM/Camera"
+
+    return videos_dir
+
+
+@lru_cache(maxsize=1)
+def _android_music_folder() -> str:
+    """:return: music folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        music_dir: str = context.getExternalFilesDir(environment.DIRECTORY_MUSIC).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        music_dir = "/storage/emulated/0/Music"
+
+    return music_dir
+
+
+__all__ = [
+    "Android",
+]
diff --git a/setuptools/_vendor/platformdirs/api.py b/setuptools/_vendor/platformdirs/api.py
new file mode 100644
index 0000000000..251600e6d1
--- /dev/null
+++ b/setuptools/_vendor/platformdirs/api.py
@@ -0,0 +1,299 @@
+"""Base API."""
+
+from __future__ import annotations
+
+import os
+from abc import ABC, abstractmethod
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import Iterator
+    from typing import Literal
+
+
+class PlatformDirsABC(ABC):  # noqa: PLR0904
+    """Abstract base class for platform directories."""
+
+    def __init__(  # noqa: PLR0913, PLR0917
+        self,
+        appname: str | None = None,
+        appauthor: str | Literal[False] | None = None,
+        version: str | None = None,
+        roaming: bool = False,  # noqa: FBT001, FBT002
+        multipath: bool = False,  # noqa: FBT001, FBT002
+        opinion: bool = True,  # noqa: FBT001, FBT002
+        ensure_exists: bool = False,  # noqa: FBT001, FBT002
+    ) -> None:
+        """
+        Create a new platform directory.
+
+        :param appname: See `appname`.
+        :param appauthor: See `appauthor`.
+        :param version: See `version`.
+        :param roaming: See `roaming`.
+        :param multipath: See `multipath`.
+        :param opinion: See `opinion`.
+        :param ensure_exists: See `ensure_exists`.
+
+        """
+        self.appname = appname  #: The name of application.
+        self.appauthor = appauthor
+        """
+        The name of the app author or distributing body for this application.
+
+        Typically, it is the owning company name. Defaults to `appname`. You may pass ``False`` to disable it.
+
+        """
+        self.version = version
+        """
+        An optional version path element to append to the path.
+
+        You might want to use this if you want multiple versions of your app to be able to run independently. If used,
+        this would typically be ``.``.
+
+        """
+        self.roaming = roaming
+        """
+        Whether to use the roaming appdata directory on Windows.
+
+        That means that for users on a Windows network setup for roaming profiles, this user data will be synced on
+        login (see
+        `here `_).
+
+        """
+        self.multipath = multipath
+        """
+        An optional parameter which indicates that the entire list of data dirs should be returned.
+
+        By default, the first item would only be returned.
+
+        """
+        self.opinion = opinion  #: A flag to indicating to use opinionated values.
+        self.ensure_exists = ensure_exists
+        """
+        Optionally create the directory (and any missing parents) upon access if it does not exist.
+
+        By default, no directories are created.
+
+        """
+
+    def _append_app_name_and_version(self, *base: str) -> str:
+        params = list(base[1:])
+        if self.appname:
+            params.append(self.appname)
+            if self.version:
+                params.append(self.version)
+        path = os.path.join(base[0], *params)  # noqa: PTH118
+        self._optionally_create_directory(path)
+        return path
+
+    def _optionally_create_directory(self, path: str) -> None:
+        if self.ensure_exists:
+            Path(path).mkdir(parents=True, exist_ok=True)
+
+    def _first_item_as_path_if_multipath(self, directory: str) -> Path:
+        if self.multipath:
+            # If multipath is True, the first path is returned.
+            directory = directory.partition(os.pathsep)[0]
+        return Path(directory)
+
+    @property
+    @abstractmethod
+    def user_data_dir(self) -> str:
+        """:return: data directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_data_dir(self) -> str:
+        """:return: data directory shared by users"""
+
+    @property
+    @abstractmethod
+    def user_config_dir(self) -> str:
+        """:return: config directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_config_dir(self) -> str:
+        """:return: config directory shared by the users"""
+
+    @property
+    @abstractmethod
+    def user_cache_dir(self) -> str:
+        """:return: cache directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_cache_dir(self) -> str:
+        """:return: cache directory shared by users"""
+
+    @property
+    @abstractmethod
+    def user_state_dir(self) -> str:
+        """:return: state directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_log_dir(self) -> str:
+        """:return: log directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_documents_dir(self) -> str:
+        """:return: documents directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_downloads_dir(self) -> str:
+        """:return: downloads directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_pictures_dir(self) -> str:
+        """:return: pictures directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_videos_dir(self) -> str:
+        """:return: videos directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_music_dir(self) -> str:
+        """:return: music directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_desktop_dir(self) -> str:
+        """:return: desktop directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_runtime_dir(self) -> str:
+        """:return: runtime directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_runtime_dir(self) -> str:
+        """:return: runtime directory shared by users"""
+
+    @property
+    def user_data_path(self) -> Path:
+        """:return: data path tied to the user"""
+        return Path(self.user_data_dir)
+
+    @property
+    def site_data_path(self) -> Path:
+        """:return: data path shared by users"""
+        return Path(self.site_data_dir)
+
+    @property
+    def user_config_path(self) -> Path:
+        """:return: config path tied to the user"""
+        return Path(self.user_config_dir)
+
+    @property
+    def site_config_path(self) -> Path:
+        """:return: config path shared by the users"""
+        return Path(self.site_config_dir)
+
+    @property
+    def user_cache_path(self) -> Path:
+        """:return: cache path tied to the user"""
+        return Path(self.user_cache_dir)
+
+    @property
+    def site_cache_path(self) -> Path:
+        """:return: cache path shared by users"""
+        return Path(self.site_cache_dir)
+
+    @property
+    def user_state_path(self) -> Path:
+        """:return: state path tied to the user"""
+        return Path(self.user_state_dir)
+
+    @property
+    def user_log_path(self) -> Path:
+        """:return: log path tied to the user"""
+        return Path(self.user_log_dir)
+
+    @property
+    def user_documents_path(self) -> Path:
+        """:return: documents a path tied to the user"""
+        return Path(self.user_documents_dir)
+
+    @property
+    def user_downloads_path(self) -> Path:
+        """:return: downloads path tied to the user"""
+        return Path(self.user_downloads_dir)
+
+    @property
+    def user_pictures_path(self) -> Path:
+        """:return: pictures path tied to the user"""
+        return Path(self.user_pictures_dir)
+
+    @property
+    def user_videos_path(self) -> Path:
+        """:return: videos path tied to the user"""
+        return Path(self.user_videos_dir)
+
+    @property
+    def user_music_path(self) -> Path:
+        """:return: music path tied to the user"""
+        return Path(self.user_music_dir)
+
+    @property
+    def user_desktop_path(self) -> Path:
+        """:return: desktop path tied to the user"""
+        return Path(self.user_desktop_dir)
+
+    @property
+    def user_runtime_path(self) -> Path:
+        """:return: runtime path tied to the user"""
+        return Path(self.user_runtime_dir)
+
+    @property
+    def site_runtime_path(self) -> Path:
+        """:return: runtime path shared by users"""
+        return Path(self.site_runtime_dir)
+
+    def iter_config_dirs(self) -> Iterator[str]:
+        """:yield: all user and site configuration directories."""
+        yield self.user_config_dir
+        yield self.site_config_dir
+
+    def iter_data_dirs(self) -> Iterator[str]:
+        """:yield: all user and site data directories."""
+        yield self.user_data_dir
+        yield self.site_data_dir
+
+    def iter_cache_dirs(self) -> Iterator[str]:
+        """:yield: all user and site cache directories."""
+        yield self.user_cache_dir
+        yield self.site_cache_dir
+
+    def iter_runtime_dirs(self) -> Iterator[str]:
+        """:yield: all user and site runtime directories."""
+        yield self.user_runtime_dir
+        yield self.site_runtime_dir
+
+    def iter_config_paths(self) -> Iterator[Path]:
+        """:yield: all user and site configuration paths."""
+        for path in self.iter_config_dirs():
+            yield Path(path)
+
+    def iter_data_paths(self) -> Iterator[Path]:
+        """:yield: all user and site data paths."""
+        for path in self.iter_data_dirs():
+            yield Path(path)
+
+    def iter_cache_paths(self) -> Iterator[Path]:
+        """:yield: all user and site cache paths."""
+        for path in self.iter_cache_dirs():
+            yield Path(path)
+
+    def iter_runtime_paths(self) -> Iterator[Path]:
+        """:yield: all user and site runtime paths."""
+        for path in self.iter_runtime_dirs():
+            yield Path(path)
diff --git a/setuptools/_vendor/platformdirs/macos.py b/setuptools/_vendor/platformdirs/macos.py
new file mode 100644
index 0000000000..30ab368913
--- /dev/null
+++ b/setuptools/_vendor/platformdirs/macos.py
@@ -0,0 +1,146 @@
+"""macOS."""
+
+from __future__ import annotations
+
+import os.path
+import sys
+from typing import TYPE_CHECKING
+
+from .api import PlatformDirsABC
+
+if TYPE_CHECKING:
+    from pathlib import Path
+
+
+class MacOS(PlatformDirsABC):
+    """
+    Platform directories for the macOS operating system.
+
+    Follows the guidance from
+    `Apple documentation `_.
+    Makes use of the `appname `,
+    `version `,
+    `ensure_exists `.
+
+    """
+
+    @property
+    def user_data_dir(self) -> str:
+        """:return: data directory tied to the user, e.g. ``~/Library/Application Support/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/Library/Application Support"))  # noqa: PTH111
+
+    @property
+    def site_data_dir(self) -> str:
+        """
+        :return: data directory shared by users, e.g. ``/Library/Application Support/$appname/$version``.
+          If we're using a Python binary managed by `Homebrew `_, the directory
+          will be under the Homebrew prefix, e.g. ``$homebrew_prefix/share/$appname/$version``.
+          If `multipath ` is enabled, and we're in Homebrew,
+          the response is a multi-path string separated by ":", e.g.
+          ``$homebrew_prefix/share/$appname/$version:/Library/Application Support/$appname/$version``
+        """
+        is_homebrew = "/opt/python" in sys.prefix
+        homebrew_prefix = sys.prefix.split("/opt/python")[0] if is_homebrew else ""
+        path_list = [self._append_app_name_and_version(f"{homebrew_prefix}/share")] if is_homebrew else []
+        path_list.append(self._append_app_name_and_version("/Library/Application Support"))
+        if self.multipath:
+            return os.pathsep.join(path_list)
+        return path_list[0]
+
+    @property
+    def site_data_path(self) -> Path:
+        """:return: data path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
+        return self._first_item_as_path_if_multipath(self.site_data_dir)
+
+    @property
+    def user_config_dir(self) -> str:
+        """:return: config directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def site_config_dir(self) -> str:
+        """:return: config directory shared by the users, same as `site_data_dir`"""
+        return self.site_data_dir
+
+    @property
+    def user_cache_dir(self) -> str:
+        """:return: cache directory tied to the user, e.g. ``~/Library/Caches/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/Library/Caches"))  # noqa: PTH111
+
+    @property
+    def site_cache_dir(self) -> str:
+        """
+        :return: cache directory shared by users, e.g. ``/Library/Caches/$appname/$version``.
+          If we're using a Python binary managed by `Homebrew `_, the directory
+          will be under the Homebrew prefix, e.g. ``$homebrew_prefix/var/cache/$appname/$version``.
+          If `multipath ` is enabled, and we're in Homebrew,
+          the response is a multi-path string separated by ":", e.g.
+          ``$homebrew_prefix/var/cache/$appname/$version:/Library/Caches/$appname/$version``
+        """
+        is_homebrew = "/opt/python" in sys.prefix
+        homebrew_prefix = sys.prefix.split("/opt/python")[0] if is_homebrew else ""
+        path_list = [self._append_app_name_and_version(f"{homebrew_prefix}/var/cache")] if is_homebrew else []
+        path_list.append(self._append_app_name_and_version("/Library/Caches"))
+        if self.multipath:
+            return os.pathsep.join(path_list)
+        return path_list[0]
+
+    @property
+    def site_cache_path(self) -> Path:
+        """:return: cache path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
+        return self._first_item_as_path_if_multipath(self.site_cache_dir)
+
+    @property
+    def user_state_dir(self) -> str:
+        """:return: state directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def user_log_dir(self) -> str:
+        """:return: log directory tied to the user, e.g. ``~/Library/Logs/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/Library/Logs"))  # noqa: PTH111
+
+    @property
+    def user_documents_dir(self) -> str:
+        """:return: documents directory tied to the user, e.g. ``~/Documents``"""
+        return os.path.expanduser("~/Documents")  # noqa: PTH111
+
+    @property
+    def user_downloads_dir(self) -> str:
+        """:return: downloads directory tied to the user, e.g. ``~/Downloads``"""
+        return os.path.expanduser("~/Downloads")  # noqa: PTH111
+
+    @property
+    def user_pictures_dir(self) -> str:
+        """:return: pictures directory tied to the user, e.g. ``~/Pictures``"""
+        return os.path.expanduser("~/Pictures")  # noqa: PTH111
+
+    @property
+    def user_videos_dir(self) -> str:
+        """:return: videos directory tied to the user, e.g. ``~/Movies``"""
+        return os.path.expanduser("~/Movies")  # noqa: PTH111
+
+    @property
+    def user_music_dir(self) -> str:
+        """:return: music directory tied to the user, e.g. ``~/Music``"""
+        return os.path.expanduser("~/Music")  # noqa: PTH111
+
+    @property
+    def user_desktop_dir(self) -> str:
+        """:return: desktop directory tied to the user, e.g. ``~/Desktop``"""
+        return os.path.expanduser("~/Desktop")  # noqa: PTH111
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """:return: runtime directory tied to the user, e.g. ``~/Library/Caches/TemporaryItems/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/Library/Caches/TemporaryItems"))  # noqa: PTH111
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """:return: runtime directory shared by users, same as `user_runtime_dir`"""
+        return self.user_runtime_dir
+
+
+__all__ = [
+    "MacOS",
+]
diff --git a/pkg_resources/_vendor/packaging/py.typed b/setuptools/_vendor/platformdirs/py.typed
similarity index 100%
rename from pkg_resources/_vendor/packaging/py.typed
rename to setuptools/_vendor/platformdirs/py.typed
diff --git a/setuptools/_vendor/platformdirs/unix.py b/setuptools/_vendor/platformdirs/unix.py
new file mode 100644
index 0000000000..fc75d8d074
--- /dev/null
+++ b/setuptools/_vendor/platformdirs/unix.py
@@ -0,0 +1,272 @@
+"""Unix."""
+
+from __future__ import annotations
+
+import os
+import sys
+from configparser import ConfigParser
+from pathlib import Path
+from typing import TYPE_CHECKING, NoReturn
+
+from .api import PlatformDirsABC
+
+if TYPE_CHECKING:
+    from collections.abc import Iterator
+
+if sys.platform == "win32":
+
+    def getuid() -> NoReturn:
+        msg = "should only be used on Unix"
+        raise RuntimeError(msg)
+
+else:
+    from os import getuid
+
+
+class Unix(PlatformDirsABC):  # noqa: PLR0904
+    """
+    On Unix/Linux, we follow the `XDG Basedir Spec `_.
+
+    The spec allows overriding directories with environment variables. The examples shown are the default values,
+    alongside the name of the environment variable that overrides them. Makes use of the `appname
+    `, `version `, `multipath
+    `, `opinion `, `ensure_exists
+    `.
+
+    """
+
+    @property
+    def user_data_dir(self) -> str:
+        """
+        :return: data directory tied to the user, e.g. ``~/.local/share/$appname/$version`` or
+         ``$XDG_DATA_HOME/$appname/$version``
+        """
+        path = os.environ.get("XDG_DATA_HOME", "")
+        if not path.strip():
+            path = os.path.expanduser("~/.local/share")  # noqa: PTH111
+        return self._append_app_name_and_version(path)
+
+    @property
+    def _site_data_dirs(self) -> list[str]:
+        path = os.environ.get("XDG_DATA_DIRS", "")
+        if not path.strip():
+            path = f"/usr/local/share{os.pathsep}/usr/share"
+        return [self._append_app_name_and_version(p) for p in path.split(os.pathsep)]
+
+    @property
+    def site_data_dir(self) -> str:
+        """
+        :return: data directories shared by users (if `multipath ` is
+         enabled and ``XDG_DATA_DIRS`` is set and a multi path the response is also a multi path separated by the
+         OS path separator), e.g. ``/usr/local/share/$appname/$version`` or ``/usr/share/$appname/$version``
+        """
+        # XDG default for $XDG_DATA_DIRS; only first, if multipath is False
+        dirs = self._site_data_dirs
+        if not self.multipath:
+            return dirs[0]
+        return os.pathsep.join(dirs)
+
+    @property
+    def user_config_dir(self) -> str:
+        """
+        :return: config directory tied to the user, e.g. ``~/.config/$appname/$version`` or
+         ``$XDG_CONFIG_HOME/$appname/$version``
+        """
+        path = os.environ.get("XDG_CONFIG_HOME", "")
+        if not path.strip():
+            path = os.path.expanduser("~/.config")  # noqa: PTH111
+        return self._append_app_name_and_version(path)
+
+    @property
+    def _site_config_dirs(self) -> list[str]:
+        path = os.environ.get("XDG_CONFIG_DIRS", "")
+        if not path.strip():
+            path = "/etc/xdg"
+        return [self._append_app_name_and_version(p) for p in path.split(os.pathsep)]
+
+    @property
+    def site_config_dir(self) -> str:
+        """
+        :return: config directories shared by users (if `multipath `
+         is enabled and ``XDG_CONFIG_DIRS`` is set and a multi path the response is also a multi path separated by
+         the OS path separator), e.g. ``/etc/xdg/$appname/$version``
+        """
+        # XDG default for $XDG_CONFIG_DIRS only first, if multipath is False
+        dirs = self._site_config_dirs
+        if not self.multipath:
+            return dirs[0]
+        return os.pathsep.join(dirs)
+
+    @property
+    def user_cache_dir(self) -> str:
+        """
+        :return: cache directory tied to the user, e.g. ``~/.cache/$appname/$version`` or
+         ``~/$XDG_CACHE_HOME/$appname/$version``
+        """
+        path = os.environ.get("XDG_CACHE_HOME", "")
+        if not path.strip():
+            path = os.path.expanduser("~/.cache")  # noqa: PTH111
+        return self._append_app_name_and_version(path)
+
+    @property
+    def site_cache_dir(self) -> str:
+        """:return: cache directory shared by users, e.g. ``/var/cache/$appname/$version``"""
+        return self._append_app_name_and_version("/var/cache")
+
+    @property
+    def user_state_dir(self) -> str:
+        """
+        :return: state directory tied to the user, e.g. ``~/.local/state/$appname/$version`` or
+         ``$XDG_STATE_HOME/$appname/$version``
+        """
+        path = os.environ.get("XDG_STATE_HOME", "")
+        if not path.strip():
+            path = os.path.expanduser("~/.local/state")  # noqa: PTH111
+        return self._append_app_name_and_version(path)
+
+    @property
+    def user_log_dir(self) -> str:
+        """:return: log directory tied to the user, same as `user_state_dir` if not opinionated else ``log`` in it"""
+        path = self.user_state_dir
+        if self.opinion:
+            path = os.path.join(path, "log")  # noqa: PTH118
+            self._optionally_create_directory(path)
+        return path
+
+    @property
+    def user_documents_dir(self) -> str:
+        """:return: documents directory tied to the user, e.g. ``~/Documents``"""
+        return _get_user_media_dir("XDG_DOCUMENTS_DIR", "~/Documents")
+
+    @property
+    def user_downloads_dir(self) -> str:
+        """:return: downloads directory tied to the user, e.g. ``~/Downloads``"""
+        return _get_user_media_dir("XDG_DOWNLOAD_DIR", "~/Downloads")
+
+    @property
+    def user_pictures_dir(self) -> str:
+        """:return: pictures directory tied to the user, e.g. ``~/Pictures``"""
+        return _get_user_media_dir("XDG_PICTURES_DIR", "~/Pictures")
+
+    @property
+    def user_videos_dir(self) -> str:
+        """:return: videos directory tied to the user, e.g. ``~/Videos``"""
+        return _get_user_media_dir("XDG_VIDEOS_DIR", "~/Videos")
+
+    @property
+    def user_music_dir(self) -> str:
+        """:return: music directory tied to the user, e.g. ``~/Music``"""
+        return _get_user_media_dir("XDG_MUSIC_DIR", "~/Music")
+
+    @property
+    def user_desktop_dir(self) -> str:
+        """:return: desktop directory tied to the user, e.g. ``~/Desktop``"""
+        return _get_user_media_dir("XDG_DESKTOP_DIR", "~/Desktop")
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """
+        :return: runtime directory tied to the user, e.g. ``/run/user/$(id -u)/$appname/$version`` or
+         ``$XDG_RUNTIME_DIR/$appname/$version``.
+
+         For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/user/$(id -u)/$appname/$version`` if
+         exists, otherwise ``/tmp/runtime-$(id -u)/$appname/$version``, if``$XDG_RUNTIME_DIR``
+         is not set.
+        """
+        path = os.environ.get("XDG_RUNTIME_DIR", "")
+        if not path.strip():
+            if sys.platform.startswith(("freebsd", "openbsd", "netbsd")):
+                path = f"/var/run/user/{getuid()}"
+                if not Path(path).exists():
+                    path = f"/tmp/runtime-{getuid()}"  # noqa: S108
+            else:
+                path = f"/run/user/{getuid()}"
+        return self._append_app_name_and_version(path)
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """
+        :return: runtime directory shared by users, e.g. ``/run/$appname/$version`` or \
+        ``$XDG_RUNTIME_DIR/$appname/$version``.
+
+        Note that this behaves almost exactly like `user_runtime_dir` if ``$XDG_RUNTIME_DIR`` is set, but will
+        fall back to paths associated to the root user instead of a regular logged-in user if it's not set.
+
+        If you wish to ensure that a logged-in root user path is returned e.g. ``/run/user/0``, use `user_runtime_dir`
+        instead.
+
+        For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/$appname/$version`` if ``$XDG_RUNTIME_DIR`` is not set.
+        """
+        path = os.environ.get("XDG_RUNTIME_DIR", "")
+        if not path.strip():
+            if sys.platform.startswith(("freebsd", "openbsd", "netbsd")):
+                path = "/var/run"
+            else:
+                path = "/run"
+        return self._append_app_name_and_version(path)
+
+    @property
+    def site_data_path(self) -> Path:
+        """:return: data path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
+        return self._first_item_as_path_if_multipath(self.site_data_dir)
+
+    @property
+    def site_config_path(self) -> Path:
+        """:return: config path shared by the users, returns the first item, even if ``multipath`` is set to ``True``"""
+        return self._first_item_as_path_if_multipath(self.site_config_dir)
+
+    @property
+    def site_cache_path(self) -> Path:
+        """:return: cache path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
+        return self._first_item_as_path_if_multipath(self.site_cache_dir)
+
+    def iter_config_dirs(self) -> Iterator[str]:
+        """:yield: all user and site configuration directories."""
+        yield self.user_config_dir
+        yield from self._site_config_dirs
+
+    def iter_data_dirs(self) -> Iterator[str]:
+        """:yield: all user and site data directories."""
+        yield self.user_data_dir
+        yield from self._site_data_dirs
+
+
+def _get_user_media_dir(env_var: str, fallback_tilde_path: str) -> str:
+    media_dir = _get_user_dirs_folder(env_var)
+    if media_dir is None:
+        media_dir = os.environ.get(env_var, "").strip()
+        if not media_dir:
+            media_dir = os.path.expanduser(fallback_tilde_path)  # noqa: PTH111
+
+    return media_dir
+
+
+def _get_user_dirs_folder(key: str) -> str | None:
+    """
+    Return directory from user-dirs.dirs config file.
+
+    See https://freedesktop.org/wiki/Software/xdg-user-dirs/.
+
+    """
+    user_dirs_config_path = Path(Unix().user_config_dir) / "user-dirs.dirs"
+    if user_dirs_config_path.exists():
+        parser = ConfigParser()
+
+        with user_dirs_config_path.open() as stream:
+            # Add fake section header, so ConfigParser doesn't complain
+            parser.read_string(f"[top]\n{stream.read()}")
+
+        if key not in parser["top"]:
+            return None
+
+        path = parser["top"][key].strip('"')
+        # Handle relative home paths
+        return path.replace("$HOME", os.path.expanduser("~"))  # noqa: PTH111
+
+    return None
+
+
+__all__ = [
+    "Unix",
+]
diff --git a/setuptools/_vendor/platformdirs/version.py b/setuptools/_vendor/platformdirs/version.py
new file mode 100644
index 0000000000..b9451472c3
--- /dev/null
+++ b/setuptools/_vendor/platformdirs/version.py
@@ -0,0 +1,34 @@
+# file generated by setuptools-scm
+# don't change, don't track in version control
+
+__all__ = [
+    "__version__",
+    "__version_tuple__",
+    "version",
+    "version_tuple",
+    "__commit_id__",
+    "commit_id",
+]
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+    from typing import Tuple
+    from typing import Union
+
+    VERSION_TUPLE = Tuple[Union[int, str], ...]
+    COMMIT_ID = Union[str, None]
+else:
+    VERSION_TUPLE = object
+    COMMIT_ID = object
+
+version: str
+__version__: str
+__version_tuple__: VERSION_TUPLE
+version_tuple: VERSION_TUPLE
+commit_id: COMMIT_ID
+__commit_id__: COMMIT_ID
+
+__version__ = version = '4.4.0'
+__version_tuple__ = version_tuple = (4, 4, 0)
+
+__commit_id__ = commit_id = None
diff --git a/setuptools/_vendor/platformdirs/windows.py b/setuptools/_vendor/platformdirs/windows.py
new file mode 100644
index 0000000000..d7bc96091a
--- /dev/null
+++ b/setuptools/_vendor/platformdirs/windows.py
@@ -0,0 +1,272 @@
+"""Windows."""
+
+from __future__ import annotations
+
+import os
+import sys
+from functools import lru_cache
+from typing import TYPE_CHECKING
+
+from .api import PlatformDirsABC
+
+if TYPE_CHECKING:
+    from collections.abc import Callable
+
+
+class Windows(PlatformDirsABC):
+    """
+    `MSDN on where to store app data files `_.
+
+    Makes use of the `appname `, `appauthor
+    `, `version `, `roaming
+    `, `opinion `, `ensure_exists
+    `.
+
+    """
+
+    @property
+    def user_data_dir(self) -> str:
+        """
+        :return: data directory tied to the user, e.g.
+         ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname`` (not roaming) or
+         ``%USERPROFILE%\\AppData\\Roaming\\$appauthor\\$appname`` (roaming)
+        """
+        const = "CSIDL_APPDATA" if self.roaming else "CSIDL_LOCAL_APPDATA"
+        path = os.path.normpath(get_win_folder(const))
+        return self._append_parts(path)
+
+    def _append_parts(self, path: str, *, opinion_value: str | None = None) -> str:
+        params = []
+        if self.appname:
+            if self.appauthor is not False:
+                author = self.appauthor or self.appname
+                params.append(author)
+            params.append(self.appname)
+            if opinion_value is not None and self.opinion:
+                params.append(opinion_value)
+            if self.version:
+                params.append(self.version)
+        path = os.path.join(path, *params)  # noqa: PTH118
+        self._optionally_create_directory(path)
+        return path
+
+    @property
+    def site_data_dir(self) -> str:
+        """:return: data directory shared by users, e.g. ``C:\\ProgramData\\$appauthor\\$appname``"""
+        path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
+        return self._append_parts(path)
+
+    @property
+    def user_config_dir(self) -> str:
+        """:return: config directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def site_config_dir(self) -> str:
+        """:return: config directory shared by the users, same as `site_data_dir`"""
+        return self.site_data_dir
+
+    @property
+    def user_cache_dir(self) -> str:
+        """
+        :return: cache directory tied to the user (if opinionated with ``Cache`` folder within ``$appname``) e.g.
+         ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname\\Cache\\$version``
+        """
+        path = os.path.normpath(get_win_folder("CSIDL_LOCAL_APPDATA"))
+        return self._append_parts(path, opinion_value="Cache")
+
+    @property
+    def site_cache_dir(self) -> str:
+        """:return: cache directory shared by users, e.g. ``C:\\ProgramData\\$appauthor\\$appname\\Cache\\$version``"""
+        path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
+        return self._append_parts(path, opinion_value="Cache")
+
+    @property
+    def user_state_dir(self) -> str:
+        """:return: state directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def user_log_dir(self) -> str:
+        """:return: log directory tied to the user, same as `user_data_dir` if not opinionated else ``Logs`` in it"""
+        path = self.user_data_dir
+        if self.opinion:
+            path = os.path.join(path, "Logs")  # noqa: PTH118
+            self._optionally_create_directory(path)
+        return path
+
+    @property
+    def user_documents_dir(self) -> str:
+        """:return: documents directory tied to the user e.g. ``%USERPROFILE%\\Documents``"""
+        return os.path.normpath(get_win_folder("CSIDL_PERSONAL"))
+
+    @property
+    def user_downloads_dir(self) -> str:
+        """:return: downloads directory tied to the user e.g. ``%USERPROFILE%\\Downloads``"""
+        return os.path.normpath(get_win_folder("CSIDL_DOWNLOADS"))
+
+    @property
+    def user_pictures_dir(self) -> str:
+        """:return: pictures directory tied to the user e.g. ``%USERPROFILE%\\Pictures``"""
+        return os.path.normpath(get_win_folder("CSIDL_MYPICTURES"))
+
+    @property
+    def user_videos_dir(self) -> str:
+        """:return: videos directory tied to the user e.g. ``%USERPROFILE%\\Videos``"""
+        return os.path.normpath(get_win_folder("CSIDL_MYVIDEO"))
+
+    @property
+    def user_music_dir(self) -> str:
+        """:return: music directory tied to the user e.g. ``%USERPROFILE%\\Music``"""
+        return os.path.normpath(get_win_folder("CSIDL_MYMUSIC"))
+
+    @property
+    def user_desktop_dir(self) -> str:
+        """:return: desktop directory tied to the user, e.g. ``%USERPROFILE%\\Desktop``"""
+        return os.path.normpath(get_win_folder("CSIDL_DESKTOPDIRECTORY"))
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """
+        :return: runtime directory tied to the user, e.g.
+         ``%USERPROFILE%\\AppData\\Local\\Temp\\$appauthor\\$appname``
+        """
+        path = os.path.normpath(os.path.join(get_win_folder("CSIDL_LOCAL_APPDATA"), "Temp"))  # noqa: PTH118
+        return self._append_parts(path)
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """:return: runtime directory shared by users, same as `user_runtime_dir`"""
+        return self.user_runtime_dir
+
+
+def get_win_folder_from_env_vars(csidl_name: str) -> str:
+    """Get folder from environment variables."""
+    result = get_win_folder_if_csidl_name_not_env_var(csidl_name)
+    if result is not None:
+        return result
+
+    env_var_name = {
+        "CSIDL_APPDATA": "APPDATA",
+        "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE",
+        "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA",
+    }.get(csidl_name)
+    if env_var_name is None:
+        msg = f"Unknown CSIDL name: {csidl_name}"
+        raise ValueError(msg)
+    result = os.environ.get(env_var_name)
+    if result is None:
+        msg = f"Unset environment variable: {env_var_name}"
+        raise ValueError(msg)
+    return result
+
+
+def get_win_folder_if_csidl_name_not_env_var(csidl_name: str) -> str | None:
+    """Get a folder for a CSIDL name that does not exist as an environment variable."""
+    if csidl_name == "CSIDL_PERSONAL":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Documents")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_DOWNLOADS":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Downloads")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_MYPICTURES":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Pictures")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_MYVIDEO":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Videos")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_MYMUSIC":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Music")  # noqa: PTH118
+    return None
+
+
+def get_win_folder_from_registry(csidl_name: str) -> str:
+    """
+    Get folder from the registry.
+
+    This is a fallback technique at best. I'm not sure if using the registry for these guarantees us the correct answer
+    for all CSIDL_* names.
+
+    """
+    shell_folder_name = {
+        "CSIDL_APPDATA": "AppData",
+        "CSIDL_COMMON_APPDATA": "Common AppData",
+        "CSIDL_LOCAL_APPDATA": "Local AppData",
+        "CSIDL_PERSONAL": "Personal",
+        "CSIDL_DOWNLOADS": "{374DE290-123F-4565-9164-39C4925E467B}",
+        "CSIDL_MYPICTURES": "My Pictures",
+        "CSIDL_MYVIDEO": "My Video",
+        "CSIDL_MYMUSIC": "My Music",
+    }.get(csidl_name)
+    if shell_folder_name is None:
+        msg = f"Unknown CSIDL name: {csidl_name}"
+        raise ValueError(msg)
+    if sys.platform != "win32":  # only needed for mypy type checker to know that this code runs only on Windows
+        raise NotImplementedError
+    import winreg  # noqa: PLC0415
+
+    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
+    directory, _ = winreg.QueryValueEx(key, shell_folder_name)
+    return str(directory)
+
+
+def get_win_folder_via_ctypes(csidl_name: str) -> str:
+    """Get folder with ctypes."""
+    # There is no 'CSIDL_DOWNLOADS'.
+    # Use 'CSIDL_PROFILE' (40) and append the default folder 'Downloads' instead.
+    # https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid
+
+    import ctypes  # noqa: PLC0415
+
+    csidl_const = {
+        "CSIDL_APPDATA": 26,
+        "CSIDL_COMMON_APPDATA": 35,
+        "CSIDL_LOCAL_APPDATA": 28,
+        "CSIDL_PERSONAL": 5,
+        "CSIDL_MYPICTURES": 39,
+        "CSIDL_MYVIDEO": 14,
+        "CSIDL_MYMUSIC": 13,
+        "CSIDL_DOWNLOADS": 40,
+        "CSIDL_DESKTOPDIRECTORY": 16,
+    }.get(csidl_name)
+    if csidl_const is None:
+        msg = f"Unknown CSIDL name: {csidl_name}"
+        raise ValueError(msg)
+
+    buf = ctypes.create_unicode_buffer(1024)
+    windll = getattr(ctypes, "windll")  # noqa: B009 # using getattr to avoid false positive with mypy type checker
+    windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
+
+    # Downgrade to short path name if it has high-bit chars.
+    if any(ord(c) > 255 for c in buf):  # noqa: PLR2004
+        buf2 = ctypes.create_unicode_buffer(1024)
+        if windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
+            buf = buf2
+
+    if csidl_name == "CSIDL_DOWNLOADS":
+        return os.path.join(buf.value, "Downloads")  # noqa: PTH118
+
+    return buf.value
+
+
+def _pick_get_win_folder() -> Callable[[str], str]:
+    try:
+        import ctypes  # noqa: PLC0415
+    except ImportError:
+        pass
+    else:
+        if hasattr(ctypes, "windll"):
+            return get_win_folder_via_ctypes
+    try:
+        import winreg  # noqa: PLC0415, F401
+    except ImportError:
+        return get_win_folder_from_env_vars
+    else:
+        return get_win_folder_from_registry
+
+
+get_win_folder = lru_cache(maxsize=None)(_pick_get_win_folder())
+
+__all__ = [
+    "Windows",
+]
diff --git a/setuptools/_vendor/ruff.toml b/setuptools/_vendor/ruff.toml
new file mode 100644
index 0000000000..00fee625a5
--- /dev/null
+++ b/setuptools/_vendor/ruff.toml
@@ -0,0 +1 @@
+exclude = ["*"]
diff --git a/setuptools/_vendor/tomli-2.0.1.dist-info/INSTALLER b/setuptools/_vendor/tomli-2.0.1.dist-info/INSTALLER
deleted file mode 100644
index a1b589e38a..0000000000
--- a/setuptools/_vendor/tomli-2.0.1.dist-info/INSTALLER
+++ /dev/null
@@ -1 +0,0 @@
-pip
diff --git a/setuptools/_vendor/tomli-2.0.1.dist-info/RECORD b/setuptools/_vendor/tomli-2.0.1.dist-info/RECORD
deleted file mode 100644
index 5f7a6b06b3..0000000000
--- a/setuptools/_vendor/tomli-2.0.1.dist-info/RECORD
+++ /dev/null
@@ -1,15 +0,0 @@
-tomli-2.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-tomli-2.0.1.dist-info/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
-tomli-2.0.1.dist-info/METADATA,sha256=zPDceKmPwJGLWtZykrHixL7WVXWmJGzZ1jyRT5lCoPI,8875
-tomli-2.0.1.dist-info/RECORD,,
-tomli-2.0.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-tomli-2.0.1.dist-info/WHEEL,sha256=jPMR_Dzkc4X4icQtmz81lnNY_kAsfog7ry7qoRvYLXw,81
-tomli/__init__.py,sha256=JhUwV66DB1g4Hvt1UQCVMdfCu-IgAV8FXmvDU9onxd4,396
-tomli/__pycache__/__init__.cpython-311.pyc,,
-tomli/__pycache__/_parser.cpython-311.pyc,,
-tomli/__pycache__/_re.cpython-311.pyc,,
-tomli/__pycache__/_types.cpython-311.pyc,,
-tomli/_parser.py,sha256=g9-ENaALS-B8dokYpCuzUFalWlog7T-SIYMjLZSWrtM,22633
-tomli/_re.py,sha256=dbjg5ChZT23Ka9z9DHOXfdtSpPwUfdgMXnj8NOoly-w,2943
-tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254
-tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
diff --git a/setuptools/_vendor/tomli-2.0.1.dist-info/WHEEL b/setuptools/_vendor/tomli-2.0.1.dist-info/WHEEL
deleted file mode 100644
index c727d14823..0000000000
--- a/setuptools/_vendor/tomli-2.0.1.dist-info/WHEEL
+++ /dev/null
@@ -1,4 +0,0 @@
-Wheel-Version: 1.0
-Generator: flit 3.6.0
-Root-Is-Purelib: true
-Tag: py3-none-any
diff --git a/setuptools/_vendor/tomli-2.4.0.dist-info/INSTALLER b/setuptools/_vendor/tomli-2.4.0.dist-info/INSTALLER
new file mode 100644
index 0000000000..5c69047b2e
--- /dev/null
+++ b/setuptools/_vendor/tomli-2.4.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/setuptools/_vendor/tomli-2.0.1.dist-info/METADATA b/setuptools/_vendor/tomli-2.4.0.dist-info/METADATA
similarity index 63%
rename from setuptools/_vendor/tomli-2.0.1.dist-info/METADATA
rename to setuptools/_vendor/tomli-2.4.0.dist-info/METADATA
index efd87ecc16..ffe8e40d77 100644
--- a/setuptools/_vendor/tomli-2.0.1.dist-info/METADATA
+++ b/setuptools/_vendor/tomli-2.4.0.dist-info/METADATA
@@ -1,28 +1,25 @@
-Metadata-Version: 2.1
+Metadata-Version: 2.4
 Name: tomli
-Version: 2.0.1
+Version: 2.4.0
 Summary: A lil' TOML parser
 Keywords: toml
 Author-email: Taneli Hukkinen 
-Requires-Python: >=3.7
+Requires-Python: >=3.8
 Description-Content-Type: text/markdown
-Classifier: License :: OSI Approved :: MIT License
+License-Expression: MIT
 Classifier: Operating System :: MacOS
 Classifier: Operating System :: Microsoft :: Windows
 Classifier: Operating System :: POSIX :: Linux
 Classifier: Programming Language :: Python :: 3 :: Only
-Classifier: Programming Language :: Python :: 3.7
-Classifier: Programming Language :: Python :: 3.8
-Classifier: Programming Language :: Python :: 3.9
-Classifier: Programming Language :: Python :: 3.10
 Classifier: Programming Language :: Python :: Implementation :: CPython
 Classifier: Programming Language :: Python :: Implementation :: PyPy
 Classifier: Topic :: Software Development :: Libraries :: Python Modules
 Classifier: Typing :: Typed
+License-File: LICENSE
 Project-URL: Changelog, https://github.com/hukkin/tomli/blob/master/CHANGELOG.md
 Project-URL: Homepage, https://github.com/hukkin/tomli
 
-[![Build Status](https://github.com/hukkin/tomli/workflows/Tests/badge.svg?branch=master)](https://github.com/hukkin/tomli/actions?query=workflow%3ATests+branch%3Amaster+event%3Apush)
+[![Build Status](https://github.com/hukkin/tomli/actions/workflows/tests.yaml/badge.svg?branch=master)](https://github.com/hukkin/tomli/actions?query=workflow%3ATests+branch%3Amaster+event%3Apush)
 [![codecov.io](https://codecov.io/gh/hukkin/tomli/branch/master/graph/badge.svg)](https://codecov.io/gh/hukkin/tomli)
 [![PyPI version](https://img.shields.io/pypi/v/tomli)](https://pypi.org/project/tomli)
 
@@ -30,7 +27,7 @@ Project-URL: Homepage, https://github.com/hukkin/tomli
 
 > A lil' TOML parser
 
-**Table of Contents**  *generated with [mdformat-toc](https://github.com/hukkin/mdformat-toc)*
+**Table of Contents** *generated with [mdformat-toc](https://github.com/hukkin/mdformat-toc)*
 
 
 
@@ -41,19 +38,35 @@ Project-URL: Homepage, https://github.com/hukkin/tomli
   - [Parse a TOML file](#parse-a-toml-file)
   - [Handle invalid TOML](#handle-invalid-toml)
   - [Construct `decimal.Decimal`s from TOML floats](#construct-decimaldecimals-from-toml-floats)
+  - [Building a `tomli`/`tomllib` compatibility layer](#building-a-tomlitomllib-compatibility-layer)
 - [FAQ](#faq)
   - [Why this parser?](#why-this-parser)
   - [Is comment preserving round-trip parsing supported?](#is-comment-preserving-round-trip-parsing-supported)
   - [Is there a `dumps`, `write` or `encode` function?](#is-there-a-dumps-write-or-encode-function)
   - [How do TOML types map into Python types?](#how-do-toml-types-map-into-python-types)
 - [Performance](#performance)
+  - [Pure Python](#pure-python)
+  - [Mypyc generated wheel](#mypyc-generated-wheel)
 
 
 
 ## Intro
 
 Tomli is a Python library for parsing [TOML](https://toml.io).
-Tomli is fully compatible with [TOML v1.0.0](https://toml.io/en/v1.0.0).
+Version 2.4.0 and later are compatible with [TOML v1.1.0](https://toml.io/en/v1.1.0).
+Older versions are [TOML v1.0.0](https://toml.io/en/v1.0.0) compatible.
+
+A version of Tomli, the `tomllib` module,
+was added to the standard library in Python 3.11
+via [PEP 680](https://www.python.org/dev/peps/pep-0680/).
+Tomli continues to provide a backport on PyPI for Python versions
+where the standard library module is not available
+and that have not yet reached their end-of-life.
+
+Tomli uses [mypyc](https://github.com/mypyc/mypyc)
+to generate binary wheels for most of the widely used platforms,
+so Python 3.11+ users may prefer it over `tomllib` for improved performance.
+Pure Python wheels are available on any platform and should perform the same as `tomllib`.
 
 ## Installation
 
@@ -69,14 +82,19 @@ pip install tomli
 import tomli
 
 toml_str = """
-           gretzky = 99
+[[players]]
+name = "Lehtinen"
+number = 26
 
-           [kurri]
-           jari = 17
-           """
+[[players]]
+name = "Numminen"
+number = 27
+"""
 
 toml_dict = tomli.loads(toml_str)
-assert toml_dict == {"gretzky": 99, "kurri": {"jari": 17}}
+assert toml_dict == {
+    "players": [{"name": "Lehtinen", "number": 26}, {"name": "Numminen", "number": 27}]
+}
 ```
 
 ### Parse a TOML file
@@ -113,6 +131,7 @@ from decimal import Decimal
 import tomli
 
 toml_dict = tomli.loads("precision-matters = 0.982492", parse_float=Decimal)
+assert isinstance(toml_dict["precision-matters"], Decimal)
 assert toml_dict["precision-matters"] == Decimal("0.982492")
 ```
 
@@ -122,21 +141,48 @@ The `decimal.Decimal` is, however, a practical choice for use cases where float
 Illegal types are `dict` and `list`, and their subtypes.
 A `ValueError` will be raised if `parse_float` produces illegal types.
 
+### Building a `tomli`/`tomllib` compatibility layer
+
+Python versions 3.11+ ship with a version of Tomli:
+the `tomllib` standard library module.
+To build code that uses the standard library if available,
+but still works seamlessly with Python 3.6+,
+do the following.
+
+Instead of a hard Tomli dependency, use the following
+[dependency specifier](https://packaging.python.org/en/latest/specifications/dependency-specifiers/)
+to only require Tomli when the standard library module is not available:
+
+```
+tomli >= 1.1.0 ; python_version < "3.11"
+```
+
+Then, in your code, import a TOML parser using the following fallback mechanism:
+
+```python
+import sys
+
+if sys.version_info >= (3, 11):
+    import tomllib
+else:
+    import tomli as tomllib
+
+tomllib.loads("['This parses fine with Python 3.6+']")
+```
+
 ## FAQ
 
 ### Why this parser?
 
 - it's lil'
 - pure Python with zero dependencies
-- the fastest pure Python parser [\*](#performance):
-  15x as fast as [tomlkit](https://pypi.org/project/tomlkit/),
-  2.4x as fast as [toml](https://pypi.org/project/toml/)
+- the fastest pure Python parser [\*](#pure-python):
+  18x as fast as [tomlkit](https://pypi.org/project/tomlkit/),
+  2.1x as fast as [toml](https://pypi.org/project/toml/)
 - outputs [basic data types](#how-do-toml-types-map-into-python-types) only
 - 100% spec compliant: passes all tests in
-  [a test set](https://github.com/toml-lang/compliance/pull/8)
-  soon to be merged to the official
-  [compliance tests for TOML](https://github.com/toml-lang/compliance)
-  repository
+  [toml-lang/toml-test](https://github.com/toml-lang/toml-test)
+  test suite
 - thoroughly tested: 100% branch coverage
 
 ### Is comment preserving round-trip parsing supported?
@@ -176,31 +222,49 @@ The core library does not include write capability, as most TOML use cases are r
 ## Performance
 
 The `benchmark/` folder in this repository contains a performance benchmark for comparing the various Python TOML parsers.
-The benchmark can be run with `tox -e benchmark-pypi`.
-Running the benchmark on my personal computer output the following:
+
+Below are the results for commit [0724e2a](https://github.com/hukkin/tomli/tree/0724e2ab1858da7f5e05a9bffdb24c33589d951c).
+
+### Pure Python
 
 ```console
-foo@bar:~/dev/tomli$ tox -e benchmark-pypi
-benchmark-pypi installed: attrs==19.3.0,click==7.1.2,pytomlpp==1.0.2,qtoml==0.3.0,rtoml==0.7.0,toml==0.10.2,tomli==1.1.0,tomlkit==0.7.2
-benchmark-pypi run-test-pre: PYTHONHASHSEED='2658546909'
-benchmark-pypi run-test: commands[0] | python -c 'import datetime; print(datetime.date.today())'
-2021-07-23
-benchmark-pypi run-test: commands[1] | python --version
-Python 3.8.10
-benchmark-pypi run-test: commands[2] | python benchmark/run.py
+foo@bar:~/dev/tomli$ python --version
+Python 3.12.7
+foo@bar:~/dev/tomli$ pip freeze
+attrs==21.4.0
+click==8.1.7
+pytomlpp==1.0.13
+qtoml==0.3.1
+rtoml==0.11.0
+toml==0.10.2
+tomli @ file:///home/foo/dev/tomli
+tomlkit==0.13.2
+foo@bar:~/dev/tomli$ python benchmark/run.py
 Parsing data.toml 5000 times:
 ------------------------------------------------------
     parser |  exec time | performance (more is better)
 -----------+------------+-----------------------------
-     rtoml |    0.901 s | baseline (100%)
-  pytomlpp |     1.08 s | 83.15%
-     tomli |     3.89 s | 23.15%
-      toml |     9.36 s | 9.63%
-     qtoml |     11.5 s | 7.82%
-   tomlkit |     56.8 s | 1.59%
+     rtoml |    0.647 s | baseline (100%)
+  pytomlpp |    0.891 s | 72.62%
+     tomli |     3.14 s | 20.56%
+      toml |     6.69 s | 9.67%
+     qtoml |     8.27 s | 7.82%
+   tomlkit |     56.1 s | 1.15%
 ```
 
-The parsers are ordered from fastest to slowest, using the fastest parser as baseline.
-Tomli performed the best out of all pure Python TOML parsers,
-losing only to pytomlpp (wraps C++) and rtoml (wraps Rust).
+### Mypyc generated wheel
+
+```console
+foo@bar:~/dev/tomli$ python benchmark/run.py
+Parsing data.toml 5000 times:
+------------------------------------------------------
+    parser |  exec time | performance (more is better)
+-----------+------------+-----------------------------
+     rtoml |    0.668 s | baseline (100%)
+  pytomlpp |    0.893 s | 74.81%
+     tomli |     1.96 s | 34.18%
+      toml |     6.64 s | 10.07%
+     qtoml |     8.26 s | 8.09%
+   tomlkit |     52.9 s | 1.26%
+```
 
diff --git a/setuptools/_vendor/tomli-2.4.0.dist-info/RECORD b/setuptools/_vendor/tomli-2.4.0.dist-info/RECORD
new file mode 100644
index 0000000000..d2415a38de
--- /dev/null
+++ b/setuptools/_vendor/tomli-2.4.0.dist-info/RECORD
@@ -0,0 +1,11 @@
+tomli-2.4.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+tomli-2.4.0.dist-info/METADATA,sha256=9awKH4-6kItGRs1lUwnpGq2Wm2eHYWrFccpGKjgy_84,10567
+tomli-2.4.0.dist-info/RECORD,,
+tomli-2.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tomli-2.4.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
+tomli-2.4.0.dist-info/licenses/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
+tomli/__init__.py,sha256=ahtDjGJA2M_wWVvGpzx4YJtWxrWBx6qE-GH5-UYoECA,314
+tomli/_parser.py,sha256=txeATLE3zHyZ-ushXtYfrZ3LoIs7JzQF2W2KL1gwJPg,25958
+tomli/_re.py,sha256=oSNZ_ilFI6chEuQ01YRSoUydBQr_okF_mSdHTkFmv90,3396
+tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254
+tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
diff --git a/setuptools/_vendor/ordered_set-3.1.1.dist-info/REQUESTED b/setuptools/_vendor/tomli-2.4.0.dist-info/REQUESTED
similarity index 100%
rename from setuptools/_vendor/ordered_set-3.1.1.dist-info/REQUESTED
rename to setuptools/_vendor/tomli-2.4.0.dist-info/REQUESTED
diff --git a/pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/WHEEL b/setuptools/_vendor/tomli-2.4.0.dist-info/WHEEL
similarity index 71%
rename from pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/WHEEL
rename to setuptools/_vendor/tomli-2.4.0.dist-info/WHEEL
index 668ba4d015..d8b9936dad 100644
--- a/pkg_resources/_vendor/typing_extensions-4.4.0.dist-info/WHEEL
+++ b/setuptools/_vendor/tomli-2.4.0.dist-info/WHEEL
@@ -1,4 +1,4 @@
 Wheel-Version: 1.0
-Generator: flit 3.7.1
+Generator: flit 3.12.0
 Root-Is-Purelib: true
 Tag: py3-none-any
diff --git a/setuptools/_vendor/tomli-2.0.1.dist-info/LICENSE b/setuptools/_vendor/tomli-2.4.0.dist-info/licenses/LICENSE
similarity index 100%
rename from setuptools/_vendor/tomli-2.0.1.dist-info/LICENSE
rename to setuptools/_vendor/tomli-2.4.0.dist-info/licenses/LICENSE
diff --git a/setuptools/_vendor/tomli/__init__.py b/setuptools/_vendor/tomli/__init__.py
index 4c6ec97ec6..55699b1ea6 100644
--- a/setuptools/_vendor/tomli/__init__.py
+++ b/setuptools/_vendor/tomli/__init__.py
@@ -3,9 +3,6 @@
 # Licensed to PSF under a Contributor Agreement.
 
 __all__ = ("loads", "load", "TOMLDecodeError")
-__version__ = "2.0.1"  # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT
+__version__ = "2.4.0"  # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT
 
 from ._parser import TOMLDecodeError, load, loads
-
-# Pretend this exception was created here.
-TOMLDecodeError.__module__ = __name__
diff --git a/setuptools/_vendor/tomli/_parser.py b/setuptools/_vendor/tomli/_parser.py
index f1bb0aa19a..3038891afe 100644
--- a/setuptools/_vendor/tomli/_parser.py
+++ b/setuptools/_vendor/tomli/_parser.py
@@ -4,10 +4,8 @@
 
 from __future__ import annotations
 
-from collections.abc import Iterable
-import string
+import sys
 from types import MappingProxyType
-from typing import Any, BinaryIO, NamedTuple
 
 from ._re import (
     RE_DATETIME,
@@ -17,44 +15,126 @@
     match_to_localtime,
     match_to_number,
 )
-from ._types import Key, ParseFloat, Pos
 
-ASCII_CTRL = frozenset(chr(i) for i in range(32)) | frozenset(chr(127))
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+    from collections.abc import Iterable
+    from typing import IO, Any, Final
+
+    from ._types import Key, ParseFloat, Pos
+
+# Inline tables/arrays are implemented using recursion. Pathologically
+# nested documents cause pure Python to raise RecursionError (which is OK),
+# but mypyc binary wheels will crash unrecoverably (not OK). According to
+# mypyc docs this will be fixed in the future:
+# https://mypyc.readthedocs.io/en/latest/differences_from_python.html#stack-overflows
+# Before mypyc's fix is in, recursion needs to be limited by this library.
+# Choosing `sys.getrecursionlimit()` as maximum inline table/array nesting
+# level, as it allows more nesting than pure Python, but still seems a far
+# lower number than where mypyc binaries crash.
+MAX_INLINE_NESTING: Final = sys.getrecursionlimit()
+
+ASCII_CTRL: Final = frozenset(chr(i) for i in range(32)) | frozenset(chr(127))
 
 # Neither of these sets include quotation mark or backslash. They are
 # currently handled as separate cases in the parser functions.
-ILLEGAL_BASIC_STR_CHARS = ASCII_CTRL - frozenset("\t")
-ILLEGAL_MULTILINE_BASIC_STR_CHARS = ASCII_CTRL - frozenset("\t\n")
+ILLEGAL_BASIC_STR_CHARS: Final = ASCII_CTRL - frozenset("\t")
+ILLEGAL_MULTILINE_BASIC_STR_CHARS: Final = ASCII_CTRL - frozenset("\t\n")
 
-ILLEGAL_LITERAL_STR_CHARS = ILLEGAL_BASIC_STR_CHARS
-ILLEGAL_MULTILINE_LITERAL_STR_CHARS = ILLEGAL_MULTILINE_BASIC_STR_CHARS
+ILLEGAL_LITERAL_STR_CHARS: Final = ILLEGAL_BASIC_STR_CHARS
+ILLEGAL_MULTILINE_LITERAL_STR_CHARS: Final = ILLEGAL_MULTILINE_BASIC_STR_CHARS
 
-ILLEGAL_COMMENT_CHARS = ILLEGAL_BASIC_STR_CHARS
+ILLEGAL_COMMENT_CHARS: Final = ILLEGAL_BASIC_STR_CHARS
 
-TOML_WS = frozenset(" \t")
-TOML_WS_AND_NEWLINE = TOML_WS | frozenset("\n")
-BARE_KEY_CHARS = frozenset(string.ascii_letters + string.digits + "-_")
-KEY_INITIAL_CHARS = BARE_KEY_CHARS | frozenset("\"'")
-HEXDIGIT_CHARS = frozenset(string.hexdigits)
+TOML_WS: Final = frozenset(" \t")
+TOML_WS_AND_NEWLINE: Final = TOML_WS | frozenset("\n")
+BARE_KEY_CHARS: Final = frozenset(
+    "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789" "-_"
+)
+KEY_INITIAL_CHARS: Final = BARE_KEY_CHARS | frozenset("\"'")
+HEXDIGIT_CHARS: Final = frozenset("abcdef" "ABCDEF" "0123456789")
 
-BASIC_STR_ESCAPE_REPLACEMENTS = MappingProxyType(
+BASIC_STR_ESCAPE_REPLACEMENTS: Final = MappingProxyType(
     {
         "\\b": "\u0008",  # backspace
         "\\t": "\u0009",  # tab
-        "\\n": "\u000A",  # linefeed
-        "\\f": "\u000C",  # form feed
-        "\\r": "\u000D",  # carriage return
+        "\\n": "\u000a",  # linefeed
+        "\\f": "\u000c",  # form feed
+        "\\r": "\u000d",  # carriage return
+        "\\e": "\u001b",  # escape
         '\\"': "\u0022",  # quote
-        "\\\\": "\u005C",  # backslash
+        "\\\\": "\u005c",  # backslash
     }
 )
 
 
+class DEPRECATED_DEFAULT:
+    """Sentinel to be used as default arg during deprecation
+    period of TOMLDecodeError's free-form arguments."""
+
+
 class TOMLDecodeError(ValueError):
-    """An error raised if a document is not valid TOML."""
+    """An error raised if a document is not valid TOML.
+
+    Adds the following attributes to ValueError:
+    msg: The unformatted error message
+    doc: The TOML document being parsed
+    pos: The index of doc where parsing failed
+    lineno: The line corresponding to pos
+    colno: The column corresponding to pos
+    """
 
+    def __init__(
+        self,
+        msg: str | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,
+        doc: str | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,
+        pos: Pos | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,
+        *args: Any,
+    ):
+        if (
+            args
+            or not isinstance(msg, str)
+            or not isinstance(doc, str)
+            or not isinstance(pos, int)
+        ):
+            import warnings
+
+            warnings.warn(
+                "Free-form arguments for TOMLDecodeError are deprecated. "
+                "Please set 'msg' (str), 'doc' (str) and 'pos' (int) arguments only.",
+                DeprecationWarning,
+                stacklevel=2,
+            )
+            if pos is not DEPRECATED_DEFAULT:
+                args = pos, *args
+            if doc is not DEPRECATED_DEFAULT:
+                args = doc, *args
+            if msg is not DEPRECATED_DEFAULT:
+                args = msg, *args
+            ValueError.__init__(self, *args)
+            return
+
+        lineno = doc.count("\n", 0, pos) + 1
+        if lineno == 1:
+            colno = pos + 1
+        else:
+            colno = pos - doc.rindex("\n", 0, pos)
 
-def load(__fp: BinaryIO, *, parse_float: ParseFloat = float) -> dict[str, Any]:
+        if pos >= len(doc):
+            coord_repr = "end of document"
+        else:
+            coord_repr = f"line {lineno}, column {colno}"
+        errmsg = f"{msg} (at {coord_repr})"
+        ValueError.__init__(self, errmsg)
+
+        self.msg = msg
+        self.doc = doc
+        self.pos = pos
+        self.lineno = lineno
+        self.colno = colno
+
+
+def load(__fp: IO[bytes], *, parse_float: ParseFloat = float) -> dict[str, Any]:
     """Parse TOML from a binary file object."""
     b = __fp.read()
     try:
@@ -66,14 +146,19 @@ def load(__fp: BinaryIO, *, parse_float: ParseFloat = float) -> dict[str, Any]:
     return loads(s, parse_float=parse_float)
 
 
-def loads(__s: str, *, parse_float: ParseFloat = float) -> dict[str, Any]:  # noqa: C901
+def loads(__s: str, *, parse_float: ParseFloat = float) -> dict[str, Any]:
     """Parse TOML from a string."""
 
     # The spec allows converting "\r\n" to "\n", even in string
     # literals. Let's do so to simplify parsing.
-    src = __s.replace("\r\n", "\n")
+    try:
+        src = __s.replace("\r\n", "\n")
+    except (AttributeError, TypeError):
+        raise TypeError(
+            f"Expected str object, not '{type(__s).__qualname__}'"
+        ) from None
     pos = 0
-    out = Output(NestedDict(), Flags())
+    out = Output()
     header: Key = ()
     parse_float = make_safe_parse_float(parse_float)
 
@@ -113,7 +198,7 @@ def loads(__s: str, *, parse_float: ParseFloat = float) -> dict[str, Any]:  # no
                 pos, header = create_dict_rule(src, pos, out)
             pos = skip_chars(src, pos, TOML_WS)
         elif char != "#":
-            raise suffixed_err(src, pos, "Invalid statement")
+            raise TOMLDecodeError("Invalid statement", src, pos)
 
         # 3. Skip comment
         pos = skip_comment(src, pos)
@@ -124,8 +209,8 @@ def loads(__s: str, *, parse_float: ParseFloat = float) -> dict[str, Any]:  # no
         except IndexError:
             break
         if char != "\n":
-            raise suffixed_err(
-                src, pos, "Expected newline or end of document after a statement"
+            raise TOMLDecodeError(
+                "Expected newline or end of document after a statement", src, pos
             )
         pos += 1
 
@@ -136,13 +221,13 @@ class Flags:
     """Flags that map to parsed keys/namespaces."""
 
     # Marks an immutable namespace (inline array or inline table).
-    FROZEN = 0
+    FROZEN: Final = 0
     # Marks a nest that has been explicitly created and can no longer
     # be opened using the "[table]" syntax.
-    EXPLICIT_NEST = 1
+    EXPLICIT_NEST: Final = 1
 
     def __init__(self) -> None:
-        self._flags: dict[str, dict] = {}
+        self._flags: dict[str, dict[Any, Any]] = {}
         self._pending_flags: set[tuple[Key, int]] = set()
 
     def add_pending(self, key: Key, flag: int) -> None:
@@ -185,8 +270,8 @@ def is_(self, key: Key, flag: int) -> bool:
             cont = inner_cont["nested"]
         key_stem = key[-1]
         if key_stem in cont:
-            cont = cont[key_stem]
-            return flag in cont["flags"] or flag in cont["recursive_flags"]
+            inner_cont = cont[key_stem]
+            return flag in inner_cont["flags"] or flag in inner_cont["recursive_flags"]
         return False
 
 
@@ -200,7 +285,7 @@ def get_or_create_nest(
         key: Key,
         *,
         access_lists: bool = True,
-    ) -> dict:
+    ) -> dict[str, Any]:
         cont: Any = self.dict
         for k in key:
             if k not in cont:
@@ -210,7 +295,7 @@ def get_or_create_nest(
                 cont = cont[-1]
             if not isinstance(cont, dict):
                 raise KeyError("There is no nest behind this key")
-        return cont
+        return cont  # type: ignore[no-any-return]
 
     def append_nest_to_list(self, key: Key) -> None:
         cont = self.get_or_create_nest(key[:-1])
@@ -224,9 +309,10 @@ def append_nest_to_list(self, key: Key) -> None:
             cont[last_key] = [{}]
 
 
-class Output(NamedTuple):
-    data: NestedDict
-    flags: Flags
+class Output:
+    def __init__(self) -> None:
+        self.data = NestedDict()
+        self.flags = Flags()
 
 
 def skip_chars(src: str, pos: Pos, chars: Iterable[str]) -> Pos:
@@ -251,12 +337,12 @@ def skip_until(
     except ValueError:
         new_pos = len(src)
         if error_on_eof:
-            raise suffixed_err(src, new_pos, f"Expected {expect!r}") from None
+            raise TOMLDecodeError(f"Expected {expect!r}", src, new_pos) from None
 
     if not error_on.isdisjoint(src[pos:new_pos]):
         while src[pos] not in error_on:
             pos += 1
-        raise suffixed_err(src, pos, f"Found invalid character {src[pos]!r}")
+        raise TOMLDecodeError(f"Found invalid character {src[pos]!r}", src, pos)
     return new_pos
 
 
@@ -287,15 +373,17 @@ def create_dict_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:
     pos, key = parse_key(src, pos)
 
     if out.flags.is_(key, Flags.EXPLICIT_NEST) or out.flags.is_(key, Flags.FROZEN):
-        raise suffixed_err(src, pos, f"Cannot declare {key} twice")
+        raise TOMLDecodeError(f"Cannot declare {key} twice", src, pos)
     out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)
     try:
         out.data.get_or_create_nest(key)
     except KeyError:
-        raise suffixed_err(src, pos, "Cannot overwrite a value") from None
+        raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None
 
     if not src.startswith("]", pos):
-        raise suffixed_err(src, pos, "Expected ']' at the end of a table declaration")
+        raise TOMLDecodeError(
+            "Expected ']' at the end of a table declaration", src, pos
+        )
     return pos + 1, key
 
 
@@ -305,7 +393,7 @@ def create_list_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:
     pos, key = parse_key(src, pos)
 
     if out.flags.is_(key, Flags.FROZEN):
-        raise suffixed_err(src, pos, f"Cannot mutate immutable namespace {key}")
+        raise TOMLDecodeError(f"Cannot mutate immutable namespace {key}", src, pos)
     # Free the namespace now that it points to another empty list item...
     out.flags.unset_all(key)
     # ...but this key precisely is still prohibited from table declaration
@@ -313,17 +401,19 @@ def create_list_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:
     try:
         out.data.append_nest_to_list(key)
     except KeyError:
-        raise suffixed_err(src, pos, "Cannot overwrite a value") from None
+        raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None
 
     if not src.startswith("]]", pos):
-        raise suffixed_err(src, pos, "Expected ']]' at the end of an array declaration")
+        raise TOMLDecodeError(
+            "Expected ']]' at the end of an array declaration", src, pos
+        )
     return pos + 2, key
 
 
 def key_value_rule(
     src: str, pos: Pos, out: Output, header: Key, parse_float: ParseFloat
 ) -> Pos:
-    pos, key, value = parse_key_value_pair(src, pos, parse_float)
+    pos, key, value = parse_key_value_pair(src, pos, parse_float, nest_lvl=0)
     key_parent, key_stem = key[:-1], key[-1]
     abs_key_parent = header + key_parent
 
@@ -331,22 +421,22 @@ def key_value_rule(
     for cont_key in relative_path_cont_keys:
         # Check that dotted key syntax does not redefine an existing table
         if out.flags.is_(cont_key, Flags.EXPLICIT_NEST):
-            raise suffixed_err(src, pos, f"Cannot redefine namespace {cont_key}")
+            raise TOMLDecodeError(f"Cannot redefine namespace {cont_key}", src, pos)
         # Containers in the relative path can't be opened with the table syntax or
         # dotted key/value syntax in following table sections.
         out.flags.add_pending(cont_key, Flags.EXPLICIT_NEST)
 
     if out.flags.is_(abs_key_parent, Flags.FROZEN):
-        raise suffixed_err(
-            src, pos, f"Cannot mutate immutable namespace {abs_key_parent}"
+        raise TOMLDecodeError(
+            f"Cannot mutate immutable namespace {abs_key_parent}", src, pos
         )
 
     try:
         nest = out.data.get_or_create_nest(abs_key_parent)
     except KeyError:
-        raise suffixed_err(src, pos, "Cannot overwrite a value") from None
+        raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None
     if key_stem in nest:
-        raise suffixed_err(src, pos, "Cannot overwrite a value")
+        raise TOMLDecodeError("Cannot overwrite a value", src, pos)
     # Mark inline table and array namespaces recursively immutable
     if isinstance(value, (dict, list)):
         out.flags.set(header + key, Flags.FROZEN, recursive=True)
@@ -355,7 +445,7 @@ def key_value_rule(
 
 
 def parse_key_value_pair(
-    src: str, pos: Pos, parse_float: ParseFloat
+    src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int
 ) -> tuple[Pos, Key, Any]:
     pos, key = parse_key(src, pos)
     try:
@@ -363,10 +453,10 @@ def parse_key_value_pair(
     except IndexError:
         char = None
     if char != "=":
-        raise suffixed_err(src, pos, "Expected '=' after a key in a key/value pair")
+        raise TOMLDecodeError("Expected '=' after a key in a key/value pair", src, pos)
     pos += 1
     pos = skip_chars(src, pos, TOML_WS)
-    pos, value = parse_value(src, pos, parse_float)
+    pos, value = parse_value(src, pos, parse_float, nest_lvl)
     return pos, key, value
 
 
@@ -401,7 +491,7 @@ def parse_key_part(src: str, pos: Pos) -> tuple[Pos, str]:
         return parse_literal_str(src, pos)
     if char == '"':
         return parse_one_line_basic_str(src, pos)
-    raise suffixed_err(src, pos, "Invalid initial character for a key part")
+    raise TOMLDecodeError("Invalid initial character for a key part", src, pos)
 
 
 def parse_one_line_basic_str(src: str, pos: Pos) -> tuple[Pos, str]:
@@ -409,15 +499,17 @@ def parse_one_line_basic_str(src: str, pos: Pos) -> tuple[Pos, str]:
     return parse_basic_str(src, pos, multiline=False)
 
 
-def parse_array(src: str, pos: Pos, parse_float: ParseFloat) -> tuple[Pos, list]:
+def parse_array(
+    src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int
+) -> tuple[Pos, list[Any]]:
     pos += 1
-    array: list = []
+    array: list[Any] = []
 
     pos = skip_comments_and_array_ws(src, pos)
     if src.startswith("]", pos):
         return pos + 1, array
     while True:
-        pos, val = parse_value(src, pos, parse_float)
+        pos, val = parse_value(src, pos, parse_float, nest_lvl)
         array.append(val)
         pos = skip_comments_and_array_ws(src, pos)
 
@@ -425,7 +517,7 @@ def parse_array(src: str, pos: Pos, parse_float: ParseFloat) -> tuple[Pos, list]
         if c == "]":
             return pos + 1, array
         if c != ",":
-            raise suffixed_err(src, pos, "Unclosed array")
+            raise TOMLDecodeError("Unclosed array", src, pos)
         pos += 1
 
         pos = skip_comments_and_array_ws(src, pos)
@@ -433,36 +525,40 @@ def parse_array(src: str, pos: Pos, parse_float: ParseFloat) -> tuple[Pos, list]
             return pos + 1, array
 
 
-def parse_inline_table(src: str, pos: Pos, parse_float: ParseFloat) -> tuple[Pos, dict]:
+def parse_inline_table(
+    src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int
+) -> tuple[Pos, dict[str, Any]]:
     pos += 1
     nested_dict = NestedDict()
     flags = Flags()
 
-    pos = skip_chars(src, pos, TOML_WS)
+    pos = skip_comments_and_array_ws(src, pos)
     if src.startswith("}", pos):
         return pos + 1, nested_dict.dict
     while True:
-        pos, key, value = parse_key_value_pair(src, pos, parse_float)
+        pos, key, value = parse_key_value_pair(src, pos, parse_float, nest_lvl)
         key_parent, key_stem = key[:-1], key[-1]
         if flags.is_(key, Flags.FROZEN):
-            raise suffixed_err(src, pos, f"Cannot mutate immutable namespace {key}")
+            raise TOMLDecodeError(f"Cannot mutate immutable namespace {key}", src, pos)
         try:
             nest = nested_dict.get_or_create_nest(key_parent, access_lists=False)
         except KeyError:
-            raise suffixed_err(src, pos, "Cannot overwrite a value") from None
+            raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None
         if key_stem in nest:
-            raise suffixed_err(src, pos, f"Duplicate inline table key {key_stem!r}")
+            raise TOMLDecodeError(f"Duplicate inline table key {key_stem!r}", src, pos)
         nest[key_stem] = value
-        pos = skip_chars(src, pos, TOML_WS)
+        pos = skip_comments_and_array_ws(src, pos)
         c = src[pos : pos + 1]
         if c == "}":
             return pos + 1, nested_dict.dict
         if c != ",":
-            raise suffixed_err(src, pos, "Unclosed inline table")
+            raise TOMLDecodeError("Unclosed inline table", src, pos)
+        pos += 1
+        pos = skip_comments_and_array_ws(src, pos)
+        if src.startswith("}", pos):
+            return pos + 1, nested_dict.dict
         if isinstance(value, (dict, list)):
             flags.set(key, Flags.FROZEN, recursive=True)
-        pos += 1
-        pos = skip_chars(src, pos, TOML_WS)
 
 
 def parse_basic_str_escape(
@@ -480,10 +576,12 @@ def parse_basic_str_escape(
             except IndexError:
                 return pos, ""
             if char != "\n":
-                raise suffixed_err(src, pos, "Unescaped '\\' in a string")
+                raise TOMLDecodeError("Unescaped '\\' in a string", src, pos)
             pos += 1
         pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)
         return pos, ""
+    if escape_id == "\\x":
+        return parse_hex_char(src, pos, 2)
     if escape_id == "\\u":
         return parse_hex_char(src, pos, 4)
     if escape_id == "\\U":
@@ -491,7 +589,7 @@ def parse_basic_str_escape(
     try:
         return pos, BASIC_STR_ESCAPE_REPLACEMENTS[escape_id]
     except KeyError:
-        raise suffixed_err(src, pos, "Unescaped '\\' in a string") from None
+        raise TOMLDecodeError("Unescaped '\\' in a string", src, pos) from None
 
 
 def parse_basic_str_escape_multiline(src: str, pos: Pos) -> tuple[Pos, str]:
@@ -501,11 +599,13 @@ def parse_basic_str_escape_multiline(src: str, pos: Pos) -> tuple[Pos, str]:
 def parse_hex_char(src: str, pos: Pos, hex_len: int) -> tuple[Pos, str]:
     hex_str = src[pos : pos + hex_len]
     if len(hex_str) != hex_len or not HEXDIGIT_CHARS.issuperset(hex_str):
-        raise suffixed_err(src, pos, "Invalid hex value")
+        raise TOMLDecodeError("Invalid hex value", src, pos)
     pos += hex_len
     hex_int = int(hex_str, 16)
     if not is_unicode_scalar_value(hex_int):
-        raise suffixed_err(src, pos, "Escaped character is not a Unicode scalar value")
+        raise TOMLDecodeError(
+            "Escaped character is not a Unicode scalar value", src, pos
+        )
     return pos, chr(hex_int)
 
 
@@ -562,7 +662,7 @@ def parse_basic_str(src: str, pos: Pos, *, multiline: bool) -> tuple[Pos, str]:
         try:
             char = src[pos]
         except IndexError:
-            raise suffixed_err(src, pos, "Unterminated string") from None
+            raise TOMLDecodeError("Unterminated string", src, pos) from None
         if char == '"':
             if not multiline:
                 return pos + 1, result + src[start_pos:pos]
@@ -577,13 +677,21 @@ def parse_basic_str(src: str, pos: Pos, *, multiline: bool) -> tuple[Pos, str]:
             start_pos = pos
             continue
         if char in error_on:
-            raise suffixed_err(src, pos, f"Illegal character {char!r}")
+            raise TOMLDecodeError(f"Illegal character {char!r}", src, pos)
         pos += 1
 
 
-def parse_value(  # noqa: C901
-    src: str, pos: Pos, parse_float: ParseFloat
+def parse_value(
+    src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int
 ) -> tuple[Pos, Any]:
+    if nest_lvl > MAX_INLINE_NESTING:
+        # Pure Python should have raised RecursionError already.
+        # This ensures mypyc binaries eventually do the same.
+        raise RecursionError(  # pragma: no cover
+            "TOML inline arrays/tables are nested more than the allowed"
+            f" {MAX_INLINE_NESTING} levels"
+        )
+
     try:
         char: str | None = src[pos]
     except IndexError:
@@ -613,11 +721,11 @@ def parse_value(  # noqa: C901
 
     # Arrays
     if char == "[":
-        return parse_array(src, pos, parse_float)
+        return parse_array(src, pos, parse_float, nest_lvl + 1)
 
     # Inline tables
     if char == "{":
-        return parse_inline_table(src, pos, parse_float)
+        return parse_inline_table(src, pos, parse_float, nest_lvl + 1)
 
     # Dates and times
     datetime_match = RE_DATETIME.match(src, pos)
@@ -625,7 +733,7 @@ def parse_value(  # noqa: C901
         try:
             datetime_obj = match_to_datetime(datetime_match)
         except ValueError as e:
-            raise suffixed_err(src, pos, "Invalid date or datetime") from e
+            raise TOMLDecodeError("Invalid date or datetime", src, pos) from e
         return datetime_match.end(), datetime_obj
     localtime_match = RE_LOCALTIME.match(src, pos)
     if localtime_match:
@@ -646,24 +754,7 @@ def parse_value(  # noqa: C901
     if first_four in {"-inf", "+inf", "-nan", "+nan"}:
         return pos + 4, parse_float(first_four)
 
-    raise suffixed_err(src, pos, "Invalid value")
-
-
-def suffixed_err(src: str, pos: Pos, msg: str) -> TOMLDecodeError:
-    """Return a `TOMLDecodeError` where error message is suffixed with
-    coordinates in source."""
-
-    def coord_repr(src: str, pos: Pos) -> str:
-        if pos >= len(src):
-            return "end of document"
-        line = src.count("\n", 0, pos) + 1
-        if line == 1:
-            column = pos + 1
-        else:
-            column = pos - src.rindex("\n", 0, pos)
-        return f"line {line}, column {column}"
-
-    return TOMLDecodeError(f"{msg} (at {coord_repr(src, pos)})")
+    raise TOMLDecodeError("Invalid value", src, pos)
 
 
 def is_unicode_scalar_value(codepoint: int) -> bool:
@@ -679,7 +770,7 @@ def make_safe_parse_float(parse_float: ParseFloat) -> ParseFloat:
     instead of returning illegal types.
     """
     # The default `float` callable never returns illegal types. Optimize it.
-    if parse_float is float:  # type: ignore[comparison-overlap]
+    if parse_float is float:
         return float
 
     def safe_parse_float(float_str: str) -> Any:
diff --git a/setuptools/_vendor/tomli/_re.py b/setuptools/_vendor/tomli/_re.py
index 994bb7493f..fc374ed63d 100644
--- a/setuptools/_vendor/tomli/_re.py
+++ b/setuptools/_vendor/tomli/_re.py
@@ -7,16 +7,23 @@
 from datetime import date, datetime, time, timedelta, timezone, tzinfo
 from functools import lru_cache
 import re
-from typing import Any
 
-from ._types import ParseFloat
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+    from typing import Any, Final
 
-# E.g.
-# - 00:32:00.999999
-# - 00:32:00
-_TIME_RE_STR = r"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\.([0-9]{1,6})[0-9]*)?"
+    from ._types import ParseFloat
 
-RE_NUMBER = re.compile(
+_TIME_RE_STR: Final = r"""
+([01][0-9]|2[0-3])             # hours
+:([0-5][0-9])                  # minutes
+(?:
+    :([0-5][0-9])              # optional seconds
+    (?:\.([0-9]{1,6})[0-9]*)?  # optional fractions of a second
+)?
+"""
+
+RE_NUMBER: Final = re.compile(
     r"""
 0
 (?:
@@ -35,8 +42,8 @@
 """,
     flags=re.VERBOSE,
 )
-RE_LOCALTIME = re.compile(_TIME_RE_STR)
-RE_DATETIME = re.compile(
+RE_LOCALTIME: Final = re.compile(_TIME_RE_STR, flags=re.VERBOSE)
+RE_DATETIME: Final = re.compile(
     rf"""
 ([0-9]{{4}})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])  # date, e.g. 1988-10-27
 (?:
@@ -49,7 +56,7 @@
 )
 
 
-def match_to_datetime(match: re.Match) -> datetime | date:
+def match_to_datetime(match: re.Match[str]) -> datetime | date:
     """Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`.
 
     Raises ValueError if the match does not correspond to a valid date
@@ -71,7 +78,8 @@ def match_to_datetime(match: re.Match) -> datetime | date:
     year, month, day = int(year_str), int(month_str), int(day_str)
     if hour_str is None:
         return date(year, month, day)
-    hour, minute, sec = int(hour_str), int(minute_str), int(sec_str)
+    hour, minute = int(hour_str), int(minute_str)
+    sec = int(sec_str) if sec_str else 0
     micros = int(micros_str.ljust(6, "0")) if micros_str else 0
     if offset_sign_str:
         tz: tzinfo | None = cached_tz(
@@ -84,6 +92,9 @@ def match_to_datetime(match: re.Match) -> datetime | date:
     return datetime(year, month, day, hour, minute, sec, micros, tzinfo=tz)
 
 
+# No need to limit cache size. This is only ever called on input
+# that matched RE_DATETIME, so there is an implicit bound of
+# 24 (hours) * 60 (minutes) * 2 (offset direction) = 2880.
 @lru_cache(maxsize=None)
 def cached_tz(hour_str: str, minute_str: str, sign_str: str) -> timezone:
     sign = 1 if sign_str == "+" else -1
@@ -95,13 +106,14 @@ def cached_tz(hour_str: str, minute_str: str, sign_str: str) -> timezone:
     )
 
 
-def match_to_localtime(match: re.Match) -> time:
+def match_to_localtime(match: re.Match[str]) -> time:
     hour_str, minute_str, sec_str, micros_str = match.groups()
+    sec = int(sec_str) if sec_str else 0
     micros = int(micros_str.ljust(6, "0")) if micros_str else 0
-    return time(int(hour_str), int(minute_str), int(sec_str), micros)
+    return time(int(hour_str), int(minute_str), sec, micros)
 
 
-def match_to_number(match: re.Match, parse_float: ParseFloat) -> Any:
+def match_to_number(match: re.Match[str], parse_float: ParseFloat) -> Any:
     if match.group("floatpart"):
         return parse_float(match.group())
     return int(match.group(), 0)
diff --git a/setuptools/_vendor/typing_extensions-4.0.1.dist-info/INSTALLER b/setuptools/_vendor/typing_extensions-4.0.1.dist-info/INSTALLER
deleted file mode 100644
index a1b589e38a..0000000000
--- a/setuptools/_vendor/typing_extensions-4.0.1.dist-info/INSTALLER
+++ /dev/null
@@ -1 +0,0 @@
-pip
diff --git a/setuptools/_vendor/typing_extensions-4.0.1.dist-info/LICENSE b/setuptools/_vendor/typing_extensions-4.0.1.dist-info/LICENSE
deleted file mode 100644
index 583f9f6e61..0000000000
--- a/setuptools/_vendor/typing_extensions-4.0.1.dist-info/LICENSE
+++ /dev/null
@@ -1,254 +0,0 @@
-A. HISTORY OF THE SOFTWARE
-==========================
-
-Python was created in the early 1990s by Guido van Rossum at Stichting
-Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
-as a successor of a language called ABC.  Guido remains Python's
-principal author, although it includes many contributions from others.
-
-In 1995, Guido continued his work on Python at the Corporation for
-National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
-in Reston, Virginia where he released several versions of the
-software.
-
-In May 2000, Guido and the Python core development team moved to
-BeOpen.com to form the BeOpen PythonLabs team.  In October of the same
-year, the PythonLabs team moved to Digital Creations (now Zope
-Corporation, see http://www.zope.com).  In 2001, the Python Software
-Foundation (PSF, see http://www.python.org/psf/) was formed, a
-non-profit organization created specifically to own Python-related
-Intellectual Property.  Zope Corporation is a sponsoring member of
-the PSF.
-
-All Python releases are Open Source (see http://www.opensource.org for
-the Open Source Definition).  Historically, most, but not all, Python
-releases have also been GPL-compatible; the table below summarizes
-the various releases.
-
-    Release         Derived     Year        Owner       GPL-
-                    from                                compatible? (1)
-
-    0.9.0 thru 1.2              1991-1995   CWI         yes
-    1.3 thru 1.5.2  1.2         1995-1999   CNRI        yes
-    1.6             1.5.2       2000        CNRI        no
-    2.0             1.6         2000        BeOpen.com  no
-    1.6.1           1.6         2001        CNRI        yes (2)
-    2.1             2.0+1.6.1   2001        PSF         no
-    2.0.1           2.0+1.6.1   2001        PSF         yes
-    2.1.1           2.1+2.0.1   2001        PSF         yes
-    2.1.2           2.1.1       2002        PSF         yes
-    2.1.3           2.1.2       2002        PSF         yes
-    2.2 and above   2.1.1       2001-now    PSF         yes
-
-Footnotes:
-
-(1) GPL-compatible doesn't mean that we're distributing Python under
-    the GPL.  All Python licenses, unlike the GPL, let you distribute
-    a modified version without making your changes open source.  The
-    GPL-compatible licenses make it possible to combine Python with
-    other software that is released under the GPL; the others don't.
-
-(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
-    because its license has a choice of law clause.  According to
-    CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
-    is "not incompatible" with the GPL.
-
-Thanks to the many outside volunteers who have worked under Guido's
-direction to make these releases possible.
-
-
-B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
-===============================================================
-
-PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
---------------------------------------------
-
-1. This LICENSE AGREEMENT is between the Python Software Foundation
-("PSF"), and the Individual or Organization ("Licensee") accessing and
-otherwise using this software ("Python") in source or binary form and
-its associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement, PSF hereby
-grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
-analyze, test, perform and/or display publicly, prepare derivative works,
-distribute, and otherwise use Python alone or in any derivative version,
-provided, however, that PSF's License Agreement and PSF's notice of copyright,
-i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
-2011, 2012, 2013, 2014 Python Software Foundation; All Rights Reserved" are
-retained in Python alone or in any derivative version prepared by Licensee.
-
-3. In the event Licensee prepares a derivative work that is based on
-or incorporates Python or any part thereof, and wants to make
-the derivative work available to others as provided herein, then
-Licensee hereby agrees to include in any such work a brief summary of
-the changes made to Python.
-
-4. PSF is making Python available to Licensee on an "AS IS"
-basis.  PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
-IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
-DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
-INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
-FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
-A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
-OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-7. Nothing in this License Agreement shall be deemed to create any
-relationship of agency, partnership, or joint venture between PSF and
-Licensee.  This License Agreement does not grant permission to use PSF
-trademarks or trade name in a trademark sense to endorse or promote
-products or services of Licensee, or any third party.
-
-8. By copying, installing or otherwise using Python, Licensee
-agrees to be bound by the terms and conditions of this License
-Agreement.
-
-
-BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
--------------------------------------------
-
-BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
-
-1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
-office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
-Individual or Organization ("Licensee") accessing and otherwise using
-this software in source or binary form and its associated
-documentation ("the Software").
-
-2. Subject to the terms and conditions of this BeOpen Python License
-Agreement, BeOpen hereby grants Licensee a non-exclusive,
-royalty-free, world-wide license to reproduce, analyze, test, perform
-and/or display publicly, prepare derivative works, distribute, and
-otherwise use the Software alone or in any derivative version,
-provided, however, that the BeOpen Python License is retained in the
-Software, alone or in any derivative version prepared by Licensee.
-
-3. BeOpen is making the Software available to Licensee on an "AS IS"
-basis.  BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
-IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
-DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
-INFRINGE ANY THIRD PARTY RIGHTS.
-
-4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
-SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
-AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
-DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-5. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-6. This License Agreement shall be governed by and interpreted in all
-respects by the law of the State of California, excluding conflict of
-law provisions.  Nothing in this License Agreement shall be deemed to
-create any relationship of agency, partnership, or joint venture
-between BeOpen and Licensee.  This License Agreement does not grant
-permission to use BeOpen trademarks or trade names in a trademark
-sense to endorse or promote products or services of Licensee, or any
-third party.  As an exception, the "BeOpen Python" logos available at
-http://www.pythonlabs.com/logos.html may be used according to the
-permissions granted on that web page.
-
-7. By copying, installing or otherwise using the software, Licensee
-agrees to be bound by the terms and conditions of this License
-Agreement.
-
-
-CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
----------------------------------------
-
-1. This LICENSE AGREEMENT is between the Corporation for National
-Research Initiatives, having an office at 1895 Preston White Drive,
-Reston, VA 20191 ("CNRI"), and the Individual or Organization
-("Licensee") accessing and otherwise using Python 1.6.1 software in
-source or binary form and its associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement, CNRI
-hereby grants Licensee a nonexclusive, royalty-free, world-wide
-license to reproduce, analyze, test, perform and/or display publicly,
-prepare derivative works, distribute, and otherwise use Python 1.6.1
-alone or in any derivative version, provided, however, that CNRI's
-License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
-1995-2001 Corporation for National Research Initiatives; All Rights
-Reserved" are retained in Python 1.6.1 alone or in any derivative
-version prepared by Licensee.  Alternately, in lieu of CNRI's License
-Agreement, Licensee may substitute the following text (omitting the
-quotes): "Python 1.6.1 is made available subject to the terms and
-conditions in CNRI's License Agreement.  This Agreement together with
-Python 1.6.1 may be located on the Internet using the following
-unique, persistent identifier (known as a handle): 1895.22/1013.  This
-Agreement may also be obtained from a proxy server on the Internet
-using the following URL: http://hdl.handle.net/1895.22/1013".
-
-3. In the event Licensee prepares a derivative work that is based on
-or incorporates Python 1.6.1 or any part thereof, and wants to make
-the derivative work available to others as provided herein, then
-Licensee hereby agrees to include in any such work a brief summary of
-the changes made to Python 1.6.1.
-
-4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
-basis.  CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
-IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
-DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
-INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
-1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
-A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
-OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-7. This License Agreement shall be governed by the federal
-intellectual property law of the United States, including without
-limitation the federal copyright law, and, to the extent such
-U.S. federal law does not apply, by the law of the Commonwealth of
-Virginia, excluding Virginia's conflict of law provisions.
-Notwithstanding the foregoing, with regard to derivative works based
-on Python 1.6.1 that incorporate non-separable material that was
-previously distributed under the GNU General Public License (GPL), the
-law of the Commonwealth of Virginia shall govern this License
-Agreement only as to issues arising under or with respect to
-Paragraphs 4, 5, and 7 of this License Agreement.  Nothing in this
-License Agreement shall be deemed to create any relationship of
-agency, partnership, or joint venture between CNRI and Licensee.  This
-License Agreement does not grant permission to use CNRI trademarks or
-trade name in a trademark sense to endorse or promote products or
-services of Licensee, or any third party.
-
-8. By clicking on the "ACCEPT" button where indicated, or by copying,
-installing or otherwise using Python 1.6.1, Licensee agrees to be
-bound by the terms and conditions of this License Agreement.
-
-        ACCEPT
-
-
-CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
---------------------------------------------------
-
-Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
-The Netherlands.  All rights reserved.
-
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose and without fee is hereby granted,
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in
-supporting documentation, and that the name of Stichting Mathematisch
-Centrum or CWI not be used in advertising or publicity pertaining to
-distribution of the software without specific, written prior
-permission.
-
-STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
-THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
-FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
-OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/setuptools/_vendor/typing_extensions-4.0.1.dist-info/METADATA b/setuptools/_vendor/typing_extensions-4.0.1.dist-info/METADATA
deleted file mode 100644
index fe10dfd02a..0000000000
--- a/setuptools/_vendor/typing_extensions-4.0.1.dist-info/METADATA
+++ /dev/null
@@ -1,35 +0,0 @@
-Metadata-Version: 2.1
-Name: typing_extensions
-Version: 4.0.1
-Summary: Backported and Experimental Type Hints for Python 3.6+
-Keywords: annotations,backport,checker,checking,function,hinting,hints,type,typechecking,typehinting,typehints,typing
-Author-email: "Guido van Rossum, Jukka Lehtosalo, Łukasz Langa, Michael Lee" 
-Requires-Python: >=3.6
-Description-Content-Type: text/x-rst
-Classifier: Development Status :: 3 - Alpha
-Classifier: Environment :: Console
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: Python Software Foundation License
-Classifier: Operating System :: OS Independent
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3 :: Only
-Classifier: Programming Language :: Python :: 3.6
-Classifier: Programming Language :: Python :: 3.7
-Classifier: Programming Language :: Python :: 3.8
-Classifier: Programming Language :: Python :: 3.9
-Classifier: Programming Language :: Python :: 3.10
-Classifier: Topic :: Software Development
-Project-URL: Home, https://github.com/python/typing/blob/master/typing_extensions/README.rst
-
-Typing Extensions -- Backported and Experimental Type Hints for Python
-
-The ``typing`` module was added to the standard library in Python 3.5, but
-many new features have been added to the module since then.
-This means users of older Python versions who are unable to upgrade will not be
-able to take advantage of new types added to the ``typing`` module, such as
-``typing.Protocol`` or ``typing.TypedDict``.
-
-The ``typing_extensions`` module contains backports of these changes.
-Experimental types that may eventually be added to the ``typing``
-module are also included in ``typing_extensions``.
-
diff --git a/setuptools/_vendor/typing_extensions-4.0.1.dist-info/RECORD b/setuptools/_vendor/typing_extensions-4.0.1.dist-info/RECORD
deleted file mode 100644
index 786de8542d..0000000000
--- a/setuptools/_vendor/typing_extensions-4.0.1.dist-info/RECORD
+++ /dev/null
@@ -1,8 +0,0 @@
-__pycache__/typing_extensions.cpython-311.pyc,,
-typing_extensions-4.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-typing_extensions-4.0.1.dist-info/LICENSE,sha256=_xfOlOECAk3raHc-scx0ynbaTmWPNzUx8Kwi1oprsa0,12755
-typing_extensions-4.0.1.dist-info/METADATA,sha256=iZ_5HONZZBXtF4kroz-IPZYIl9M8IE1B00R82dWcBqE,1736
-typing_extensions-4.0.1.dist-info/RECORD,,
-typing_extensions-4.0.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-typing_extensions-4.0.1.dist-info/WHEEL,sha256=LVOPL_YDMEiGvRLgDK1hLkfhFCnTcxcAYZJtpNFses0,81
-typing_extensions.py,sha256=1uqi_RSlI7gos4eJB_NEV3d5wQwzTUQHd3_jrkbTo8Q,87149
diff --git a/setuptools/_vendor/typing_extensions-4.0.1.dist-info/REQUESTED b/setuptools/_vendor/typing_extensions-4.0.1.dist-info/REQUESTED
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/setuptools/_vendor/typing_extensions-4.0.1.dist-info/WHEEL b/setuptools/_vendor/typing_extensions-4.0.1.dist-info/WHEEL
deleted file mode 100644
index 884ceb565c..0000000000
--- a/setuptools/_vendor/typing_extensions-4.0.1.dist-info/WHEEL
+++ /dev/null
@@ -1,4 +0,0 @@
-Wheel-Version: 1.0
-Generator: flit 3.5.1
-Root-Is-Purelib: true
-Tag: py3-none-any
diff --git a/setuptools/_vendor/typing_extensions.py b/setuptools/_vendor/typing_extensions.py
deleted file mode 100644
index 9f1c7aa31e..0000000000
--- a/setuptools/_vendor/typing_extensions.py
+++ /dev/null
@@ -1,2296 +0,0 @@
-import abc
-import collections
-import collections.abc
-import operator
-import sys
-import typing
-
-# After PEP 560, internal typing API was substantially reworked.
-# This is especially important for Protocol class which uses internal APIs
-# quite extensively.
-PEP_560 = sys.version_info[:3] >= (3, 7, 0)
-
-if PEP_560:
-    GenericMeta = type
-else:
-    # 3.6
-    from typing import GenericMeta, _type_vars  # noqa
-
-# The two functions below are copies of typing internal helpers.
-# They are needed by _ProtocolMeta
-
-
-def _no_slots_copy(dct):
-    dict_copy = dict(dct)
-    if '__slots__' in dict_copy:
-        for slot in dict_copy['__slots__']:
-            dict_copy.pop(slot, None)
-    return dict_copy
-
-
-def _check_generic(cls, parameters):
-    if not cls.__parameters__:
-        raise TypeError(f"{cls} is not a generic class")
-    alen = len(parameters)
-    elen = len(cls.__parameters__)
-    if alen != elen:
-        raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments for {cls};"
-                        f" actual {alen}, expected {elen}")
-
-
-# Please keep __all__ alphabetized within each category.
-__all__ = [
-    # Super-special typing primitives.
-    'ClassVar',
-    'Concatenate',
-    'Final',
-    'ParamSpec',
-    'Self',
-    'Type',
-
-    # ABCs (from collections.abc).
-    'Awaitable',
-    'AsyncIterator',
-    'AsyncIterable',
-    'Coroutine',
-    'AsyncGenerator',
-    'AsyncContextManager',
-    'ChainMap',
-
-    # Concrete collection types.
-    'ContextManager',
-    'Counter',
-    'Deque',
-    'DefaultDict',
-    'OrderedDict',
-    'TypedDict',
-
-    # Structural checks, a.k.a. protocols.
-    'SupportsIndex',
-
-    # One-off things.
-    'Annotated',
-    'final',
-    'IntVar',
-    'Literal',
-    'NewType',
-    'overload',
-    'Protocol',
-    'runtime',
-    'runtime_checkable',
-    'Text',
-    'TypeAlias',
-    'TypeGuard',
-    'TYPE_CHECKING',
-]
-
-if PEP_560:
-    __all__.extend(["get_args", "get_origin", "get_type_hints"])
-
-# 3.6.2+
-if hasattr(typing, 'NoReturn'):
-    NoReturn = typing.NoReturn
-# 3.6.0-3.6.1
-else:
-    class _NoReturn(typing._FinalTypingBase, _root=True):
-        """Special type indicating functions that never return.
-        Example::
-
-          from typing import NoReturn
-
-          def stop() -> NoReturn:
-              raise Exception('no way')
-
-        This type is invalid in other positions, e.g., ``List[NoReturn]``
-        will fail in static type checkers.
-        """
-        __slots__ = ()
-
-        def __instancecheck__(self, obj):
-            raise TypeError("NoReturn cannot be used with isinstance().")
-
-        def __subclasscheck__(self, cls):
-            raise TypeError("NoReturn cannot be used with issubclass().")
-
-    NoReturn = _NoReturn(_root=True)
-
-# Some unconstrained type variables.  These are used by the container types.
-# (These are not for export.)
-T = typing.TypeVar('T')  # Any type.
-KT = typing.TypeVar('KT')  # Key type.
-VT = typing.TypeVar('VT')  # Value type.
-T_co = typing.TypeVar('T_co', covariant=True)  # Any type covariant containers.
-T_contra = typing.TypeVar('T_contra', contravariant=True)  # Ditto contravariant.
-
-ClassVar = typing.ClassVar
-
-# On older versions of typing there is an internal class named "Final".
-# 3.8+
-if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7):
-    Final = typing.Final
-# 3.7
-elif sys.version_info[:2] >= (3, 7):
-    class _FinalForm(typing._SpecialForm, _root=True):
-
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-        def __getitem__(self, parameters):
-            item = typing._type_check(parameters,
-                                      f'{self._name} accepts only single type')
-            return typing._GenericAlias(self, (item,))
-
-    Final = _FinalForm('Final',
-                       doc="""A special typing construct to indicate that a name
-                       cannot be re-assigned or overridden in a subclass.
-                       For example:
-
-                           MAX_SIZE: Final = 9000
-                           MAX_SIZE += 1  # Error reported by type checker
-
-                           class Connection:
-                               TIMEOUT: Final[int] = 10
-                           class FastConnector(Connection):
-                               TIMEOUT = 1  # Error reported by type checker
-
-                       There is no runtime checking of these properties.""")
-# 3.6
-else:
-    class _Final(typing._FinalTypingBase, _root=True):
-        """A special typing construct to indicate that a name
-        cannot be re-assigned or overridden in a subclass.
-        For example:
-
-            MAX_SIZE: Final = 9000
-            MAX_SIZE += 1  # Error reported by type checker
-
-            class Connection:
-                TIMEOUT: Final[int] = 10
-            class FastConnector(Connection):
-                TIMEOUT = 1  # Error reported by type checker
-
-        There is no runtime checking of these properties.
-        """
-
-        __slots__ = ('__type__',)
-
-        def __init__(self, tp=None, **kwds):
-            self.__type__ = tp
-
-        def __getitem__(self, item):
-            cls = type(self)
-            if self.__type__ is None:
-                return cls(typing._type_check(item,
-                           f'{cls.__name__[1:]} accepts only single type.'),
-                           _root=True)
-            raise TypeError(f'{cls.__name__[1:]} cannot be further subscripted')
-
-        def _eval_type(self, globalns, localns):
-            new_tp = typing._eval_type(self.__type__, globalns, localns)
-            if new_tp == self.__type__:
-                return self
-            return type(self)(new_tp, _root=True)
-
-        def __repr__(self):
-            r = super().__repr__()
-            if self.__type__ is not None:
-                r += f'[{typing._type_repr(self.__type__)}]'
-            return r
-
-        def __hash__(self):
-            return hash((type(self).__name__, self.__type__))
-
-        def __eq__(self, other):
-            if not isinstance(other, _Final):
-                return NotImplemented
-            if self.__type__ is not None:
-                return self.__type__ == other.__type__
-            return self is other
-
-    Final = _Final(_root=True)
-
-
-# 3.8+
-if hasattr(typing, 'final'):
-    final = typing.final
-# 3.6-3.7
-else:
-    def final(f):
-        """This decorator can be used to indicate to type checkers that
-        the decorated method cannot be overridden, and decorated class
-        cannot be subclassed. For example:
-
-            class Base:
-                @final
-                def done(self) -> None:
-                    ...
-            class Sub(Base):
-                def done(self) -> None:  # Error reported by type checker
-                    ...
-            @final
-            class Leaf:
-                ...
-            class Other(Leaf):  # Error reported by type checker
-                ...
-
-        There is no runtime checking of these properties.
-        """
-        return f
-
-
-def IntVar(name):
-    return typing.TypeVar(name)
-
-
-# 3.8+:
-if hasattr(typing, 'Literal'):
-    Literal = typing.Literal
-# 3.7:
-elif sys.version_info[:2] >= (3, 7):
-    class _LiteralForm(typing._SpecialForm, _root=True):
-
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-        def __getitem__(self, parameters):
-            return typing._GenericAlias(self, parameters)
-
-    Literal = _LiteralForm('Literal',
-                           doc="""A type that can be used to indicate to type checkers
-                           that the corresponding value has a value literally equivalent
-                           to the provided parameter. For example:
-
-                               var: Literal[4] = 4
-
-                           The type checker understands that 'var' is literally equal to
-                           the value 4 and no other value.
-
-                           Literal[...] cannot be subclassed. There is no runtime
-                           checking verifying that the parameter is actually a value
-                           instead of a type.""")
-# 3.6:
-else:
-    class _Literal(typing._FinalTypingBase, _root=True):
-        """A type that can be used to indicate to type checkers that the
-        corresponding value has a value literally equivalent to the
-        provided parameter. For example:
-
-            var: Literal[4] = 4
-
-        The type checker understands that 'var' is literally equal to the
-        value 4 and no other value.
-
-        Literal[...] cannot be subclassed. There is no runtime checking
-        verifying that the parameter is actually a value instead of a type.
-        """
-
-        __slots__ = ('__values__',)
-
-        def __init__(self, values=None, **kwds):
-            self.__values__ = values
-
-        def __getitem__(self, values):
-            cls = type(self)
-            if self.__values__ is None:
-                if not isinstance(values, tuple):
-                    values = (values,)
-                return cls(values, _root=True)
-            raise TypeError(f'{cls.__name__[1:]} cannot be further subscripted')
-
-        def _eval_type(self, globalns, localns):
-            return self
-
-        def __repr__(self):
-            r = super().__repr__()
-            if self.__values__ is not None:
-                r += f'[{", ".join(map(typing._type_repr, self.__values__))}]'
-            return r
-
-        def __hash__(self):
-            return hash((type(self).__name__, self.__values__))
-
-        def __eq__(self, other):
-            if not isinstance(other, _Literal):
-                return NotImplemented
-            if self.__values__ is not None:
-                return self.__values__ == other.__values__
-            return self is other
-
-    Literal = _Literal(_root=True)
-
-
-_overload_dummy = typing._overload_dummy  # noqa
-overload = typing.overload
-
-
-# This is not a real generic class.  Don't use outside annotations.
-Type = typing.Type
-
-# Various ABCs mimicking those in collections.abc.
-# A few are simply re-exported for completeness.
-
-
-class _ExtensionsGenericMeta(GenericMeta):
-    def __subclasscheck__(self, subclass):
-        """This mimics a more modern GenericMeta.__subclasscheck__() logic
-        (that does not have problems with recursion) to work around interactions
-        between collections, typing, and typing_extensions on older
-        versions of Python, see https://github.com/python/typing/issues/501.
-        """
-        if self.__origin__ is not None:
-            if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']:
-                raise TypeError("Parameterized generics cannot be used with class "
-                                "or instance checks")
-            return False
-        if not self.__extra__:
-            return super().__subclasscheck__(subclass)
-        res = self.__extra__.__subclasshook__(subclass)
-        if res is not NotImplemented:
-            return res
-        if self.__extra__ in subclass.__mro__:
-            return True
-        for scls in self.__extra__.__subclasses__():
-            if isinstance(scls, GenericMeta):
-                continue
-            if issubclass(subclass, scls):
-                return True
-        return False
-
-
-Awaitable = typing.Awaitable
-Coroutine = typing.Coroutine
-AsyncIterable = typing.AsyncIterable
-AsyncIterator = typing.AsyncIterator
-
-# 3.6.1+
-if hasattr(typing, 'Deque'):
-    Deque = typing.Deque
-# 3.6.0
-else:
-    class Deque(collections.deque, typing.MutableSequence[T],
-                metaclass=_ExtensionsGenericMeta,
-                extra=collections.deque):
-        __slots__ = ()
-
-        def __new__(cls, *args, **kwds):
-            if cls._gorg is Deque:
-                return collections.deque(*args, **kwds)
-            return typing._generic_new(collections.deque, cls, *args, **kwds)
-
-ContextManager = typing.ContextManager
-# 3.6.2+
-if hasattr(typing, 'AsyncContextManager'):
-    AsyncContextManager = typing.AsyncContextManager
-# 3.6.0-3.6.1
-else:
-    from _collections_abc import _check_methods as _check_methods_in_mro  # noqa
-
-    class AsyncContextManager(typing.Generic[T_co]):
-        __slots__ = ()
-
-        async def __aenter__(self):
-            return self
-
-        @abc.abstractmethod
-        async def __aexit__(self, exc_type, exc_value, traceback):
-            return None
-
-        @classmethod
-        def __subclasshook__(cls, C):
-            if cls is AsyncContextManager:
-                return _check_methods_in_mro(C, "__aenter__", "__aexit__")
-            return NotImplemented
-
-DefaultDict = typing.DefaultDict
-
-# 3.7.2+
-if hasattr(typing, 'OrderedDict'):
-    OrderedDict = typing.OrderedDict
-# 3.7.0-3.7.2
-elif (3, 7, 0) <= sys.version_info[:3] < (3, 7, 2):
-    OrderedDict = typing._alias(collections.OrderedDict, (KT, VT))
-# 3.6
-else:
-    class OrderedDict(collections.OrderedDict, typing.MutableMapping[KT, VT],
-                      metaclass=_ExtensionsGenericMeta,
-                      extra=collections.OrderedDict):
-
-        __slots__ = ()
-
-        def __new__(cls, *args, **kwds):
-            if cls._gorg is OrderedDict:
-                return collections.OrderedDict(*args, **kwds)
-            return typing._generic_new(collections.OrderedDict, cls, *args, **kwds)
-
-# 3.6.2+
-if hasattr(typing, 'Counter'):
-    Counter = typing.Counter
-# 3.6.0-3.6.1
-else:
-    class Counter(collections.Counter,
-                  typing.Dict[T, int],
-                  metaclass=_ExtensionsGenericMeta, extra=collections.Counter):
-
-        __slots__ = ()
-
-        def __new__(cls, *args, **kwds):
-            if cls._gorg is Counter:
-                return collections.Counter(*args, **kwds)
-            return typing._generic_new(collections.Counter, cls, *args, **kwds)
-
-# 3.6.1+
-if hasattr(typing, 'ChainMap'):
-    ChainMap = typing.ChainMap
-elif hasattr(collections, 'ChainMap'):
-    class ChainMap(collections.ChainMap, typing.MutableMapping[KT, VT],
-                   metaclass=_ExtensionsGenericMeta,
-                   extra=collections.ChainMap):
-
-        __slots__ = ()
-
-        def __new__(cls, *args, **kwds):
-            if cls._gorg is ChainMap:
-                return collections.ChainMap(*args, **kwds)
-            return typing._generic_new(collections.ChainMap, cls, *args, **kwds)
-
-# 3.6.1+
-if hasattr(typing, 'AsyncGenerator'):
-    AsyncGenerator = typing.AsyncGenerator
-# 3.6.0
-else:
-    class AsyncGenerator(AsyncIterator[T_co], typing.Generic[T_co, T_contra],
-                         metaclass=_ExtensionsGenericMeta,
-                         extra=collections.abc.AsyncGenerator):
-        __slots__ = ()
-
-NewType = typing.NewType
-Text = typing.Text
-TYPE_CHECKING = typing.TYPE_CHECKING
-
-
-def _gorg(cls):
-    """This function exists for compatibility with old typing versions."""
-    assert isinstance(cls, GenericMeta)
-    if hasattr(cls, '_gorg'):
-        return cls._gorg
-    while cls.__origin__ is not None:
-        cls = cls.__origin__
-    return cls
-
-
-_PROTO_WHITELIST = ['Callable', 'Awaitable',
-                    'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator',
-                    'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
-                    'ContextManager', 'AsyncContextManager']
-
-
-def _get_protocol_attrs(cls):
-    attrs = set()
-    for base in cls.__mro__[:-1]:  # without object
-        if base.__name__ in ('Protocol', 'Generic'):
-            continue
-        annotations = getattr(base, '__annotations__', {})
-        for attr in list(base.__dict__.keys()) + list(annotations.keys()):
-            if (not attr.startswith('_abc_') and attr not in (
-                    '__abstractmethods__', '__annotations__', '__weakref__',
-                    '_is_protocol', '_is_runtime_protocol', '__dict__',
-                    '__args__', '__slots__',
-                    '__next_in_mro__', '__parameters__', '__origin__',
-                    '__orig_bases__', '__extra__', '__tree_hash__',
-                    '__doc__', '__subclasshook__', '__init__', '__new__',
-                    '__module__', '_MutableMapping__marker', '_gorg')):
-                attrs.add(attr)
-    return attrs
-
-
-def _is_callable_members_only(cls):
-    return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))
-
-
-# 3.8+
-if hasattr(typing, 'Protocol'):
-    Protocol = typing.Protocol
-# 3.7
-elif PEP_560:
-    from typing import _collect_type_vars  # noqa
-
-    def _no_init(self, *args, **kwargs):
-        if type(self)._is_protocol:
-            raise TypeError('Protocols cannot be instantiated')
-
-    class _ProtocolMeta(abc.ABCMeta):
-        # This metaclass is a bit unfortunate and exists only because of the lack
-        # of __instancehook__.
-        def __instancecheck__(cls, instance):
-            # We need this method for situations where attributes are
-            # assigned in __init__.
-            if ((not getattr(cls, '_is_protocol', False) or
-                 _is_callable_members_only(cls)) and
-                    issubclass(instance.__class__, cls)):
-                return True
-            if cls._is_protocol:
-                if all(hasattr(instance, attr) and
-                       (not callable(getattr(cls, attr, None)) or
-                        getattr(instance, attr) is not None)
-                       for attr in _get_protocol_attrs(cls)):
-                    return True
-            return super().__instancecheck__(instance)
-
-    class Protocol(metaclass=_ProtocolMeta):
-        # There is quite a lot of overlapping code with typing.Generic.
-        # Unfortunately it is hard to avoid this while these live in two different
-        # modules. The duplicated code will be removed when Protocol is moved to typing.
-        """Base class for protocol classes. Protocol classes are defined as::
-
-            class Proto(Protocol):
-                def meth(self) -> int:
-                    ...
-
-        Such classes are primarily used with static type checkers that recognize
-        structural subtyping (static duck-typing), for example::
-
-            class C:
-                def meth(self) -> int:
-                    return 0
-
-            def func(x: Proto) -> int:
-                return x.meth()
-
-            func(C())  # Passes static type check
-
-        See PEP 544 for details. Protocol classes decorated with
-        @typing_extensions.runtime act as simple-minded runtime protocol that checks
-        only the presence of given attributes, ignoring their type signatures.
-
-        Protocol classes can be generic, they are defined as::
-
-            class GenProto(Protocol[T]):
-                def meth(self) -> T:
-                    ...
-        """
-        __slots__ = ()
-        _is_protocol = True
-
-        def __new__(cls, *args, **kwds):
-            if cls is Protocol:
-                raise TypeError("Type Protocol cannot be instantiated; "
-                                "it can only be used as a base class")
-            return super().__new__(cls)
-
-        @typing._tp_cache
-        def __class_getitem__(cls, params):
-            if not isinstance(params, tuple):
-                params = (params,)
-            if not params and cls is not typing.Tuple:
-                raise TypeError(
-                    f"Parameter list to {cls.__qualname__}[...] cannot be empty")
-            msg = "Parameters to generic types must be types."
-            params = tuple(typing._type_check(p, msg) for p in params)  # noqa
-            if cls is Protocol:
-                # Generic can only be subscripted with unique type variables.
-                if not all(isinstance(p, typing.TypeVar) for p in params):
-                    i = 0
-                    while isinstance(params[i], typing.TypeVar):
-                        i += 1
-                    raise TypeError(
-                        "Parameters to Protocol[...] must all be type variables."
-                        f" Parameter {i + 1} is {params[i]}")
-                if len(set(params)) != len(params):
-                    raise TypeError(
-                        "Parameters to Protocol[...] must all be unique")
-            else:
-                # Subscripting a regular Generic subclass.
-                _check_generic(cls, params)
-            return typing._GenericAlias(cls, params)
-
-        def __init_subclass__(cls, *args, **kwargs):
-            tvars = []
-            if '__orig_bases__' in cls.__dict__:
-                error = typing.Generic in cls.__orig_bases__
-            else:
-                error = typing.Generic in cls.__bases__
-            if error:
-                raise TypeError("Cannot inherit from plain Generic")
-            if '__orig_bases__' in cls.__dict__:
-                tvars = _collect_type_vars(cls.__orig_bases__)
-                # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn].
-                # If found, tvars must be a subset of it.
-                # If not found, tvars is it.
-                # Also check for and reject plain Generic,
-                # and reject multiple Generic[...] and/or Protocol[...].
-                gvars = None
-                for base in cls.__orig_bases__:
-                    if (isinstance(base, typing._GenericAlias) and
-                            base.__origin__ in (typing.Generic, Protocol)):
-                        # for error messages
-                        the_base = base.__origin__.__name__
-                        if gvars is not None:
-                            raise TypeError(
-                                "Cannot inherit from Generic[...]"
-                                " and/or Protocol[...] multiple types.")
-                        gvars = base.__parameters__
-                if gvars is None:
-                    gvars = tvars
-                else:
-                    tvarset = set(tvars)
-                    gvarset = set(gvars)
-                    if not tvarset <= gvarset:
-                        s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
-                        s_args = ', '.join(str(g) for g in gvars)
-                        raise TypeError(f"Some type variables ({s_vars}) are"
-                                        f" not listed in {the_base}[{s_args}]")
-                    tvars = gvars
-            cls.__parameters__ = tuple(tvars)
-
-            # Determine if this is a protocol or a concrete subclass.
-            if not cls.__dict__.get('_is_protocol', None):
-                cls._is_protocol = any(b is Protocol for b in cls.__bases__)
-
-            # Set (or override) the protocol subclass hook.
-            def _proto_hook(other):
-                if not cls.__dict__.get('_is_protocol', None):
-                    return NotImplemented
-                if not getattr(cls, '_is_runtime_protocol', False):
-                    if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
-                        return NotImplemented
-                    raise TypeError("Instance and class checks can only be used with"
-                                    " @runtime protocols")
-                if not _is_callable_members_only(cls):
-                    if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
-                        return NotImplemented
-                    raise TypeError("Protocols with non-method members"
-                                    " don't support issubclass()")
-                if not isinstance(other, type):
-                    # Same error as for issubclass(1, int)
-                    raise TypeError('issubclass() arg 1 must be a class')
-                for attr in _get_protocol_attrs(cls):
-                    for base in other.__mro__:
-                        if attr in base.__dict__:
-                            if base.__dict__[attr] is None:
-                                return NotImplemented
-                            break
-                        annotations = getattr(base, '__annotations__', {})
-                        if (isinstance(annotations, typing.Mapping) and
-                                attr in annotations and
-                                isinstance(other, _ProtocolMeta) and
-                                other._is_protocol):
-                            break
-                    else:
-                        return NotImplemented
-                return True
-            if '__subclasshook__' not in cls.__dict__:
-                cls.__subclasshook__ = _proto_hook
-
-            # We have nothing more to do for non-protocols.
-            if not cls._is_protocol:
-                return
-
-            # Check consistency of bases.
-            for base in cls.__bases__:
-                if not (base in (object, typing.Generic) or
-                        base.__module__ == 'collections.abc' and
-                        base.__name__ in _PROTO_WHITELIST or
-                        isinstance(base, _ProtocolMeta) and base._is_protocol):
-                    raise TypeError('Protocols can only inherit from other'
-                                    f' protocols, got {repr(base)}')
-            cls.__init__ = _no_init
-# 3.6
-else:
-    from typing import _next_in_mro, _type_check  # noqa
-
-    def _no_init(self, *args, **kwargs):
-        if type(self)._is_protocol:
-            raise TypeError('Protocols cannot be instantiated')
-
-    class _ProtocolMeta(GenericMeta):
-        """Internal metaclass for Protocol.
-
-        This exists so Protocol classes can be generic without deriving
-        from Generic.
-        """
-        def __new__(cls, name, bases, namespace,
-                    tvars=None, args=None, origin=None, extra=None, orig_bases=None):
-            # This is just a version copied from GenericMeta.__new__ that
-            # includes "Protocol" special treatment. (Comments removed for brevity.)
-            assert extra is None  # Protocols should not have extra
-            if tvars is not None:
-                assert origin is not None
-                assert all(isinstance(t, typing.TypeVar) for t in tvars), tvars
-            else:
-                tvars = _type_vars(bases)
-                gvars = None
-                for base in bases:
-                    if base is typing.Generic:
-                        raise TypeError("Cannot inherit from plain Generic")
-                    if (isinstance(base, GenericMeta) and
-                            base.__origin__ in (typing.Generic, Protocol)):
-                        if gvars is not None:
-                            raise TypeError(
-                                "Cannot inherit from Generic[...] or"
-                                " Protocol[...] multiple times.")
-                        gvars = base.__parameters__
-                if gvars is None:
-                    gvars = tvars
-                else:
-                    tvarset = set(tvars)
-                    gvarset = set(gvars)
-                    if not tvarset <= gvarset:
-                        s_vars = ", ".join(str(t) for t in tvars if t not in gvarset)
-                        s_args = ", ".join(str(g) for g in gvars)
-                        cls_name = "Generic" if any(b.__origin__ is typing.Generic
-                                                    for b in bases) else "Protocol"
-                        raise TypeError(f"Some type variables ({s_vars}) are"
-                                        f" not listed in {cls_name}[{s_args}]")
-                    tvars = gvars
-
-            initial_bases = bases
-            if (extra is not None and type(extra) is abc.ABCMeta and
-                    extra not in bases):
-                bases = (extra,) + bases
-            bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b
-                          for b in bases)
-            if any(isinstance(b, GenericMeta) and b is not typing.Generic for b in bases):
-                bases = tuple(b for b in bases if b is not typing.Generic)
-            namespace.update({'__origin__': origin, '__extra__': extra})
-            self = super(GenericMeta, cls).__new__(cls, name, bases, namespace,
-                                                   _root=True)
-            super(GenericMeta, self).__setattr__('_gorg',
-                                                 self if not origin else
-                                                 _gorg(origin))
-            self.__parameters__ = tvars
-            self.__args__ = tuple(... if a is typing._TypingEllipsis else
-                                  () if a is typing._TypingEmpty else
-                                  a for a in args) if args else None
-            self.__next_in_mro__ = _next_in_mro(self)
-            if orig_bases is None:
-                self.__orig_bases__ = initial_bases
-            elif origin is not None:
-                self._abc_registry = origin._abc_registry
-                self._abc_cache = origin._abc_cache
-            if hasattr(self, '_subs_tree'):
-                self.__tree_hash__ = (hash(self._subs_tree()) if origin else
-                                      super(GenericMeta, self).__hash__())
-            return self
-
-        def __init__(cls, *args, **kwargs):
-            super().__init__(*args, **kwargs)
-            if not cls.__dict__.get('_is_protocol', None):
-                cls._is_protocol = any(b is Protocol or
-                                       isinstance(b, _ProtocolMeta) and
-                                       b.__origin__ is Protocol
-                                       for b in cls.__bases__)
-            if cls._is_protocol:
-                for base in cls.__mro__[1:]:
-                    if not (base in (object, typing.Generic) or
-                            base.__module__ == 'collections.abc' and
-                            base.__name__ in _PROTO_WHITELIST or
-                            isinstance(base, typing.TypingMeta) and base._is_protocol or
-                            isinstance(base, GenericMeta) and
-                            base.__origin__ is typing.Generic):
-                        raise TypeError(f'Protocols can only inherit from other'
-                                        f' protocols, got {repr(base)}')
-
-                cls.__init__ = _no_init
-
-            def _proto_hook(other):
-                if not cls.__dict__.get('_is_protocol', None):
-                    return NotImplemented
-                if not isinstance(other, type):
-                    # Same error as for issubclass(1, int)
-                    raise TypeError('issubclass() arg 1 must be a class')
-                for attr in _get_protocol_attrs(cls):
-                    for base in other.__mro__:
-                        if attr in base.__dict__:
-                            if base.__dict__[attr] is None:
-                                return NotImplemented
-                            break
-                        annotations = getattr(base, '__annotations__', {})
-                        if (isinstance(annotations, typing.Mapping) and
-                                attr in annotations and
-                                isinstance(other, _ProtocolMeta) and
-                                other._is_protocol):
-                            break
-                    else:
-                        return NotImplemented
-                return True
-            if '__subclasshook__' not in cls.__dict__:
-                cls.__subclasshook__ = _proto_hook
-
-        def __instancecheck__(self, instance):
-            # We need this method for situations where attributes are
-            # assigned in __init__.
-            if ((not getattr(self, '_is_protocol', False) or
-                    _is_callable_members_only(self)) and
-                    issubclass(instance.__class__, self)):
-                return True
-            if self._is_protocol:
-                if all(hasattr(instance, attr) and
-                        (not callable(getattr(self, attr, None)) or
-                         getattr(instance, attr) is not None)
-                        for attr in _get_protocol_attrs(self)):
-                    return True
-            return super(GenericMeta, self).__instancecheck__(instance)
-
-        def __subclasscheck__(self, cls):
-            if self.__origin__ is not None:
-                if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']:
-                    raise TypeError("Parameterized generics cannot be used with class "
-                                    "or instance checks")
-                return False
-            if (self.__dict__.get('_is_protocol', None) and
-                    not self.__dict__.get('_is_runtime_protocol', None)):
-                if sys._getframe(1).f_globals['__name__'] in ['abc',
-                                                              'functools',
-                                                              'typing']:
-                    return False
-                raise TypeError("Instance and class checks can only be used with"
-                                " @runtime protocols")
-            if (self.__dict__.get('_is_runtime_protocol', None) and
-                    not _is_callable_members_only(self)):
-                if sys._getframe(1).f_globals['__name__'] in ['abc',
-                                                              'functools',
-                                                              'typing']:
-                    return super(GenericMeta, self).__subclasscheck__(cls)
-                raise TypeError("Protocols with non-method members"
-                                " don't support issubclass()")
-            return super(GenericMeta, self).__subclasscheck__(cls)
-
-        @typing._tp_cache
-        def __getitem__(self, params):
-            # We also need to copy this from GenericMeta.__getitem__ to get
-            # special treatment of "Protocol". (Comments removed for brevity.)
-            if not isinstance(params, tuple):
-                params = (params,)
-            if not params and _gorg(self) is not typing.Tuple:
-                raise TypeError(
-                    f"Parameter list to {self.__qualname__}[...] cannot be empty")
-            msg = "Parameters to generic types must be types."
-            params = tuple(_type_check(p, msg) for p in params)
-            if self in (typing.Generic, Protocol):
-                if not all(isinstance(p, typing.TypeVar) for p in params):
-                    raise TypeError(
-                        f"Parameters to {repr(self)}[...] must all be type variables")
-                if len(set(params)) != len(params):
-                    raise TypeError(
-                        f"Parameters to {repr(self)}[...] must all be unique")
-                tvars = params
-                args = params
-            elif self in (typing.Tuple, typing.Callable):
-                tvars = _type_vars(params)
-                args = params
-            elif self.__origin__ in (typing.Generic, Protocol):
-                raise TypeError(f"Cannot subscript already-subscripted {repr(self)}")
-            else:
-                _check_generic(self, params)
-                tvars = _type_vars(params)
-                args = params
-
-            prepend = (self,) if self.__origin__ is None else ()
-            return self.__class__(self.__name__,
-                                  prepend + self.__bases__,
-                                  _no_slots_copy(self.__dict__),
-                                  tvars=tvars,
-                                  args=args,
-                                  origin=self,
-                                  extra=self.__extra__,
-                                  orig_bases=self.__orig_bases__)
-
-    class Protocol(metaclass=_ProtocolMeta):
-        """Base class for protocol classes. Protocol classes are defined as::
-
-          class Proto(Protocol):
-              def meth(self) -> int:
-                  ...
-
-        Such classes are primarily used with static type checkers that recognize
-        structural subtyping (static duck-typing), for example::
-
-          class C:
-              def meth(self) -> int:
-                  return 0
-
-          def func(x: Proto) -> int:
-              return x.meth()
-
-          func(C())  # Passes static type check
-
-        See PEP 544 for details. Protocol classes decorated with
-        @typing_extensions.runtime act as simple-minded runtime protocol that checks
-        only the presence of given attributes, ignoring their type signatures.
-
-        Protocol classes can be generic, they are defined as::
-
-          class GenProto(Protocol[T]):
-              def meth(self) -> T:
-                  ...
-        """
-        __slots__ = ()
-        _is_protocol = True
-
-        def __new__(cls, *args, **kwds):
-            if _gorg(cls) is Protocol:
-                raise TypeError("Type Protocol cannot be instantiated; "
-                                "it can be used only as a base class")
-            return typing._generic_new(cls.__next_in_mro__, cls, *args, **kwds)
-
-
-# 3.8+
-if hasattr(typing, 'runtime_checkable'):
-    runtime_checkable = typing.runtime_checkable
-# 3.6-3.7
-else:
-    def runtime_checkable(cls):
-        """Mark a protocol class as a runtime protocol, so that it
-        can be used with isinstance() and issubclass(). Raise TypeError
-        if applied to a non-protocol class.
-
-        This allows a simple-minded structural check very similar to the
-        one-offs in collections.abc such as Hashable.
-        """
-        if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol:
-            raise TypeError('@runtime_checkable can be only applied to protocol classes,'
-                            f' got {cls!r}')
-        cls._is_runtime_protocol = True
-        return cls
-
-
-# Exists for backwards compatibility.
-runtime = runtime_checkable
-
-
-# 3.8+
-if hasattr(typing, 'SupportsIndex'):
-    SupportsIndex = typing.SupportsIndex
-# 3.6-3.7
-else:
-    @runtime_checkable
-    class SupportsIndex(Protocol):
-        __slots__ = ()
-
-        @abc.abstractmethod
-        def __index__(self) -> int:
-            pass
-
-
-if sys.version_info >= (3, 9, 2):
-    # The standard library TypedDict in Python 3.8 does not store runtime information
-    # about which (if any) keys are optional.  See https://bugs.python.org/issue38834
-    # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
-    # keyword with old-style TypedDict().  See https://bugs.python.org/issue42059
-    TypedDict = typing.TypedDict
-else:
-    def _check_fails(cls, other):
-        try:
-            if sys._getframe(1).f_globals['__name__'] not in ['abc',
-                                                              'functools',
-                                                              'typing']:
-                # Typed dicts are only for static structural subtyping.
-                raise TypeError('TypedDict does not support instance and class checks')
-        except (AttributeError, ValueError):
-            pass
-        return False
-
-    def _dict_new(*args, **kwargs):
-        if not args:
-            raise TypeError('TypedDict.__new__(): not enough arguments')
-        _, args = args[0], args[1:]  # allow the "cls" keyword be passed
-        return dict(*args, **kwargs)
-
-    _dict_new.__text_signature__ = '($cls, _typename, _fields=None, /, **kwargs)'
-
-    def _typeddict_new(*args, total=True, **kwargs):
-        if not args:
-            raise TypeError('TypedDict.__new__(): not enough arguments')
-        _, args = args[0], args[1:]  # allow the "cls" keyword be passed
-        if args:
-            typename, args = args[0], args[1:]  # allow the "_typename" keyword be passed
-        elif '_typename' in kwargs:
-            typename = kwargs.pop('_typename')
-            import warnings
-            warnings.warn("Passing '_typename' as keyword argument is deprecated",
-                          DeprecationWarning, stacklevel=2)
-        else:
-            raise TypeError("TypedDict.__new__() missing 1 required positional "
-                            "argument: '_typename'")
-        if args:
-            try:
-                fields, = args  # allow the "_fields" keyword be passed
-            except ValueError:
-                raise TypeError('TypedDict.__new__() takes from 2 to 3 '
-                                f'positional arguments but {len(args) + 2} '
-                                'were given')
-        elif '_fields' in kwargs and len(kwargs) == 1:
-            fields = kwargs.pop('_fields')
-            import warnings
-            warnings.warn("Passing '_fields' as keyword argument is deprecated",
-                          DeprecationWarning, stacklevel=2)
-        else:
-            fields = None
-
-        if fields is None:
-            fields = kwargs
-        elif kwargs:
-            raise TypeError("TypedDict takes either a dict or keyword arguments,"
-                            " but not both")
-
-        ns = {'__annotations__': dict(fields)}
-        try:
-            # Setting correct module is necessary to make typed dict classes pickleable.
-            ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
-        except (AttributeError, ValueError):
-            pass
-
-        return _TypedDictMeta(typename, (), ns, total=total)
-
-    _typeddict_new.__text_signature__ = ('($cls, _typename, _fields=None,'
-                                         ' /, *, total=True, **kwargs)')
-
-    class _TypedDictMeta(type):
-        def __init__(cls, name, bases, ns, total=True):
-            super().__init__(name, bases, ns)
-
-        def __new__(cls, name, bases, ns, total=True):
-            # Create new typed dict class object.
-            # This method is called directly when TypedDict is subclassed,
-            # or via _typeddict_new when TypedDict is instantiated. This way
-            # TypedDict supports all three syntaxes described in its docstring.
-            # Subclasses and instances of TypedDict return actual dictionaries
-            # via _dict_new.
-            ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new
-            tp_dict = super().__new__(cls, name, (dict,), ns)
-
-            annotations = {}
-            own_annotations = ns.get('__annotations__', {})
-            own_annotation_keys = set(own_annotations.keys())
-            msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
-            own_annotations = {
-                n: typing._type_check(tp, msg) for n, tp in own_annotations.items()
-            }
-            required_keys = set()
-            optional_keys = set()
-
-            for base in bases:
-                annotations.update(base.__dict__.get('__annotations__', {}))
-                required_keys.update(base.__dict__.get('__required_keys__', ()))
-                optional_keys.update(base.__dict__.get('__optional_keys__', ()))
-
-            annotations.update(own_annotations)
-            if total:
-                required_keys.update(own_annotation_keys)
-            else:
-                optional_keys.update(own_annotation_keys)
-
-            tp_dict.__annotations__ = annotations
-            tp_dict.__required_keys__ = frozenset(required_keys)
-            tp_dict.__optional_keys__ = frozenset(optional_keys)
-            if not hasattr(tp_dict, '__total__'):
-                tp_dict.__total__ = total
-            return tp_dict
-
-        __instancecheck__ = __subclasscheck__ = _check_fails
-
-    TypedDict = _TypedDictMeta('TypedDict', (dict,), {})
-    TypedDict.__module__ = __name__
-    TypedDict.__doc__ = \
-        """A simple typed name space. At runtime it is equivalent to a plain dict.
-
-        TypedDict creates a dictionary type that expects all of its
-        instances to have a certain set of keys, with each key
-        associated with a value of a consistent type. This expectation
-        is not checked at runtime but is only enforced by type checkers.
-        Usage::
-
-            class Point2D(TypedDict):
-                x: int
-                y: int
-                label: str
-
-            a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
-            b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check
-
-            assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
-
-        The type info can be accessed via the Point2D.__annotations__ dict, and
-        the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
-        TypedDict supports two additional equivalent forms::
-
-            Point2D = TypedDict('Point2D', x=int, y=int, label=str)
-            Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
-
-        The class syntax is only supported in Python 3.6+, while two other
-        syntax forms work for Python 2.7 and 3.2+
-        """
-
-
-# Python 3.9+ has PEP 593 (Annotated and modified get_type_hints)
-if hasattr(typing, 'Annotated'):
-    Annotated = typing.Annotated
-    get_type_hints = typing.get_type_hints
-    # Not exported and not a public API, but needed for get_origin() and get_args()
-    # to work.
-    _AnnotatedAlias = typing._AnnotatedAlias
-# 3.7-3.8
-elif PEP_560:
-    class _AnnotatedAlias(typing._GenericAlias, _root=True):
-        """Runtime representation of an annotated type.
-
-        At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
-        with extra annotations. The alias behaves like a normal typing alias,
-        instantiating is the same as instantiating the underlying type, binding
-        it to types is also the same.
-        """
-        def __init__(self, origin, metadata):
-            if isinstance(origin, _AnnotatedAlias):
-                metadata = origin.__metadata__ + metadata
-                origin = origin.__origin__
-            super().__init__(origin, origin)
-            self.__metadata__ = metadata
-
-        def copy_with(self, params):
-            assert len(params) == 1
-            new_type = params[0]
-            return _AnnotatedAlias(new_type, self.__metadata__)
-
-        def __repr__(self):
-            return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
-                    f"{', '.join(repr(a) for a in self.__metadata__)}]")
-
-        def __reduce__(self):
-            return operator.getitem, (
-                Annotated, (self.__origin__,) + self.__metadata__
-            )
-
-        def __eq__(self, other):
-            if not isinstance(other, _AnnotatedAlias):
-                return NotImplemented
-            if self.__origin__ != other.__origin__:
-                return False
-            return self.__metadata__ == other.__metadata__
-
-        def __hash__(self):
-            return hash((self.__origin__, self.__metadata__))
-
-    class Annotated:
-        """Add context specific metadata to a type.
-
-        Example: Annotated[int, runtime_check.Unsigned] indicates to the
-        hypothetical runtime_check module that this type is an unsigned int.
-        Every other consumer of this type can ignore this metadata and treat
-        this type as int.
-
-        The first argument to Annotated must be a valid type (and will be in
-        the __origin__ field), the remaining arguments are kept as a tuple in
-        the __extra__ field.
-
-        Details:
-
-        - It's an error to call `Annotated` with less than two arguments.
-        - Nested Annotated are flattened::
-
-            Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
-
-        - Instantiating an annotated type is equivalent to instantiating the
-        underlying type::
-
-            Annotated[C, Ann1](5) == C(5)
-
-        - Annotated can be used as a generic type alias::
-
-            Optimized = Annotated[T, runtime.Optimize()]
-            Optimized[int] == Annotated[int, runtime.Optimize()]
-
-            OptimizedList = Annotated[List[T], runtime.Optimize()]
-            OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
-        """
-
-        __slots__ = ()
-
-        def __new__(cls, *args, **kwargs):
-            raise TypeError("Type Annotated cannot be instantiated.")
-
-        @typing._tp_cache
-        def __class_getitem__(cls, params):
-            if not isinstance(params, tuple) or len(params) < 2:
-                raise TypeError("Annotated[...] should be used "
-                                "with at least two arguments (a type and an "
-                                "annotation).")
-            msg = "Annotated[t, ...]: t must be a type."
-            origin = typing._type_check(params[0], msg)
-            metadata = tuple(params[1:])
-            return _AnnotatedAlias(origin, metadata)
-
-        def __init_subclass__(cls, *args, **kwargs):
-            raise TypeError(
-                f"Cannot subclass {cls.__module__}.Annotated"
-            )
-
-    def _strip_annotations(t):
-        """Strips the annotations from a given type.
-        """
-        if isinstance(t, _AnnotatedAlias):
-            return _strip_annotations(t.__origin__)
-        if isinstance(t, typing._GenericAlias):
-            stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
-            if stripped_args == t.__args__:
-                return t
-            res = t.copy_with(stripped_args)
-            res._special = t._special
-            return res
-        return t
-
-    def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
-        """Return type hints for an object.
-
-        This is often the same as obj.__annotations__, but it handles
-        forward references encoded as string literals, adds Optional[t] if a
-        default value equal to None is set and recursively replaces all
-        'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
-
-        The argument may be a module, class, method, or function. The annotations
-        are returned as a dictionary. For classes, annotations include also
-        inherited members.
-
-        TypeError is raised if the argument is not of a type that can contain
-        annotations, and an empty dictionary is returned if no annotations are
-        present.
-
-        BEWARE -- the behavior of globalns and localns is counterintuitive
-        (unless you are familiar with how eval() and exec() work).  The
-        search order is locals first, then globals.
-
-        - If no dict arguments are passed, an attempt is made to use the
-          globals from obj (or the respective module's globals for classes),
-          and these are also used as the locals.  If the object does not appear
-          to have globals, an empty dictionary is used.
-
-        - If one dict argument is passed, it is used for both globals and
-          locals.
-
-        - If two dict arguments are passed, they specify globals and
-          locals, respectively.
-        """
-        hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
-        if include_extras:
-            return hint
-        return {k: _strip_annotations(t) for k, t in hint.items()}
-# 3.6
-else:
-
-    def _is_dunder(name):
-        """Returns True if name is a __dunder_variable_name__."""
-        return len(name) > 4 and name.startswith('__') and name.endswith('__')
-
-    # Prior to Python 3.7 types did not have `copy_with`. A lot of the equality
-    # checks, argument expansion etc. are done on the _subs_tre. As a result we
-    # can't provide a get_type_hints function that strips out annotations.
-
-    class AnnotatedMeta(typing.GenericMeta):
-        """Metaclass for Annotated"""
-
-        def __new__(cls, name, bases, namespace, **kwargs):
-            if any(b is not object for b in bases):
-                raise TypeError("Cannot subclass " + str(Annotated))
-            return super().__new__(cls, name, bases, namespace, **kwargs)
-
-        @property
-        def __metadata__(self):
-            return self._subs_tree()[2]
-
-        def _tree_repr(self, tree):
-            cls, origin, metadata = tree
-            if not isinstance(origin, tuple):
-                tp_repr = typing._type_repr(origin)
-            else:
-                tp_repr = origin[0]._tree_repr(origin)
-            metadata_reprs = ", ".join(repr(arg) for arg in metadata)
-            return f'{cls}[{tp_repr}, {metadata_reprs}]'
-
-        def _subs_tree(self, tvars=None, args=None):  # noqa
-            if self is Annotated:
-                return Annotated
-            res = super()._subs_tree(tvars=tvars, args=args)
-            # Flatten nested Annotated
-            if isinstance(res[1], tuple) and res[1][0] is Annotated:
-                sub_tp = res[1][1]
-                sub_annot = res[1][2]
-                return (Annotated, sub_tp, sub_annot + res[2])
-            return res
-
-        def _get_cons(self):
-            """Return the class used to create instance of this type."""
-            if self.__origin__ is None:
-                raise TypeError("Cannot get the underlying type of a "
-                                "non-specialized Annotated type.")
-            tree = self._subs_tree()
-            while isinstance(tree, tuple) and tree[0] is Annotated:
-                tree = tree[1]
-            if isinstance(tree, tuple):
-                return tree[0]
-            else:
-                return tree
-
-        @typing._tp_cache
-        def __getitem__(self, params):
-            if not isinstance(params, tuple):
-                params = (params,)
-            if self.__origin__ is not None:  # specializing an instantiated type
-                return super().__getitem__(params)
-            elif not isinstance(params, tuple) or len(params) < 2:
-                raise TypeError("Annotated[...] should be instantiated "
-                                "with at least two arguments (a type and an "
-                                "annotation).")
-            else:
-                msg = "Annotated[t, ...]: t must be a type."
-                tp = typing._type_check(params[0], msg)
-                metadata = tuple(params[1:])
-            return self.__class__(
-                self.__name__,
-                self.__bases__,
-                _no_slots_copy(self.__dict__),
-                tvars=_type_vars((tp,)),
-                # Metadata is a tuple so it won't be touched by _replace_args et al.
-                args=(tp, metadata),
-                origin=self,
-            )
-
-        def __call__(self, *args, **kwargs):
-            cons = self._get_cons()
-            result = cons(*args, **kwargs)
-            try:
-                result.__orig_class__ = self
-            except AttributeError:
-                pass
-            return result
-
-        def __getattr__(self, attr):
-            # For simplicity we just don't relay all dunder names
-            if self.__origin__ is not None and not _is_dunder(attr):
-                return getattr(self._get_cons(), attr)
-            raise AttributeError(attr)
-
-        def __setattr__(self, attr, value):
-            if _is_dunder(attr) or attr.startswith('_abc_'):
-                super().__setattr__(attr, value)
-            elif self.__origin__ is None:
-                raise AttributeError(attr)
-            else:
-                setattr(self._get_cons(), attr, value)
-
-        def __instancecheck__(self, obj):
-            raise TypeError("Annotated cannot be used with isinstance().")
-
-        def __subclasscheck__(self, cls):
-            raise TypeError("Annotated cannot be used with issubclass().")
-
-    class Annotated(metaclass=AnnotatedMeta):
-        """Add context specific metadata to a type.
-
-        Example: Annotated[int, runtime_check.Unsigned] indicates to the
-        hypothetical runtime_check module that this type is an unsigned int.
-        Every other consumer of this type can ignore this metadata and treat
-        this type as int.
-
-        The first argument to Annotated must be a valid type, the remaining
-        arguments are kept as a tuple in the __metadata__ field.
-
-        Details:
-
-        - It's an error to call `Annotated` with less than two arguments.
-        - Nested Annotated are flattened::
-
-            Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
-
-        - Instantiating an annotated type is equivalent to instantiating the
-        underlying type::
-
-            Annotated[C, Ann1](5) == C(5)
-
-        - Annotated can be used as a generic type alias::
-
-            Optimized = Annotated[T, runtime.Optimize()]
-            Optimized[int] == Annotated[int, runtime.Optimize()]
-
-            OptimizedList = Annotated[List[T], runtime.Optimize()]
-            OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
-        """
-
-# Python 3.8 has get_origin() and get_args() but those implementations aren't
-# Annotated-aware, so we can't use those. Python 3.9's versions don't support
-# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
-if sys.version_info[:2] >= (3, 10):
-    get_origin = typing.get_origin
-    get_args = typing.get_args
-# 3.7-3.9
-elif PEP_560:
-    try:
-        # 3.9+
-        from typing import _BaseGenericAlias
-    except ImportError:
-        _BaseGenericAlias = typing._GenericAlias
-    try:
-        # 3.9+
-        from typing import GenericAlias
-    except ImportError:
-        GenericAlias = typing._GenericAlias
-
-    def get_origin(tp):
-        """Get the unsubscripted version of a type.
-
-        This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
-        and Annotated. Return None for unsupported types. Examples::
-
-            get_origin(Literal[42]) is Literal
-            get_origin(int) is None
-            get_origin(ClassVar[int]) is ClassVar
-            get_origin(Generic) is Generic
-            get_origin(Generic[T]) is Generic
-            get_origin(Union[T, int]) is Union
-            get_origin(List[Tuple[T, T]][int]) == list
-            get_origin(P.args) is P
-        """
-        if isinstance(tp, _AnnotatedAlias):
-            return Annotated
-        if isinstance(tp, (typing._GenericAlias, GenericAlias, _BaseGenericAlias,
-                           ParamSpecArgs, ParamSpecKwargs)):
-            return tp.__origin__
-        if tp is typing.Generic:
-            return typing.Generic
-        return None
-
-    def get_args(tp):
-        """Get type arguments with all substitutions performed.
-
-        For unions, basic simplifications used by Union constructor are performed.
-        Examples::
-            get_args(Dict[str, int]) == (str, int)
-            get_args(int) == ()
-            get_args(Union[int, Union[T, int], str][int]) == (int, str)
-            get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
-            get_args(Callable[[], T][int]) == ([], int)
-        """
-        if isinstance(tp, _AnnotatedAlias):
-            return (tp.__origin__,) + tp.__metadata__
-        if isinstance(tp, (typing._GenericAlias, GenericAlias)):
-            if getattr(tp, "_special", False):
-                return ()
-            res = tp.__args__
-            if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
-                res = (list(res[:-1]), res[-1])
-            return res
-        return ()
-
-
-# 3.10+
-if hasattr(typing, 'TypeAlias'):
-    TypeAlias = typing.TypeAlias
-# 3.9
-elif sys.version_info[:2] >= (3, 9):
-    class _TypeAliasForm(typing._SpecialForm, _root=True):
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-    @_TypeAliasForm
-    def TypeAlias(self, parameters):
-        """Special marker indicating that an assignment should
-        be recognized as a proper type alias definition by type
-        checkers.
-
-        For example::
-
-            Predicate: TypeAlias = Callable[..., bool]
-
-        It's invalid when used anywhere except as in the example above.
-        """
-        raise TypeError(f"{self} is not subscriptable")
-# 3.7-3.8
-elif sys.version_info[:2] >= (3, 7):
-    class _TypeAliasForm(typing._SpecialForm, _root=True):
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-    TypeAlias = _TypeAliasForm('TypeAlias',
-                               doc="""Special marker indicating that an assignment should
-                               be recognized as a proper type alias definition by type
-                               checkers.
-
-                               For example::
-
-                                   Predicate: TypeAlias = Callable[..., bool]
-
-                               It's invalid when used anywhere except as in the example
-                               above.""")
-# 3.6
-else:
-    class _TypeAliasMeta(typing.TypingMeta):
-        """Metaclass for TypeAlias"""
-
-        def __repr__(self):
-            return 'typing_extensions.TypeAlias'
-
-    class _TypeAliasBase(typing._FinalTypingBase, metaclass=_TypeAliasMeta, _root=True):
-        """Special marker indicating that an assignment should
-        be recognized as a proper type alias definition by type
-        checkers.
-
-        For example::
-
-            Predicate: TypeAlias = Callable[..., bool]
-
-        It's invalid when used anywhere except as in the example above.
-        """
-        __slots__ = ()
-
-        def __instancecheck__(self, obj):
-            raise TypeError("TypeAlias cannot be used with isinstance().")
-
-        def __subclasscheck__(self, cls):
-            raise TypeError("TypeAlias cannot be used with issubclass().")
-
-        def __repr__(self):
-            return 'typing_extensions.TypeAlias'
-
-    TypeAlias = _TypeAliasBase(_root=True)
-
-
-# Python 3.10+ has PEP 612
-if hasattr(typing, 'ParamSpecArgs'):
-    ParamSpecArgs = typing.ParamSpecArgs
-    ParamSpecKwargs = typing.ParamSpecKwargs
-# 3.6-3.9
-else:
-    class _Immutable:
-        """Mixin to indicate that object should not be copied."""
-        __slots__ = ()
-
-        def __copy__(self):
-            return self
-
-        def __deepcopy__(self, memo):
-            return self
-
-    class ParamSpecArgs(_Immutable):
-        """The args for a ParamSpec object.
-
-        Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
-
-        ParamSpecArgs objects have a reference back to their ParamSpec:
-
-        P.args.__origin__ is P
-
-        This type is meant for runtime introspection and has no special meaning to
-        static type checkers.
-        """
-        def __init__(self, origin):
-            self.__origin__ = origin
-
-        def __repr__(self):
-            return f"{self.__origin__.__name__}.args"
-
-    class ParamSpecKwargs(_Immutable):
-        """The kwargs for a ParamSpec object.
-
-        Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
-
-        ParamSpecKwargs objects have a reference back to their ParamSpec:
-
-        P.kwargs.__origin__ is P
-
-        This type is meant for runtime introspection and has no special meaning to
-        static type checkers.
-        """
-        def __init__(self, origin):
-            self.__origin__ = origin
-
-        def __repr__(self):
-            return f"{self.__origin__.__name__}.kwargs"
-
-# 3.10+
-if hasattr(typing, 'ParamSpec'):
-    ParamSpec = typing.ParamSpec
-# 3.6-3.9
-else:
-
-    # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
-    class ParamSpec(list):
-        """Parameter specification variable.
-
-        Usage::
-
-           P = ParamSpec('P')
-
-        Parameter specification variables exist primarily for the benefit of static
-        type checkers.  They are used to forward the parameter types of one
-        callable to another callable, a pattern commonly found in higher order
-        functions and decorators.  They are only valid when used in ``Concatenate``,
-        or s the first argument to ``Callable``. In Python 3.10 and higher,
-        they are also supported in user-defined Generics at runtime.
-        See class Generic for more information on generic types.  An
-        example for annotating a decorator::
-
-           T = TypeVar('T')
-           P = ParamSpec('P')
-
-           def add_logging(f: Callable[P, T]) -> Callable[P, T]:
-               '''A type-safe decorator to add logging to a function.'''
-               def inner(*args: P.args, **kwargs: P.kwargs) -> T:
-                   logging.info(f'{f.__name__} was called')
-                   return f(*args, **kwargs)
-               return inner
-
-           @add_logging
-           def add_two(x: float, y: float) -> float:
-               '''Add two numbers together.'''
-               return x + y
-
-        Parameter specification variables defined with covariant=True or
-        contravariant=True can be used to declare covariant or contravariant
-        generic types.  These keyword arguments are valid, but their actual semantics
-        are yet to be decided.  See PEP 612 for details.
-
-        Parameter specification variables can be introspected. e.g.:
-
-           P.__name__ == 'T'
-           P.__bound__ == None
-           P.__covariant__ == False
-           P.__contravariant__ == False
-
-        Note that only parameter specification variables defined in global scope can
-        be pickled.
-        """
-
-        # Trick Generic __parameters__.
-        __class__ = typing.TypeVar
-
-        @property
-        def args(self):
-            return ParamSpecArgs(self)
-
-        @property
-        def kwargs(self):
-            return ParamSpecKwargs(self)
-
-        def __init__(self, name, *, bound=None, covariant=False, contravariant=False):
-            super().__init__([self])
-            self.__name__ = name
-            self.__covariant__ = bool(covariant)
-            self.__contravariant__ = bool(contravariant)
-            if bound:
-                self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
-            else:
-                self.__bound__ = None
-
-            # for pickling:
-            try:
-                def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
-            except (AttributeError, ValueError):
-                def_mod = None
-            if def_mod != 'typing_extensions':
-                self.__module__ = def_mod
-
-        def __repr__(self):
-            if self.__covariant__:
-                prefix = '+'
-            elif self.__contravariant__:
-                prefix = '-'
-            else:
-                prefix = '~'
-            return prefix + self.__name__
-
-        def __hash__(self):
-            return object.__hash__(self)
-
-        def __eq__(self, other):
-            return self is other
-
-        def __reduce__(self):
-            return self.__name__
-
-        # Hack to get typing._type_check to pass.
-        def __call__(self, *args, **kwargs):
-            pass
-
-        if not PEP_560:
-            # Only needed in 3.6.
-            def _get_type_vars(self, tvars):
-                if self not in tvars:
-                    tvars.append(self)
-
-
-# 3.6-3.9
-if not hasattr(typing, 'Concatenate'):
-    # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
-    class _ConcatenateGenericAlias(list):
-
-        # Trick Generic into looking into this for __parameters__.
-        if PEP_560:
-            __class__ = typing._GenericAlias
-        else:
-            __class__ = typing._TypingBase
-
-        # Flag in 3.8.
-        _special = False
-        # Attribute in 3.6 and earlier.
-        _gorg = typing.Generic
-
-        def __init__(self, origin, args):
-            super().__init__(args)
-            self.__origin__ = origin
-            self.__args__ = args
-
-        def __repr__(self):
-            _type_repr = typing._type_repr
-            return (f'{_type_repr(self.__origin__)}'
-                    f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
-
-        def __hash__(self):
-            return hash((self.__origin__, self.__args__))
-
-        # Hack to get typing._type_check to pass in Generic.
-        def __call__(self, *args, **kwargs):
-            pass
-
-        @property
-        def __parameters__(self):
-            return tuple(
-                tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
-            )
-
-        if not PEP_560:
-            # Only required in 3.6.
-            def _get_type_vars(self, tvars):
-                if self.__origin__ and self.__parameters__:
-                    typing._get_type_vars(self.__parameters__, tvars)
-
-
-# 3.6-3.9
-@typing._tp_cache
-def _concatenate_getitem(self, parameters):
-    if parameters == ():
-        raise TypeError("Cannot take a Concatenate of no types.")
-    if not isinstance(parameters, tuple):
-        parameters = (parameters,)
-    if not isinstance(parameters[-1], ParamSpec):
-        raise TypeError("The last parameter to Concatenate should be a "
-                        "ParamSpec variable.")
-    msg = "Concatenate[arg, ...]: each arg must be a type."
-    parameters = tuple(typing._type_check(p, msg) for p in parameters)
-    return _ConcatenateGenericAlias(self, parameters)
-
-
-# 3.10+
-if hasattr(typing, 'Concatenate'):
-    Concatenate = typing.Concatenate
-    _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa
-# 3.9
-elif sys.version_info[:2] >= (3, 9):
-    @_TypeAliasForm
-    def Concatenate(self, parameters):
-        """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
-        higher order function which adds, removes or transforms parameters of a
-        callable.
-
-        For example::
-
-           Callable[Concatenate[int, P], int]
-
-        See PEP 612 for detailed information.
-        """
-        return _concatenate_getitem(self, parameters)
-# 3.7-8
-elif sys.version_info[:2] >= (3, 7):
-    class _ConcatenateForm(typing._SpecialForm, _root=True):
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-        def __getitem__(self, parameters):
-            return _concatenate_getitem(self, parameters)
-
-    Concatenate = _ConcatenateForm(
-        'Concatenate',
-        doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
-        higher order function which adds, removes or transforms parameters of a
-        callable.
-
-        For example::
-
-           Callable[Concatenate[int, P], int]
-
-        See PEP 612 for detailed information.
-        """)
-# 3.6
-else:
-    class _ConcatenateAliasMeta(typing.TypingMeta):
-        """Metaclass for Concatenate."""
-
-        def __repr__(self):
-            return 'typing_extensions.Concatenate'
-
-    class _ConcatenateAliasBase(typing._FinalTypingBase,
-                                metaclass=_ConcatenateAliasMeta,
-                                _root=True):
-        """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
-        higher order function which adds, removes or transforms parameters of a
-        callable.
-
-        For example::
-
-           Callable[Concatenate[int, P], int]
-
-        See PEP 612 for detailed information.
-        """
-        __slots__ = ()
-
-        def __instancecheck__(self, obj):
-            raise TypeError("Concatenate cannot be used with isinstance().")
-
-        def __subclasscheck__(self, cls):
-            raise TypeError("Concatenate cannot be used with issubclass().")
-
-        def __repr__(self):
-            return 'typing_extensions.Concatenate'
-
-        def __getitem__(self, parameters):
-            return _concatenate_getitem(self, parameters)
-
-    Concatenate = _ConcatenateAliasBase(_root=True)
-
-# 3.10+
-if hasattr(typing, 'TypeGuard'):
-    TypeGuard = typing.TypeGuard
-# 3.9
-elif sys.version_info[:2] >= (3, 9):
-    class _TypeGuardForm(typing._SpecialForm, _root=True):
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-    @_TypeGuardForm
-    def TypeGuard(self, parameters):
-        """Special typing form used to annotate the return type of a user-defined
-        type guard function.  ``TypeGuard`` only accepts a single type argument.
-        At runtime, functions marked this way should return a boolean.
-
-        ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
-        type checkers to determine a more precise type of an expression within a
-        program's code flow.  Usually type narrowing is done by analyzing
-        conditional code flow and applying the narrowing to a block of code.  The
-        conditional expression here is sometimes referred to as a "type guard".
-
-        Sometimes it would be convenient to use a user-defined boolean function
-        as a type guard.  Such a function should use ``TypeGuard[...]`` as its
-        return type to alert static type checkers to this intention.
-
-        Using  ``-> TypeGuard`` tells the static type checker that for a given
-        function:
-
-        1. The return value is a boolean.
-        2. If the return value is ``True``, the type of its argument
-        is the type inside ``TypeGuard``.
-
-        For example::
-
-            def is_str(val: Union[str, float]):
-                # "isinstance" type guard
-                if isinstance(val, str):
-                    # Type of ``val`` is narrowed to ``str``
-                    ...
-                else:
-                    # Else, type of ``val`` is narrowed to ``float``.
-                    ...
-
-        Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
-        form of ``TypeA`` (it can even be a wider form) and this may lead to
-        type-unsafe results.  The main reason is to allow for things like
-        narrowing ``List[object]`` to ``List[str]`` even though the latter is not
-        a subtype of the former, since ``List`` is invariant.  The responsibility of
-        writing type-safe type guards is left to the user.
-
-        ``TypeGuard`` also works with type variables.  For more information, see
-        PEP 647 (User-Defined Type Guards).
-        """
-        item = typing._type_check(parameters, f'{self} accepts only single type.')
-        return typing._GenericAlias(self, (item,))
-# 3.7-3.8
-elif sys.version_info[:2] >= (3, 7):
-    class _TypeGuardForm(typing._SpecialForm, _root=True):
-
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-        def __getitem__(self, parameters):
-            item = typing._type_check(parameters,
-                                      f'{self._name} accepts only a single type')
-            return typing._GenericAlias(self, (item,))
-
-    TypeGuard = _TypeGuardForm(
-        'TypeGuard',
-        doc="""Special typing form used to annotate the return type of a user-defined
-        type guard function.  ``TypeGuard`` only accepts a single type argument.
-        At runtime, functions marked this way should return a boolean.
-
-        ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
-        type checkers to determine a more precise type of an expression within a
-        program's code flow.  Usually type narrowing is done by analyzing
-        conditional code flow and applying the narrowing to a block of code.  The
-        conditional expression here is sometimes referred to as a "type guard".
-
-        Sometimes it would be convenient to use a user-defined boolean function
-        as a type guard.  Such a function should use ``TypeGuard[...]`` as its
-        return type to alert static type checkers to this intention.
-
-        Using  ``-> TypeGuard`` tells the static type checker that for a given
-        function:
-
-        1. The return value is a boolean.
-        2. If the return value is ``True``, the type of its argument
-        is the type inside ``TypeGuard``.
-
-        For example::
-
-            def is_str(val: Union[str, float]):
-                # "isinstance" type guard
-                if isinstance(val, str):
-                    # Type of ``val`` is narrowed to ``str``
-                    ...
-                else:
-                    # Else, type of ``val`` is narrowed to ``float``.
-                    ...
-
-        Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
-        form of ``TypeA`` (it can even be a wider form) and this may lead to
-        type-unsafe results.  The main reason is to allow for things like
-        narrowing ``List[object]`` to ``List[str]`` even though the latter is not
-        a subtype of the former, since ``List`` is invariant.  The responsibility of
-        writing type-safe type guards is left to the user.
-
-        ``TypeGuard`` also works with type variables.  For more information, see
-        PEP 647 (User-Defined Type Guards).
-        """)
-# 3.6
-else:
-    class _TypeGuard(typing._FinalTypingBase, _root=True):
-        """Special typing form used to annotate the return type of a user-defined
-        type guard function.  ``TypeGuard`` only accepts a single type argument.
-        At runtime, functions marked this way should return a boolean.
-
-        ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
-        type checkers to determine a more precise type of an expression within a
-        program's code flow.  Usually type narrowing is done by analyzing
-        conditional code flow and applying the narrowing to a block of code.  The
-        conditional expression here is sometimes referred to as a "type guard".
-
-        Sometimes it would be convenient to use a user-defined boolean function
-        as a type guard.  Such a function should use ``TypeGuard[...]`` as its
-        return type to alert static type checkers to this intention.
-
-        Using  ``-> TypeGuard`` tells the static type checker that for a given
-        function:
-
-        1. The return value is a boolean.
-        2. If the return value is ``True``, the type of its argument
-        is the type inside ``TypeGuard``.
-
-        For example::
-
-            def is_str(val: Union[str, float]):
-                # "isinstance" type guard
-                if isinstance(val, str):
-                    # Type of ``val`` is narrowed to ``str``
-                    ...
-                else:
-                    # Else, type of ``val`` is narrowed to ``float``.
-                    ...
-
-        Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
-        form of ``TypeA`` (it can even be a wider form) and this may lead to
-        type-unsafe results.  The main reason is to allow for things like
-        narrowing ``List[object]`` to ``List[str]`` even though the latter is not
-        a subtype of the former, since ``List`` is invariant.  The responsibility of
-        writing type-safe type guards is left to the user.
-
-        ``TypeGuard`` also works with type variables.  For more information, see
-        PEP 647 (User-Defined Type Guards).
-        """
-
-        __slots__ = ('__type__',)
-
-        def __init__(self, tp=None, **kwds):
-            self.__type__ = tp
-
-        def __getitem__(self, item):
-            cls = type(self)
-            if self.__type__ is None:
-                return cls(typing._type_check(item,
-                           f'{cls.__name__[1:]} accepts only a single type.'),
-                           _root=True)
-            raise TypeError(f'{cls.__name__[1:]} cannot be further subscripted')
-
-        def _eval_type(self, globalns, localns):
-            new_tp = typing._eval_type(self.__type__, globalns, localns)
-            if new_tp == self.__type__:
-                return self
-            return type(self)(new_tp, _root=True)
-
-        def __repr__(self):
-            r = super().__repr__()
-            if self.__type__ is not None:
-                r += f'[{typing._type_repr(self.__type__)}]'
-            return r
-
-        def __hash__(self):
-            return hash((type(self).__name__, self.__type__))
-
-        def __eq__(self, other):
-            if not isinstance(other, _TypeGuard):
-                return NotImplemented
-            if self.__type__ is not None:
-                return self.__type__ == other.__type__
-            return self is other
-
-    TypeGuard = _TypeGuard(_root=True)
-
-if hasattr(typing, "Self"):
-    Self = typing.Self
-elif sys.version_info[:2] >= (3, 7):
-    # Vendored from cpython typing._SpecialFrom
-    class _SpecialForm(typing._Final, _root=True):
-        __slots__ = ('_name', '__doc__', '_getitem')
-
-        def __init__(self, getitem):
-            self._getitem = getitem
-            self._name = getitem.__name__
-            self.__doc__ = getitem.__doc__
-
-        def __getattr__(self, item):
-            if item in {'__name__', '__qualname__'}:
-                return self._name
-
-            raise AttributeError(item)
-
-        def __mro_entries__(self, bases):
-            raise TypeError(f"Cannot subclass {self!r}")
-
-        def __repr__(self):
-            return f'typing_extensions.{self._name}'
-
-        def __reduce__(self):
-            return self._name
-
-        def __call__(self, *args, **kwds):
-            raise TypeError(f"Cannot instantiate {self!r}")
-
-        def __or__(self, other):
-            return typing.Union[self, other]
-
-        def __ror__(self, other):
-            return typing.Union[other, self]
-
-        def __instancecheck__(self, obj):
-            raise TypeError(f"{self} cannot be used with isinstance()")
-
-        def __subclasscheck__(self, cls):
-            raise TypeError(f"{self} cannot be used with issubclass()")
-
-        @typing._tp_cache
-        def __getitem__(self, parameters):
-            return self._getitem(self, parameters)
-
-    @_SpecialForm
-    def Self(self, params):
-        """Used to spell the type of "self" in classes.
-
-        Example::
-
-          from typing import Self
-
-          class ReturnsSelf:
-              def parse(self, data: bytes) -> Self:
-                  ...
-                  return self
-
-        """
-
-        raise TypeError(f"{self} is not subscriptable")
-else:
-    class _Self(typing._FinalTypingBase, _root=True):
-        """Used to spell the type of "self" in classes.
-
-        Example::
-
-          from typing import Self
-
-          class ReturnsSelf:
-              def parse(self, data: bytes) -> Self:
-                  ...
-                  return self
-
-        """
-
-        __slots__ = ()
-
-        def __instancecheck__(self, obj):
-            raise TypeError(f"{self} cannot be used with isinstance().")
-
-        def __subclasscheck__(self, cls):
-            raise TypeError(f"{self} cannot be used with issubclass().")
-
-    Self = _Self(_root=True)
-
-
-if hasattr(typing, 'Required'):
-    Required = typing.Required
-    NotRequired = typing.NotRequired
-elif sys.version_info[:2] >= (3, 9):
-    class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-    @_ExtensionsSpecialForm
-    def Required(self, parameters):
-        """A special typing construct to mark a key of a total=False TypedDict
-        as required. For example:
-
-            class Movie(TypedDict, total=False):
-                title: Required[str]
-                year: int
-
-            m = Movie(
-                title='The Matrix',  # typechecker error if key is omitted
-                year=1999,
-            )
-
-        There is no runtime checking that a required key is actually provided
-        when instantiating a related TypedDict.
-        """
-        item = typing._type_check(parameters, f'{self._name} accepts only single type')
-        return typing._GenericAlias(self, (item,))
-
-    @_ExtensionsSpecialForm
-    def NotRequired(self, parameters):
-        """A special typing construct to mark a key of a TypedDict as
-        potentially missing. For example:
-
-            class Movie(TypedDict):
-                title: str
-                year: NotRequired[int]
-
-            m = Movie(
-                title='The Matrix',  # typechecker error if key is omitted
-                year=1999,
-            )
-        """
-        item = typing._type_check(parameters, f'{self._name} accepts only single type')
-        return typing._GenericAlias(self, (item,))
-
-elif sys.version_info[:2] >= (3, 7):
-    class _RequiredForm(typing._SpecialForm, _root=True):
-        def __repr__(self):
-            return 'typing_extensions.' + self._name
-
-        def __getitem__(self, parameters):
-            item = typing._type_check(parameters,
-                                      '{} accepts only single type'.format(self._name))
-            return typing._GenericAlias(self, (item,))
-
-    Required = _RequiredForm(
-        'Required',
-        doc="""A special typing construct to mark a key of a total=False TypedDict
-        as required. For example:
-
-            class Movie(TypedDict, total=False):
-                title: Required[str]
-                year: int
-
-            m = Movie(
-                title='The Matrix',  # typechecker error if key is omitted
-                year=1999,
-            )
-
-        There is no runtime checking that a required key is actually provided
-        when instantiating a related TypedDict.
-        """)
-    NotRequired = _RequiredForm(
-        'NotRequired',
-        doc="""A special typing construct to mark a key of a TypedDict as
-        potentially missing. For example:
-
-            class Movie(TypedDict):
-                title: str
-                year: NotRequired[int]
-
-            m = Movie(
-                title='The Matrix',  # typechecker error if key is omitted
-                year=1999,
-            )
-        """)
-else:
-    # NOTE: Modeled after _Final's implementation when _FinalTypingBase available
-    class _MaybeRequired(typing._FinalTypingBase, _root=True):
-        __slots__ = ('__type__',)
-
-        def __init__(self, tp=None, **kwds):
-            self.__type__ = tp
-
-        def __getitem__(self, item):
-            cls = type(self)
-            if self.__type__ is None:
-                return cls(typing._type_check(item,
-                           '{} accepts only single type.'.format(cls.__name__[1:])),
-                           _root=True)
-            raise TypeError('{} cannot be further subscripted'
-                            .format(cls.__name__[1:]))
-
-        def _eval_type(self, globalns, localns):
-            new_tp = typing._eval_type(self.__type__, globalns, localns)
-            if new_tp == self.__type__:
-                return self
-            return type(self)(new_tp, _root=True)
-
-        def __repr__(self):
-            r = super().__repr__()
-            if self.__type__ is not None:
-                r += '[{}]'.format(typing._type_repr(self.__type__))
-            return r
-
-        def __hash__(self):
-            return hash((type(self).__name__, self.__type__))
-
-        def __eq__(self, other):
-            if not isinstance(other, type(self)):
-                return NotImplemented
-            if self.__type__ is not None:
-                return self.__type__ == other.__type__
-            return self is other
-
-    class _Required(_MaybeRequired, _root=True):
-        """A special typing construct to mark a key of a total=False TypedDict
-        as required. For example:
-
-            class Movie(TypedDict, total=False):
-                title: Required[str]
-                year: int
-
-            m = Movie(
-                title='The Matrix',  # typechecker error if key is omitted
-                year=1999,
-            )
-
-        There is no runtime checking that a required key is actually provided
-        when instantiating a related TypedDict.
-        """
-
-    class _NotRequired(_MaybeRequired, _root=True):
-        """A special typing construct to mark a key of a TypedDict as
-        potentially missing. For example:
-
-            class Movie(TypedDict):
-                title: str
-                year: NotRequired[int]
-
-            m = Movie(
-                title='The Matrix',  # typechecker error if key is omitted
-                year=1999,
-            )
-        """
-
-    Required = _Required(_root=True)
-    NotRequired = _NotRequired(_root=True)
diff --git a/setuptools/_vendor/vendored.txt b/setuptools/_vendor/vendored.txt
deleted file mode 100644
index 0fed8eeeae..0000000000
--- a/setuptools/_vendor/vendored.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-packaging==23.1
-ordered-set==3.1.1
-more_itertools==8.8.0
-jaraco.text==3.7.0
-importlib_resources==5.10.2
-importlib_metadata==6.0.0
-# required for importlib_metadata on older Pythons
-typing_extensions==4.0.1
-# required for importlib_resources and _metadata on older Pythons
-zipp==3.7.0
-tomli==2.0.1
diff --git a/setuptools/_vendor/wheel-0.46.3.dist-info/INSTALLER b/setuptools/_vendor/wheel-0.46.3.dist-info/INSTALLER
new file mode 100644
index 0000000000..5c69047b2e
--- /dev/null
+++ b/setuptools/_vendor/wheel-0.46.3.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/setuptools/_vendor/wheel-0.46.3.dist-info/METADATA b/setuptools/_vendor/wheel-0.46.3.dist-info/METADATA
new file mode 100644
index 0000000000..77936a9eb6
--- /dev/null
+++ b/setuptools/_vendor/wheel-0.46.3.dist-info/METADATA
@@ -0,0 +1,69 @@
+Metadata-Version: 2.4
+Name: wheel
+Version: 0.46.3
+Summary: Command line tool for manipulating wheel files
+Keywords: wheel,packaging
+Author-email: Daniel Holth 
+Maintainer-email: Alex Grönholm 
+Requires-Python: >=3.9
+Description-Content-Type: text/x-rst
+License-Expression: MIT
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Topic :: System :: Archiving :: Packaging
+Classifier: Programming Language :: Python
+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
+License-File: LICENSE.txt
+Requires-Dist: packaging >= 24.0
+Requires-Dist: pytest >= 6.0.0 ; extra == "test"
+Requires-Dist: setuptools >= 77 ; extra == "test"
+Project-URL: Changelog, https://wheel.readthedocs.io/en/stable/news.html
+Project-URL: Documentation, https://wheel.readthedocs.io/
+Project-URL: Issue Tracker, https://github.com/pypa/wheel/issues
+Project-URL: Source, https://github.com/pypa/wheel
+Provides-Extra: test
+
+wheel
+=====
+
+This is a command line tool for manipulating Python wheel files, as defined in
+`PEP 427`_. It contains the following functionality:
+
+* Convert ``.egg`` archives into ``.whl``
+* Unpack wheel archives
+* Repack wheel archives
+* Add or remove tags in existing wheel archives
+
+.. _PEP 427: https://www.python.org/dev/peps/pep-0427/
+
+Historical note
+---------------
+
+This project used to contain the implementation of the setuptools_ ``bdist_wheel``
+command, but as of setuptools v70.1, it no longer needs ``wheel`` installed for that to
+work. Thus, you should install this **only** if you intend to use the ``wheel`` command
+line tool!
+
+.. _setuptools: https://pypi.org/project/setuptools/
+
+Documentation
+-------------
+
+The documentation_ can be found on Read The Docs.
+
+.. _documentation: https://wheel.readthedocs.io/
+
+Code of Conduct
+---------------
+
+Everyone interacting in the wheel 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
+
diff --git a/setuptools/_vendor/wheel-0.46.3.dist-info/RECORD b/setuptools/_vendor/wheel-0.46.3.dist-info/RECORD
new file mode 100644
index 0000000000..5890933bcb
--- /dev/null
+++ b/setuptools/_vendor/wheel-0.46.3.dist-info/RECORD
@@ -0,0 +1,22 @@
+bin/wheel,sha256=OLjFs9G7MQ-f_mhuW2aLGpngsyphW_v5FIoyN88Hfk0,339
+wheel-0.46.3.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+wheel-0.46.3.dist-info/METADATA,sha256=IpEKqXyonLzCCgGeJ_4xNgt5KaS9ZsoNMQ-ZpE9szTU,2410
+wheel-0.46.3.dist-info/RECORD,,
+wheel-0.46.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+wheel-0.46.3.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
+wheel-0.46.3.dist-info/entry_points.txt,sha256=JJdtSAGTvMLbIkTVZUAMvGKO39FtWfCVF8mp_NH6e4g,110
+wheel-0.46.3.dist-info/licenses/LICENSE.txt,sha256=MMI2GGeRCPPo6h0qZYx8pBe9_IkcmO8aifpP8MmChlQ,1107
+wheel/__init__.py,sha256=UweKvhe4SyP7zFyDoYo8BOuwTA6q3-_WpMmY2NNO54c,59
+wheel/__main__.py,sha256=_83wl9tyGU2cHiqfudpubGHdRL5uonPXnzeznznkxzs,512
+wheel/_bdist_wheel.py,sha256=bpmNa7_s-CYFkVgXf9ENAYTiJ01XBhRW4pxH1T8XYsI,21729
+wheel/_commands/__init__.py,sha256=fCRAQZNDyj2JLrufdgPsBlaRS_t_j_aBUMpXj09KZ4E,4432
+wheel/_commands/convert.py,sha256=0wSJMU0m-6LY16Om8Wmmloy-hJWFZeOmI8hT-2Z7Qms,12743
+wheel/_commands/pack.py,sha256=o3iwjfRHl7N9ul-M2kHbewLJZnqBLAWf0tzUCwoiTMw,3078
+wheel/_commands/tags.py,sha256=Rv2ySVb8-qX3osKp3uJgxcIMXkjt43XUD0-zvC6KvnY,4775
+wheel/_commands/unpack.py,sha256=AjDSS23XYyCSFfifnMutinrpPv-DK_2wbNHkKAUFwgM,1016
+wheel/_metadata.py,sha256=BP5jC9uC1hyicp7nL4FJ2LYixNFpEJIV_uMDY1KBZBg,6188
+wheel/_setuptools_logging.py,sha256=-5KC-lne0ilOUWIDfOkqapUWGMFZhuKYDIavIZiB5kM,781
+wheel/bdist_wheel.py,sha256=HrzYiSzMkh5ohAAhlQnYBS1p8qbr85X6F59xqxd9kBg,1102
+wheel/macosx_libfile.py,sha256=pL0wm88jRMl_4ASgGlNg_mz69Zmv5xm8JSkjLdwyvIQ,16712
+wheel/metadata.py,sha256=GknOO7JJiZMlcEe_fiD7nqnDTTLd0sX_-IgipM4L3-4,757
+wheel/wheelfile.py,sha256=m_g_7TNsEp-j-xnvSr5yDLEFb1nhyObueq9Q5_1_lBA,8720
diff --git a/setuptools/_vendor/packaging-23.1.dist-info/REQUESTED b/setuptools/_vendor/wheel-0.46.3.dist-info/REQUESTED
similarity index 100%
rename from setuptools/_vendor/packaging-23.1.dist-info/REQUESTED
rename to setuptools/_vendor/wheel-0.46.3.dist-info/REQUESTED
diff --git a/pkg_resources/_vendor/more_itertools-9.1.0.dist-info/WHEEL b/setuptools/_vendor/wheel-0.46.3.dist-info/WHEEL
similarity index 71%
rename from pkg_resources/_vendor/more_itertools-9.1.0.dist-info/WHEEL
rename to setuptools/_vendor/wheel-0.46.3.dist-info/WHEEL
index db4a255f3a..d8b9936dad 100644
--- a/pkg_resources/_vendor/more_itertools-9.1.0.dist-info/WHEEL
+++ b/setuptools/_vendor/wheel-0.46.3.dist-info/WHEEL
@@ -1,4 +1,4 @@
 Wheel-Version: 1.0
-Generator: flit 3.8.0
+Generator: flit 3.12.0
 Root-Is-Purelib: true
 Tag: py3-none-any
diff --git a/setuptools/_vendor/wheel-0.46.3.dist-info/entry_points.txt b/setuptools/_vendor/wheel-0.46.3.dist-info/entry_points.txt
new file mode 100644
index 0000000000..dcebd58811
--- /dev/null
+++ b/setuptools/_vendor/wheel-0.46.3.dist-info/entry_points.txt
@@ -0,0 +1,6 @@
+[console_scripts]
+wheel=wheel._commands:main
+
+[distutils.commands]
+bdist_wheel=wheel.bdist_wheel:bdist_wheel
+
diff --git a/setuptools/_vendor/ordered_set-3.1.1.dist-info/MIT-LICENSE b/setuptools/_vendor/wheel-0.46.3.dist-info/licenses/LICENSE.txt
similarity index 64%
rename from setuptools/_vendor/ordered_set-3.1.1.dist-info/MIT-LICENSE
rename to setuptools/_vendor/wheel-0.46.3.dist-info/licenses/LICENSE.txt
index 25117ef4f1..a31470f14c 100644
--- a/setuptools/_vendor/ordered_set-3.1.1.dist-info/MIT-LICENSE
+++ b/setuptools/_vendor/wheel-0.46.3.dist-info/licenses/LICENSE.txt
@@ -1,4 +1,6 @@
-Copyright (c) 2018 Luminoso Technologies, Inc.
+MIT License
+
+Copyright (c) 2012 Daniel Holth  and contributors
 
 Permission is hereby granted, free of charge, to any person obtaining a
 copy of this software and associated documentation files (the "Software"),
@@ -7,13 +9,13 @@ 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 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.
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
diff --git a/setuptools/_vendor/wheel/__init__.py b/setuptools/_vendor/wheel/__init__.py
new file mode 100644
index 0000000000..b5b076f05a
--- /dev/null
+++ b/setuptools/_vendor/wheel/__init__.py
@@ -0,0 +1,3 @@
+from __future__ import annotations
+
+__version__ = "0.46.3"
diff --git a/setuptools/_vendor/wheel/__main__.py b/setuptools/_vendor/wheel/__main__.py
new file mode 100644
index 0000000000..3c7de5fb7f
--- /dev/null
+++ b/setuptools/_vendor/wheel/__main__.py
@@ -0,0 +1,25 @@
+"""
+Wheel command line tool (enables the ``python -m wheel`` syntax)
+"""
+
+from __future__ import annotations
+
+import sys
+from typing import NoReturn
+
+
+def main() -> NoReturn:  # needed for console script
+    if __package__ == "":
+        # To be able to run 'python wheel-0.9.whl/wheel':
+        import os.path
+
+        path = os.path.dirname(os.path.dirname(__file__))
+        sys.path[0:0] = [path]
+
+    from ._commands import main as cli_main
+
+    sys.exit(cli_main())
+
+
+if __name__ == "__main__":
+    main()
diff --git a/setuptools/_vendor/wheel/_bdist_wheel.py b/setuptools/_vendor/wheel/_bdist_wheel.py
new file mode 100644
index 0000000000..575fbfb351
--- /dev/null
+++ b/setuptools/_vendor/wheel/_bdist_wheel.py
@@ -0,0 +1,616 @@
+"""
+Create a wheel (.whl) distribution.
+
+A wheel is a built archive format.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import re
+import shutil
+import stat
+import struct
+import sys
+import sysconfig
+import warnings
+from collections.abc import Iterable, Sequence
+from email.generator import BytesGenerator, Generator
+from email.policy import EmailPolicy
+from glob import iglob
+from shutil import rmtree
+from typing import TYPE_CHECKING, Callable, Literal, cast
+from zipfile import ZIP_DEFLATED, ZIP_STORED
+
+import setuptools
+from packaging import tags
+from packaging import version as _packaging_version
+from setuptools import Command
+
+from . import __version__ as wheel_version
+from ._metadata import pkginfo_to_metadata
+from .wheelfile import WheelFile
+
+if TYPE_CHECKING:
+    import types
+
+# ensure Python logging is configured
+try:
+    __import__("setuptools.logging")
+except ImportError:
+    # setuptools < ??
+    from . import _setuptools_logging
+
+    _setuptools_logging.configure()
+
+log = logging.getLogger("wheel")
+
+
+def safe_name(name: str) -> str:
+    """Convert an arbitrary string to a standard distribution name
+    Any runs of non-alphanumeric/. characters are replaced with a single '-'.
+    """
+    return re.sub("[^A-Za-z0-9.]+", "-", name)
+
+
+def safe_version(version: str) -> str:
+    """
+    Convert an arbitrary string to a standard version string
+    """
+    try:
+        # normalize the version
+        return str(_packaging_version.Version(version))
+    except _packaging_version.InvalidVersion:
+        version = version.replace(" ", ".")
+        return re.sub("[^A-Za-z0-9.]+", "-", version)
+
+
+setuptools_major_version = int(setuptools.__version__.split(".")[0])
+
+PY_LIMITED_API_PATTERN = r"cp3\d"
+
+
+def _is_32bit_interpreter() -> bool:
+    return struct.calcsize("P") == 4
+
+
+def python_tag() -> str:
+    return f"py{sys.version_info[0]}"
+
+
+def get_platform(archive_root: str | None) -> str:
+    """Return our platform name 'win32', 'linux_x86_64'"""
+    result = sysconfig.get_platform()
+    if result.startswith("macosx") and archive_root is not None:
+        from .macosx_libfile import calculate_macosx_platform_tag
+
+        result = calculate_macosx_platform_tag(archive_root, result)
+    elif _is_32bit_interpreter():
+        if result == "linux-x86_64":
+            # pip pull request #3497
+            result = "linux-i686"
+        elif result == "linux-aarch64":
+            # packaging pull request #234
+            # TODO armv8l, packaging pull request #690 => this did not land
+            # in pip/packaging yet
+            result = "linux-armv7l"
+
+    return result.replace("-", "_")
+
+
+def get_flag(
+    var: str, fallback: bool, expected: bool = True, warn: bool = True
+) -> bool:
+    """Use a fallback value for determining SOABI flags if the needed config
+    var is unset or unavailable."""
+    val = sysconfig.get_config_var(var)
+    if val is None:
+        if warn:
+            warnings.warn(
+                f"Config variable '{var}' is unset, Python ABI tag may be incorrect",
+                RuntimeWarning,
+                stacklevel=2,
+            )
+        return fallback
+    return val == expected
+
+
+def get_abi_tag() -> str | None:
+    """Return the ABI tag based on SOABI (if available) or emulate SOABI (PyPy2)."""
+    soabi: str = sysconfig.get_config_var("SOABI")
+    impl = tags.interpreter_name()
+    if not soabi and impl in ("cp", "pp") and hasattr(sys, "maxunicode"):
+        d = ""
+        m = ""
+        u = ""
+        if get_flag("Py_DEBUG", hasattr(sys, "gettotalrefcount"), warn=(impl == "cp")):
+            d = "d"
+
+        if get_flag(
+            "WITH_PYMALLOC",
+            impl == "cp",
+            warn=(impl == "cp" and sys.version_info < (3, 8)),
+        ) and sys.version_info < (3, 8):
+            m = "m"
+
+        abi = f"{impl}{tags.interpreter_version()}{d}{m}{u}"
+    elif soabi and impl == "cp" and soabi.startswith("cpython"):
+        # non-Windows
+        abi = "cp" + soabi.split("-")[1]
+    elif soabi and impl == "cp" and soabi.startswith("cp"):
+        # Windows
+        abi = soabi.split("-")[0]
+    elif soabi and impl == "pp":
+        # we want something like pypy36-pp73
+        abi = "-".join(soabi.split("-")[:2])
+        abi = abi.replace(".", "_").replace("-", "_")
+    elif soabi and impl == "graalpy":
+        abi = "-".join(soabi.split("-")[:3])
+        abi = abi.replace(".", "_").replace("-", "_")
+    elif soabi:
+        abi = soabi.replace(".", "_").replace("-", "_")
+    else:
+        abi = None
+
+    return abi
+
+
+def safer_name(name: str) -> str:
+    return safe_name(name).replace("-", "_")
+
+
+def safer_version(version: str) -> str:
+    return safe_version(version).replace("-", "_")
+
+
+def remove_readonly(
+    func: Callable[..., object],
+    path: str,
+    excinfo: tuple[type[Exception], Exception, types.TracebackType],
+) -> None:
+    remove_readonly_exc(func, path, excinfo[1])
+
+
+def remove_readonly_exc(func: Callable[..., object], path: str, exc: Exception) -> None:
+    os.chmod(path, stat.S_IWRITE)
+    func(path)
+
+
+class bdist_wheel(Command):
+    description = "create a wheel distribution"
+
+    supported_compressions = {
+        "stored": ZIP_STORED,
+        "deflated": ZIP_DEFLATED,
+    }
+
+    user_options = [
+        ("bdist-dir=", "b", "temporary directory for creating the distribution"),
+        (
+            "plat-name=",
+            "p",
+            "platform name to embed in generated filenames "
+            f"(default: {get_platform(None)})",
+        ),
+        (
+            "keep-temp",
+            "k",
+            "keep the pseudo-installation tree around after "
+            "creating the distribution archive",
+        ),
+        ("dist-dir=", "d", "directory to put final built distributions in"),
+        ("skip-build", None, "skip rebuilding everything (for testing/debugging)"),
+        (
+            "relative",
+            None,
+            "build the archive using relative paths (default: false)",
+        ),
+        (
+            "owner=",
+            "u",
+            "Owner name used when creating a tar file [default: current user]",
+        ),
+        (
+            "group=",
+            "g",
+            "Group name used when creating a tar file [default: current group]",
+        ),
+        ("universal", None, "make a universal wheel (default: false)"),
+        (
+            "compression=",
+            None,
+            "zipfile compression (one of: {}) (default: 'deflated')".format(
+                ", ".join(supported_compressions)
+            ),
+        ),
+        (
+            "python-tag=",
+            None,
+            f"Python implementation compatibility tag (default: '{python_tag()}')",
+        ),
+        (
+            "build-number=",
+            None,
+            "Build number for this particular version. "
+            "As specified in PEP-0427, this must start with a digit. "
+            "[default: None]",
+        ),
+        (
+            "py-limited-api=",
+            None,
+            "Python tag (cp32|cp33|cpNN) for abi3 wheel tag (default: false)",
+        ),
+    ]
+
+    boolean_options = ["keep-temp", "skip-build", "relative", "universal"]
+
+    def initialize_options(self):
+        self.bdist_dir: str = None
+        self.data_dir = None
+        self.plat_name: str | None = None
+        self.plat_tag = None
+        self.format = "zip"
+        self.keep_temp = False
+        self.dist_dir: str | None = None
+        self.egginfo_dir = None
+        self.root_is_pure: bool | None = None
+        self.skip_build = None
+        self.relative = False
+        self.owner = None
+        self.group = None
+        self.universal: bool = False
+        self.compression: str | int = "deflated"
+        self.python_tag: str = python_tag()
+        self.build_number: str | None = None
+        self.py_limited_api: str | Literal[False] = False
+        self.plat_name_supplied = False
+
+    def finalize_options(self):
+        if self.bdist_dir is None:
+            bdist_base = self.get_finalized_command("bdist").bdist_base
+            self.bdist_dir = os.path.join(bdist_base, "wheel")
+
+        egg_info = self.distribution.get_command_obj("egg_info")
+        egg_info.ensure_finalized()  # needed for correct `wheel_dist_name`
+
+        self.data_dir = self.wheel_dist_name + ".data"
+        self.plat_name_supplied = self.plat_name is not None
+
+        try:
+            self.compression = self.supported_compressions[self.compression]
+        except KeyError:
+            raise ValueError(f"Unsupported compression: {self.compression}") from None
+
+        need_options = ("dist_dir", "plat_name", "skip_build")
+
+        self.set_undefined_options("bdist", *zip(need_options, need_options))
+
+        self.root_is_pure = not (
+            self.distribution.has_ext_modules() or self.distribution.has_c_libraries()
+        )
+
+        if self.py_limited_api and not re.match(
+            PY_LIMITED_API_PATTERN, self.py_limited_api
+        ):
+            raise ValueError(f"py-limited-api must match '{PY_LIMITED_API_PATTERN}'")
+
+        # Support legacy [wheel] section for setting universal
+        wheel = self.distribution.get_option_dict("wheel")
+        if "universal" in wheel:
+            # please don't define this in your global configs
+            log.warning(
+                "The [wheel] section is deprecated. Use [bdist_wheel] instead.",
+            )
+            val = wheel["universal"][1].strip()
+            if val.lower() in ("1", "true", "yes"):
+                self.universal = True
+
+        if self.build_number is not None and not self.build_number[:1].isdigit():
+            raise ValueError("Build tag (build-number) must start with a digit.")
+
+    @property
+    def wheel_dist_name(self):
+        """Return distribution full name with - replaced with _"""
+        components = (
+            safer_name(self.distribution.get_name()),
+            safer_version(self.distribution.get_version()),
+        )
+        if self.build_number:
+            components += (self.build_number,)
+        return "-".join(components)
+
+    def get_tag(self) -> tuple[str, str, str]:
+        # bdist sets self.plat_name if unset, we should only use it for purepy
+        # wheels if the user supplied it.
+        if self.plat_name_supplied:
+            plat_name = cast(str, self.plat_name)
+        elif self.root_is_pure:
+            plat_name = "any"
+        else:
+            # macosx contains system version in platform name so need special handle
+            if self.plat_name and not self.plat_name.startswith("macosx"):
+                plat_name = self.plat_name
+            else:
+                # on macosx always limit the platform name to comply with any
+                # c-extension modules in bdist_dir, since the user can specify
+                # a higher MACOSX_DEPLOYMENT_TARGET via tools like CMake
+
+                # on other platforms, and on macosx if there are no c-extension
+                # modules, use the default platform name.
+                plat_name = get_platform(self.bdist_dir)
+
+            if _is_32bit_interpreter():
+                if plat_name in ("linux-x86_64", "linux_x86_64"):
+                    plat_name = "linux_i686"
+                if plat_name in ("linux-aarch64", "linux_aarch64"):
+                    # TODO armv8l, packaging pull request #690 => this did not land
+                    # in pip/packaging yet
+                    plat_name = "linux_armv7l"
+
+        plat_name = (
+            plat_name.lower().replace("-", "_").replace(".", "_").replace(" ", "_")
+        )
+
+        if self.root_is_pure:
+            if self.universal:
+                impl = "py2.py3"
+            else:
+                impl = self.python_tag
+            tag = (impl, "none", plat_name)
+        else:
+            impl_name = tags.interpreter_name()
+            impl_ver = tags.interpreter_version()
+            impl = impl_name + impl_ver
+            # We don't work on CPython 3.1, 3.0.
+            if self.py_limited_api and (impl_name + impl_ver).startswith("cp3"):
+                impl = self.py_limited_api
+                abi_tag = "abi3"
+            else:
+                abi_tag = str(get_abi_tag()).lower()
+            tag = (impl, abi_tag, plat_name)
+            # issue gh-374: allow overriding plat_name
+            supported_tags = [
+                (t.interpreter, t.abi, plat_name) for t in tags.sys_tags()
+            ]
+            assert tag in supported_tags, (
+                f"would build wheel with unsupported tag {tag}"
+            )
+        return tag
+
+    def run(self):
+        build_scripts = self.reinitialize_command("build_scripts")
+        build_scripts.executable = "python"
+        build_scripts.force = True
+
+        build_ext = self.reinitialize_command("build_ext")
+        build_ext.inplace = False
+
+        if not self.skip_build:
+            self.run_command("build")
+
+        install = self.reinitialize_command("install", reinit_subcommands=True)
+        install.root = self.bdist_dir
+        install.compile = False
+        install.skip_build = self.skip_build
+        install.warn_dir = False
+
+        # A wheel without setuptools scripts is more cross-platform.
+        # Use the (undocumented) `no_ep` option to setuptools'
+        # install_scripts command to avoid creating entry point scripts.
+        install_scripts = self.reinitialize_command("install_scripts")
+        install_scripts.no_ep = True
+
+        # Use a custom scheme for the archive, because we have to decide
+        # at installation time which scheme to use.
+        for key in ("headers", "scripts", "data", "purelib", "platlib"):
+            setattr(install, "install_" + key, os.path.join(self.data_dir, key))
+
+        basedir_observed = ""
+
+        if os.name == "nt":
+            # win32 barfs if any of these are ''; could be '.'?
+            # (distutils.command.install:change_roots bug)
+            basedir_observed = os.path.normpath(os.path.join(self.data_dir, ".."))
+            self.install_libbase = self.install_lib = basedir_observed
+
+        setattr(
+            install,
+            "install_purelib" if self.root_is_pure else "install_platlib",
+            basedir_observed,
+        )
+
+        log.info(f"installing to {self.bdist_dir}")
+
+        self.run_command("install")
+
+        impl_tag, abi_tag, plat_tag = self.get_tag()
+        archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}"
+        if not self.relative:
+            archive_root = self.bdist_dir
+        else:
+            archive_root = os.path.join(
+                self.bdist_dir, self._ensure_relative(install.install_base)
+            )
+
+        self.set_undefined_options("install_egg_info", ("target", "egginfo_dir"))
+        distinfo_dirname = (
+            f"{safer_name(self.distribution.get_name())}-"
+            f"{safer_version(self.distribution.get_version())}.dist-info"
+        )
+        distinfo_dir = os.path.join(self.bdist_dir, distinfo_dirname)
+        self.egg2dist(self.egginfo_dir, distinfo_dir)
+
+        self.write_wheelfile(distinfo_dir)
+
+        # Make the archive
+        if not os.path.exists(self.dist_dir):
+            os.makedirs(self.dist_dir)
+
+        wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl")
+        with WheelFile(wheel_path, "w", self.compression) as wf:
+            wf.write_files(archive_root)
+
+        # Add to 'Distribution.dist_files' so that the "upload" command works
+        getattr(self.distribution, "dist_files", []).append(
+            (
+                "bdist_wheel",
+                "{}.{}".format(*sys.version_info[:2]),  # like 3.7
+                wheel_path,
+            )
+        )
+
+        if not self.keep_temp:
+            log.info(f"removing {self.bdist_dir}")
+            if not self.dry_run:
+                if sys.version_info < (3, 12):
+                    rmtree(self.bdist_dir, onerror=remove_readonly)
+                else:
+                    rmtree(self.bdist_dir, onexc=remove_readonly_exc)
+
+    def write_wheelfile(
+        self, wheelfile_base: str, generator: str = f"bdist_wheel ({wheel_version})"
+    ):
+        from email.message import Message
+
+        msg = Message()
+        msg["Wheel-Version"] = "1.0"  # of the spec
+        msg["Generator"] = generator
+        msg["Root-Is-Purelib"] = str(self.root_is_pure).lower()
+        if self.build_number is not None:
+            msg["Build"] = self.build_number
+
+        # Doesn't work for bdist_wininst
+        impl_tag, abi_tag, plat_tag = self.get_tag()
+        for impl in impl_tag.split("."):
+            for abi in abi_tag.split("."):
+                for plat in plat_tag.split("."):
+                    msg["Tag"] = "-".join((impl, abi, plat))
+
+        wheelfile_path = os.path.join(wheelfile_base, "WHEEL")
+        log.info(f"creating {wheelfile_path}")
+        with open(wheelfile_path, "wb") as f:
+            BytesGenerator(f, maxheaderlen=0).flatten(msg)
+
+    def _ensure_relative(self, path: str) -> str:
+        # copied from dir_util, deleted
+        drive, path = os.path.splitdrive(path)
+        if path[0:1] == os.sep:
+            path = drive + path[1:]
+        return path
+
+    @property
+    def license_paths(self) -> Iterable[str]:
+        if setuptools_major_version >= 57:
+            # Setuptools has resolved any patterns to actual file names
+            return self.distribution.metadata.license_files or ()
+
+        files: set[str] = set()
+        metadata = self.distribution.get_option_dict("metadata")
+        if setuptools_major_version >= 42:
+            # Setuptools recognizes the license_files option but does not do globbing
+            patterns = cast(Sequence[str], self.distribution.metadata.license_files)
+        else:
+            # Prior to those, wheel is entirely responsible for handling license files
+            if "license_files" in metadata:
+                patterns = metadata["license_files"][1].split()
+            else:
+                patterns = ()
+
+        if "license_file" in metadata:
+            warnings.warn(
+                'The "license_file" option is deprecated. Use "license_files" instead.',
+                DeprecationWarning,
+                stacklevel=2,
+            )
+            files.add(metadata["license_file"][1])
+
+        if not files and not patterns and not isinstance(patterns, list):
+            patterns = ("LICEN[CS]E*", "COPYING*", "NOTICE*", "AUTHORS*")
+
+        for pattern in patterns:
+            for path in iglob(pattern):
+                if path.endswith("~"):
+                    log.debug(
+                        f'ignoring license file "{path}" as it looks like a backup'
+                    )
+                    continue
+
+                if path not in files and os.path.isfile(path):
+                    log.info(
+                        f'adding license file "{path}" (matched pattern "{pattern}")'
+                    )
+                    files.add(path)
+
+        return files
+
+    def egg2dist(self, egginfo_path: str, distinfo_path: str):
+        """Convert an .egg-info directory into a .dist-info directory"""
+
+        def adios(p: str) -> None:
+            """Appropriately delete directory, file or link."""
+            if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):
+                shutil.rmtree(p)
+            elif os.path.exists(p):
+                os.unlink(p)
+
+        adios(distinfo_path)
+
+        if not os.path.exists(egginfo_path):
+            # There is no egg-info. This is probably because the egg-info
+            # file/directory is not named matching the distribution name used
+            # to name the archive file. Check for this case and report
+            # accordingly.
+            import glob
+
+            pat = os.path.join(os.path.dirname(egginfo_path), "*.egg-info")
+            possible = glob.glob(pat)
+            err = f"Egg metadata expected at {egginfo_path} but not found"
+            if possible:
+                alt = os.path.basename(possible[0])
+                err += f" ({alt} found - possible misnamed archive file?)"
+
+            raise ValueError(err)
+
+        if os.path.isfile(egginfo_path):
+            # .egg-info is a single file
+            pkg_info = pkginfo_to_metadata(egginfo_path, egginfo_path)
+            os.mkdir(distinfo_path)
+        else:
+            # .egg-info is a directory
+            pkginfo_path = os.path.join(egginfo_path, "PKG-INFO")
+            pkg_info = pkginfo_to_metadata(egginfo_path, pkginfo_path)
+
+            # ignore common egg metadata that is useless to wheel
+            shutil.copytree(
+                egginfo_path,
+                distinfo_path,
+                ignore=lambda x, y: {
+                    "PKG-INFO",
+                    "requires.txt",
+                    "SOURCES.txt",
+                    "not-zip-safe",
+                },
+            )
+
+            # delete dependency_links if it is only whitespace
+            dependency_links_path = os.path.join(distinfo_path, "dependency_links.txt")
+            with open(dependency_links_path, encoding="utf-8") as dependency_links_file:
+                dependency_links = dependency_links_file.read().strip()
+            if not dependency_links:
+                adios(dependency_links_path)
+
+        pkg_info_path = os.path.join(distinfo_path, "METADATA")
+        serialization_policy = EmailPolicy(
+            utf8=True,
+            mangle_from_=False,
+            max_line_length=0,
+        )
+        with open(pkg_info_path, "w", encoding="utf-8") as out:
+            Generator(out, policy=serialization_policy).flatten(pkg_info)
+
+        for license_path in self.license_paths:
+            filename = os.path.basename(license_path)
+            shutil.copy(license_path, os.path.join(distinfo_path, filename))
+
+        adios(egginfo_path)
diff --git a/setuptools/_vendor/wheel/_commands/__init__.py b/setuptools/_vendor/wheel/_commands/__init__.py
new file mode 100644
index 0000000000..42f1d7ef30
--- /dev/null
+++ b/setuptools/_vendor/wheel/_commands/__init__.py
@@ -0,0 +1,153 @@
+"""
+Wheel command-line utility.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import sys
+from argparse import ArgumentTypeError
+
+from ..wheelfile import WheelError
+
+
+def unpack_f(args: argparse.Namespace) -> None:
+    from .unpack import unpack
+
+    unpack(args.wheelfile, args.dest)
+
+
+def pack_f(args: argparse.Namespace) -> None:
+    from .pack import pack
+
+    pack(args.directory, args.dest_dir, args.build_number)
+
+
+def convert_f(args: argparse.Namespace) -> None:
+    from .convert import convert
+
+    convert(args.files, args.dest_dir, args.verbose)
+
+
+def tags_f(args: argparse.Namespace) -> None:
+    from .tags import tags
+
+    names = (
+        tags(
+            wheel,
+            args.python_tag,
+            args.abi_tag,
+            args.platform_tag,
+            args.build,
+            args.remove,
+        )
+        for wheel in args.wheel
+    )
+
+    for name in names:
+        print(name)
+
+
+def version_f(args: argparse.Namespace) -> None:
+    from .. import __version__
+
+    print(f"wheel {__version__}")
+
+
+def parse_build_tag(build_tag: str) -> str:
+    if build_tag and not build_tag[0].isdigit():
+        raise ArgumentTypeError("build tag must begin with a digit")
+    elif "-" in build_tag:
+        raise ArgumentTypeError("invalid character ('-') in build tag")
+
+    return build_tag
+
+
+TAGS_HELP = """\
+Make a new wheel with given tags. Any tags unspecified will remain the same.
+Starting the tags with a "+" will append to the existing tags. Starting with a
+"-" will remove a tag (use --option=-TAG syntax). Multiple tags can be
+separated by ".". The original file will remain unless --remove is given.  The
+output filename(s) will be displayed on stdout for further processing.
+"""
+
+
+def parser() -> argparse.ArgumentParser:
+    p = argparse.ArgumentParser()
+    s = p.add_subparsers(help="commands")
+
+    unpack_parser = s.add_parser("unpack", help="Unpack wheel")
+    unpack_parser.add_argument(
+        "--dest", "-d", help="Destination directory", default="."
+    )
+    unpack_parser.add_argument("wheelfile", help="Wheel file")
+    unpack_parser.set_defaults(func=unpack_f)
+
+    repack_parser = s.add_parser("pack", help="Repack wheel")
+    repack_parser.add_argument("directory", help="Root directory of the unpacked wheel")
+    repack_parser.add_argument(
+        "--dest-dir",
+        "-d",
+        default=os.path.curdir,
+        help="Directory to store the wheel (default %(default)s)",
+    )
+    repack_parser.add_argument(
+        "--build-number", help="Build tag to use in the wheel name"
+    )
+    repack_parser.set_defaults(func=pack_f)
+
+    convert_parser = s.add_parser("convert", help="Convert egg or wininst to wheel")
+    convert_parser.add_argument("files", nargs="*", help="Files to convert")
+    convert_parser.add_argument(
+        "--dest-dir",
+        "-d",
+        default=os.path.curdir,
+        help="Directory to store wheels (default %(default)s)",
+    )
+    convert_parser.add_argument("--verbose", "-v", action="store_true")
+    convert_parser.set_defaults(func=convert_f)
+
+    tags_parser = s.add_parser(
+        "tags", help="Add or replace the tags on a wheel", description=TAGS_HELP
+    )
+    tags_parser.add_argument("wheel", nargs="*", help="Existing wheel(s) to retag")
+    tags_parser.add_argument(
+        "--remove",
+        action="store_true",
+        help="Remove the original files, keeping only the renamed ones",
+    )
+    tags_parser.add_argument(
+        "--python-tag", metavar="TAG", help="Specify an interpreter tag(s)"
+    )
+    tags_parser.add_argument("--abi-tag", metavar="TAG", help="Specify an ABI tag(s)")
+    tags_parser.add_argument(
+        "--platform-tag", metavar="TAG", help="Specify a platform tag(s)"
+    )
+    tags_parser.add_argument(
+        "--build", type=parse_build_tag, metavar="BUILD", help="Specify a build tag"
+    )
+    tags_parser.set_defaults(func=tags_f)
+
+    version_parser = s.add_parser("version", help="Print version and exit")
+    version_parser.set_defaults(func=version_f)
+
+    help_parser = s.add_parser("help", help="Show this help")
+    help_parser.set_defaults(func=lambda args: p.print_help())
+
+    return p
+
+
+def main() -> int:
+    p = parser()
+    args = p.parse_args()
+    if not hasattr(args, "func"):
+        p.print_help()
+    else:
+        try:
+            args.func(args)
+            return 0
+        except WheelError as e:
+            print(e, file=sys.stderr)
+
+    return 1
diff --git a/setuptools/_vendor/wheel/_commands/convert.py b/setuptools/_vendor/wheel/_commands/convert.py
new file mode 100644
index 0000000000..cafd12c86c
--- /dev/null
+++ b/setuptools/_vendor/wheel/_commands/convert.py
@@ -0,0 +1,337 @@
+from __future__ import annotations
+
+import os.path
+import re
+from abc import ABCMeta, abstractmethod
+from collections import defaultdict
+from collections.abc import Iterator
+from email.message import Message
+from email.parser import Parser
+from email.policy import EmailPolicy
+from glob import iglob
+from pathlib import Path
+from textwrap import dedent
+from zipfile import ZipFile
+
+from packaging.tags import parse_tag
+
+from .. import __version__
+from .._metadata import generate_requirements
+from ..wheelfile import WheelFile
+
+egg_filename_re = re.compile(
+    r"""
+    (?P.+?)-(?P.+?)
+    (-(?Ppy\d\.\d+)
+     (-(?P.+?))?
+    )?.egg$""",
+    re.VERBOSE,
+)
+egg_info_re = re.compile(
+    r"""
+    ^(?P.+?)-(?P.+?)
+    (-(?Ppy\d\.\d+)
+    )?.egg-info/""",
+    re.VERBOSE,
+)
+wininst_re = re.compile(
+    r"\.(?Pwin32|win-amd64)(?:-(?Ppy\d\.\d))?\.exe$"
+)
+pyd_re = re.compile(r"\.(?P[a-z0-9]+)-(?Pwin32|win_amd64)\.pyd$")
+serialization_policy = EmailPolicy(
+    utf8=True,
+    mangle_from_=False,
+    max_line_length=0,
+)
+GENERATOR = f"wheel {__version__}"
+
+
+def convert_requires(requires: str, metadata: Message) -> None:
+    extra: str | None = None
+    requirements: dict[str | None, list[str]] = defaultdict(list)
+    for line in requires.splitlines():
+        line = line.strip()
+        if not line:
+            continue
+
+        if line.startswith("[") and line.endswith("]"):
+            extra = line[1:-1]
+            continue
+
+        requirements[extra].append(line)
+
+    for key, value in generate_requirements(requirements):
+        metadata.add_header(key, value)
+
+
+def convert_pkg_info(pkginfo: str, metadata: Message) -> None:
+    parsed_message = Parser().parsestr(pkginfo)
+    for key, value in parsed_message.items():
+        key_lower = key.lower()
+        if value == "UNKNOWN":
+            continue
+
+        if key_lower == "description":
+            description_lines = value.splitlines()
+            if description_lines:
+                value = "\n".join(
+                    (
+                        description_lines[0].lstrip(),
+                        dedent("\n".join(description_lines[1:])),
+                        "\n",
+                    )
+                )
+            else:
+                value = "\n"
+
+            metadata.set_payload(value)
+        elif key_lower == "home-page":
+            metadata.add_header("Project-URL", f"Homepage, {value}")
+        elif key_lower == "download-url":
+            metadata.add_header("Project-URL", f"Download, {value}")
+        else:
+            metadata.add_header(key, value)
+
+    metadata.replace_header("Metadata-Version", "2.4")
+
+
+def normalize(name: str) -> str:
+    return re.sub(r"[-_.]+", "-", name).lower().replace("-", "_")
+
+
+class ConvertSource(metaclass=ABCMeta):
+    name: str
+    version: str
+    pyver: str = "py2.py3"
+    abi: str = "none"
+    platform: str = "any"
+    metadata: Message
+
+    @property
+    def dist_info_dir(self) -> str:
+        return f"{self.name}-{self.version}.dist-info"
+
+    @abstractmethod
+    def generate_contents(self) -> Iterator[tuple[str, bytes]]:
+        pass
+
+
+class EggFileSource(ConvertSource):
+    def __init__(self, path: Path):
+        if not (match := egg_filename_re.match(path.name)):
+            raise ValueError(f"Invalid egg file name: {path.name}")
+
+        # Binary wheels are assumed to be for CPython
+        self.path = path
+        self.name = normalize(match.group("name"))
+        self.version = match.group("ver")
+        if pyver := match.group("pyver"):
+            self.pyver = pyver.replace(".", "")
+            if arch := match.group("arch"):
+                self.abi = self.pyver.replace("py", "cp")
+                self.platform = normalize(arch)
+
+        self.metadata = Message()
+
+    def generate_contents(self) -> Iterator[tuple[str, bytes]]:
+        with ZipFile(self.path, "r") as zip_file:
+            for filename in sorted(zip_file.namelist()):
+                # Skip pure directory entries
+                if filename.endswith("/"):
+                    continue
+
+                # Handle files in the egg-info directory specially, selectively moving
+                # them to the dist-info directory while converting as needed
+                if filename.startswith("EGG-INFO/"):
+                    if filename == "EGG-INFO/requires.txt":
+                        requires = zip_file.read(filename).decode("utf-8")
+                        convert_requires(requires, self.metadata)
+                    elif filename == "EGG-INFO/PKG-INFO":
+                        pkginfo = zip_file.read(filename).decode("utf-8")
+                        convert_pkg_info(pkginfo, self.metadata)
+                    elif filename == "EGG-INFO/entry_points.txt":
+                        yield (
+                            f"{self.dist_info_dir}/entry_points.txt",
+                            zip_file.read(filename),
+                        )
+
+                    continue
+
+                # For any other file, just pass it through
+                yield filename, zip_file.read(filename)
+
+
+class EggDirectorySource(EggFileSource):
+    def generate_contents(self) -> Iterator[tuple[str, bytes]]:
+        for dirpath, _, filenames in os.walk(self.path):
+            for filename in sorted(filenames):
+                path = Path(dirpath, filename)
+                if path.parent.name == "EGG-INFO":
+                    if path.name == "requires.txt":
+                        requires = path.read_text("utf-8")
+                        convert_requires(requires, self.metadata)
+                    elif path.name == "PKG-INFO":
+                        pkginfo = path.read_text("utf-8")
+                        convert_pkg_info(pkginfo, self.metadata)
+                        if name := self.metadata.get("Name"):
+                            self.name = normalize(name)
+
+                        if version := self.metadata.get("Version"):
+                            self.version = version
+                    elif path.name == "entry_points.txt":
+                        yield (
+                            f"{self.dist_info_dir}/entry_points.txt",
+                            path.read_bytes(),
+                        )
+
+                    continue
+
+                # For any other file, just pass it through
+                yield str(path.relative_to(self.path)), path.read_bytes()
+
+
+class WininstFileSource(ConvertSource):
+    """
+    Handles distributions created with ``bdist_wininst``.
+
+    The egginfo filename has the format::
+
+        name-ver(-pyver)(-arch).egg-info
+
+    The installer filename has the format::
+
+        name-ver.arch(-pyver).exe
+
+    Some things to note:
+
+    1. The installer filename is not definitive. An installer can be renamed
+       and work perfectly well as an installer. So more reliable data should
+       be used whenever possible.
+    2. The egg-info data should be preferred for the name and version, because
+       these come straight from the distutils metadata, and are mandatory.
+    3. The pyver from the egg-info data should be ignored, as it is
+       constructed from the version of Python used to build the installer,
+       which is irrelevant - the installer filename is correct here (even to
+       the point that when it's not there, any version is implied).
+    4. The architecture must be taken from the installer filename, as it is
+       not included in the egg-info data.
+    5. Architecture-neutral installers still have an architecture because the
+       installer format itself (being executable) is architecture-specific. We
+       should therefore ignore the architecture if the content is pure-python.
+    """
+
+    def __init__(self, path: Path):
+        self.path = path
+        self.metadata = Message()
+
+        # Determine the initial architecture and Python version from the file name
+        # (if possible)
+        if match := wininst_re.search(path.name):
+            self.platform = normalize(match.group("platform"))
+            if pyver := match.group("pyver"):
+                self.pyver = pyver.replace(".", "")
+
+        # Look for an .egg-info directory and any .pyd files for more precise info
+        egg_info_found = pyd_found = False
+        with ZipFile(self.path) as zip_file:
+            for filename in zip_file.namelist():
+                prefix, filename = filename.split("/", 1)
+                if not egg_info_found and (match := egg_info_re.match(filename)):
+                    egg_info_found = True
+                    self.name = normalize(match.group("name"))
+                    self.version = match.group("ver")
+                    if pyver := match.group("pyver"):
+                        self.pyver = pyver.replace(".", "")
+                elif not pyd_found and (match := pyd_re.search(filename)):
+                    pyd_found = True
+                    self.abi = match.group("abi")
+                    self.platform = match.group("platform")
+
+                if egg_info_found and pyd_found:
+                    break
+
+    def generate_contents(self) -> Iterator[tuple[str, bytes]]:
+        dist_info_dir = f"{self.name}-{self.version}.dist-info"
+        data_dir = f"{self.name}-{self.version}.data"
+        with ZipFile(self.path, "r") as zip_file:
+            for filename in sorted(zip_file.namelist()):
+                # Skip pure directory entries
+                if filename.endswith("/"):
+                    continue
+
+                # Handle files in the egg-info directory specially, selectively moving
+                # them to the dist-info directory while converting as needed
+                prefix, target_filename = filename.split("/", 1)
+                if egg_info_re.search(target_filename):
+                    basename = target_filename.rsplit("/", 1)[-1]
+                    if basename == "requires.txt":
+                        requires = zip_file.read(filename).decode("utf-8")
+                        convert_requires(requires, self.metadata)
+                    elif basename == "PKG-INFO":
+                        pkginfo = zip_file.read(filename).decode("utf-8")
+                        convert_pkg_info(pkginfo, self.metadata)
+                    elif basename == "entry_points.txt":
+                        yield (
+                            f"{dist_info_dir}/entry_points.txt",
+                            zip_file.read(filename),
+                        )
+
+                    continue
+                elif prefix == "SCRIPTS":
+                    target_filename = f"{data_dir}/scripts/{target_filename}"
+
+                # For any other file, just pass it through
+                yield target_filename, zip_file.read(filename)
+
+
+def convert(files: list[str], dest_dir: str, verbose: bool) -> None:
+    for pat in files:
+        for archive in iglob(pat):
+            path = Path(archive)
+            if path.suffix == ".egg":
+                if path.is_dir():
+                    source: ConvertSource = EggDirectorySource(path)
+                else:
+                    source = EggFileSource(path)
+            else:
+                source = WininstFileSource(path)
+
+            if verbose:
+                print(f"{archive}...", flush=True, end="")
+
+            dest_path = Path(dest_dir) / (
+                f"{source.name}-{source.version}-{source.pyver}-{source.abi}"
+                f"-{source.platform}.whl"
+            )
+            with WheelFile(dest_path, "w") as wheelfile:
+                for name_or_zinfo, contents in source.generate_contents():
+                    wheelfile.writestr(name_or_zinfo, contents)
+
+                # Write the METADATA file
+                wheelfile.writestr(
+                    f"{source.dist_info_dir}/METADATA",
+                    source.metadata.as_string(policy=serialization_policy).encode(
+                        "utf-8"
+                    ),
+                )
+
+                # Write the WHEEL file
+                wheel_message = Message()
+                wheel_message.add_header("Wheel-Version", "1.0")
+                wheel_message.add_header("Generator", GENERATOR)
+                wheel_message.add_header(
+                    "Root-Is-Purelib", str(source.platform == "any").lower()
+                )
+                tags = parse_tag(f"{source.pyver}-{source.abi}-{source.platform}")
+                for tag in sorted(tags, key=lambda tag: tag.interpreter):
+                    wheel_message.add_header("Tag", str(tag))
+
+                wheelfile.writestr(
+                    f"{source.dist_info_dir}/WHEEL",
+                    wheel_message.as_string(policy=serialization_policy).encode(
+                        "utf-8"
+                    ),
+                )
+
+            if verbose:
+                print("OK")
diff --git a/setuptools/_vendor/wheel/_commands/pack.py b/setuptools/_vendor/wheel/_commands/pack.py
new file mode 100644
index 0000000000..1321ce9308
--- /dev/null
+++ b/setuptools/_vendor/wheel/_commands/pack.py
@@ -0,0 +1,84 @@
+from __future__ import annotations
+
+import email.policy
+import os.path
+import re
+from email.generator import BytesGenerator
+from email.parser import BytesParser
+
+from ..wheelfile import WheelError, WheelFile
+
+DIST_INFO_RE = re.compile(r"^(?P(?P.+?)-(?P\d.*?))\.dist-info$")
+
+
+def pack(directory: str, dest_dir: str, build_number: str | None) -> None:
+    """Repack a previously unpacked wheel directory into a new wheel file.
+
+    The .dist-info/WHEEL file must contain one or more tags so that the target
+    wheel file name can be determined.
+
+    :param directory: The unpacked wheel directory
+    :param dest_dir: Destination directory (defaults to the current directory)
+    """
+    # Find the .dist-info directory
+    dist_info_dirs = [
+        fn
+        for fn in os.listdir(directory)
+        if os.path.isdir(os.path.join(directory, fn)) and DIST_INFO_RE.match(fn)
+    ]
+    if len(dist_info_dirs) > 1:
+        raise WheelError(f"Multiple .dist-info directories found in {directory}")
+    elif not dist_info_dirs:
+        raise WheelError(f"No .dist-info directories found in {directory}")
+
+    # Determine the target wheel filename
+    dist_info_dir = dist_info_dirs[0]
+    name_version = DIST_INFO_RE.match(dist_info_dir).group("namever")
+
+    # Read the tags and the existing build number from .dist-info/WHEEL
+    wheel_file_path = os.path.join(directory, dist_info_dir, "WHEEL")
+    with open(wheel_file_path, "rb") as f:
+        info = BytesParser(policy=email.policy.compat32).parse(f)
+        tags: list[str] = info.get_all("Tag", [])
+        existing_build_number = info.get("Build")
+
+        if not tags:
+            raise WheelError(
+                f"No tags present in {dist_info_dir}/WHEEL; cannot determine target "
+                f"wheel filename"
+            )
+
+    # Set the wheel file name and add/replace/remove the Build tag in .dist-info/WHEEL
+    build_number = build_number if build_number is not None else existing_build_number
+    if build_number is not None:
+        del info["Build"]
+        if build_number:
+            info["Build"] = build_number
+            name_version += "-" + build_number
+
+        if build_number != existing_build_number:
+            with open(wheel_file_path, "wb") as f:
+                BytesGenerator(f, maxheaderlen=0).flatten(info)
+
+    # Reassemble the tags for the wheel file
+    tagline = compute_tagline(tags)
+
+    # Repack the wheel
+    wheel_path = os.path.join(dest_dir, f"{name_version}-{tagline}.whl")
+    with WheelFile(wheel_path, "w") as wf:
+        print(f"Repacking wheel as {wheel_path}...", end="", flush=True)
+        wf.write_files(directory)
+
+    print("OK")
+
+
+def compute_tagline(tags: list[str]) -> str:
+    """Compute a tagline from a list of tags.
+
+    :param tags: A list of tags
+    :return: A tagline
+    """
+    impls = sorted({tag.split("-")[0] for tag in tags})
+    abivers = sorted({tag.split("-")[1] for tag in tags})
+    platforms = sorted({tag.split("-")[2] for tag in tags})
+    return "-".join([".".join(impls), ".".join(abivers), ".".join(platforms)])
diff --git a/setuptools/_vendor/wheel/_commands/tags.py b/setuptools/_vendor/wheel/_commands/tags.py
new file mode 100644
index 0000000000..cec896b55b
--- /dev/null
+++ b/setuptools/_vendor/wheel/_commands/tags.py
@@ -0,0 +1,140 @@
+from __future__ import annotations
+
+import email.policy
+import itertools
+import os
+from collections.abc import Iterable
+from email.parser import BytesParser
+
+from ..wheelfile import WheelFile
+
+
+def _compute_tags(original_tags: Iterable[str], new_tags: str | None) -> set[str]:
+    """Add or replace tags. Supports dot-separated tags"""
+    if new_tags is None:
+        return set(original_tags)
+
+    if new_tags.startswith("+"):
+        return {*original_tags, *new_tags[1:].split(".")}
+
+    if new_tags.startswith("-"):
+        return set(original_tags) - set(new_tags[1:].split("."))
+
+    return set(new_tags.split("."))
+
+
+def tags(
+    wheel: str,
+    python_tags: str | None = None,
+    abi_tags: str | None = None,
+    platform_tags: str | None = None,
+    build_tag: str | None = None,
+    remove: bool = False,
+) -> str:
+    """Change the tags on a wheel file.
+
+    The tags are left unchanged if they are not specified. To specify "none",
+    use ["none"]. To append to the previous tags, a tag should start with a
+    "+".  If a tag starts with "-", it will be removed from existing tags.
+    Processing is done left to right.
+
+    :param wheel: The paths to the wheels
+    :param python_tags: The Python tags to set
+    :param abi_tags: The ABI tags to set
+    :param platform_tags: The platform tags to set
+    :param build_tag: The build tag to set
+    :param remove: Remove the original wheel
+    """
+    with WheelFile(wheel, "r") as f:
+        assert f.filename, f"{f.filename} must be available"
+
+        wheel_info = f.read(f.dist_info_path + "/WHEEL")
+        info = BytesParser(policy=email.policy.compat32).parsebytes(wheel_info)
+
+        original_wheel_name = os.path.basename(f.filename)
+        namever = f.parsed_filename.group("namever")
+        build = f.parsed_filename.group("build")
+        original_python_tags = f.parsed_filename.group("pyver").split(".")
+        original_abi_tags = f.parsed_filename.group("abi").split(".")
+        original_plat_tags = f.parsed_filename.group("plat").split(".")
+
+    tags: list[str] = info.get_all("Tag", [])
+    existing_build_tag = info.get("Build")
+
+    impls = {tag.split("-")[0] for tag in tags}
+    abivers = {tag.split("-")[1] for tag in tags}
+    platforms = {tag.split("-")[2] for tag in tags}
+
+    if impls != set(original_python_tags):
+        msg = f"Wheel internal tags {impls!r} != filename tags {original_python_tags!r}"
+        raise AssertionError(msg)
+
+    if abivers != set(original_abi_tags):
+        msg = f"Wheel internal tags {abivers!r} != filename tags {original_abi_tags!r}"
+        raise AssertionError(msg)
+
+    if platforms != set(original_plat_tags):
+        msg = (
+            f"Wheel internal tags {platforms!r} != filename tags {original_plat_tags!r}"
+        )
+        raise AssertionError(msg)
+
+    if existing_build_tag != build:
+        msg = (
+            f"Incorrect filename '{build}' "
+            f"& *.dist-info/WHEEL '{existing_build_tag}' build numbers"
+        )
+        raise AssertionError(msg)
+
+    # Start changing as needed
+    if build_tag is not None:
+        build = build_tag
+
+    final_python_tags = sorted(_compute_tags(original_python_tags, python_tags))
+    final_abi_tags = sorted(_compute_tags(original_abi_tags, abi_tags))
+    final_plat_tags = sorted(_compute_tags(original_plat_tags, platform_tags))
+
+    final_tags = [
+        namever,
+        ".".join(final_python_tags),
+        ".".join(final_abi_tags),
+        ".".join(final_plat_tags),
+    ]
+    if build:
+        final_tags.insert(1, build)
+
+    final_wheel_name = "-".join(final_tags) + ".whl"
+
+    if original_wheel_name != final_wheel_name:
+        del info["Tag"], info["Build"]
+        for a, b, c in itertools.product(
+            final_python_tags, final_abi_tags, final_plat_tags
+        ):
+            info["Tag"] = f"{a}-{b}-{c}"
+        if build:
+            info["Build"] = build
+
+        original_wheel_path = os.path.join(
+            os.path.dirname(f.filename), original_wheel_name
+        )
+        final_wheel_path = os.path.join(os.path.dirname(f.filename), final_wheel_name)
+
+        with (
+            WheelFile(original_wheel_path, "r") as fin,
+            WheelFile(final_wheel_path, "w") as fout,
+        ):
+            fout.comment = fin.comment  # preserve the comment
+            for item in fin.infolist():
+                if item.is_dir():
+                    continue
+                if item.filename == f.dist_info_path + "/RECORD":
+                    continue
+                if item.filename == f.dist_info_path + "/WHEEL":
+                    fout.writestr(item, info.as_bytes())
+                else:
+                    fout.writestr(item, fin.read(item))
+
+        if remove:
+            os.remove(original_wheel_path)
+
+    return final_wheel_name
diff --git a/setuptools/_vendor/wheel/_commands/unpack.py b/setuptools/_vendor/wheel/_commands/unpack.py
new file mode 100644
index 0000000000..83dc7423f8
--- /dev/null
+++ b/setuptools/_vendor/wheel/_commands/unpack.py
@@ -0,0 +1,30 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+from ..wheelfile import WheelFile
+
+
+def unpack(path: str, dest: str = ".") -> None:
+    """Unpack a wheel.
+
+    Wheel content will be unpacked to {dest}/{name}-{ver}, where {name}
+    is the package name and {ver} its version.
+
+    :param path: The path to the wheel.
+    :param dest: Destination directory (default to current directory).
+    """
+    with WheelFile(path) as wf:
+        namever = wf.parsed_filename.group("namever")
+        destination = Path(dest) / namever
+        print(f"Unpacking to: {destination}...", end="", flush=True)
+        for zinfo in wf.filelist:
+            target_path = Path(wf.extract(zinfo, destination))
+
+            # Set permissions to the same values as they were set in the archive
+            # We have to do this manually due to
+            # https://github.com/python/cpython/issues/59999
+            permissions = zinfo.external_attr >> 16 & 0o777
+            target_path.chmod(permissions)
+
+    print("OK")
diff --git a/setuptools/_vendor/wheel/_metadata.py b/setuptools/_vendor/wheel/_metadata.py
new file mode 100644
index 0000000000..e17a7b9245
--- /dev/null
+++ b/setuptools/_vendor/wheel/_metadata.py
@@ -0,0 +1,184 @@
+"""
+Tools for converting old- to new-style metadata.
+"""
+
+from __future__ import annotations
+
+import functools
+import itertools
+import os.path
+import re
+import textwrap
+from collections.abc import Generator, Iterable, Iterator
+from email.message import Message
+from email.parser import Parser
+from typing import Literal
+
+from packaging.requirements import Requirement
+
+
+def _nonblank(str: str) -> bool | Literal[""]:
+    return str and not str.startswith("#")
+
+
+@functools.singledispatch
+def yield_lines(iterable: Iterable[str]) -> Iterator[str]:
+    r"""
+    Yield valid lines of a string or iterable.
+    >>> list(yield_lines(''))
+    []
+    >>> list(yield_lines(['foo', 'bar']))
+    ['foo', 'bar']
+    >>> list(yield_lines('foo\nbar'))
+    ['foo', 'bar']
+    >>> list(yield_lines('\nfoo\n#bar\nbaz #comment'))
+    ['foo', 'baz #comment']
+    >>> list(yield_lines(['foo\nbar', 'baz', 'bing\n\n\n']))
+    ['foo', 'bar', 'baz', 'bing']
+    """
+    return itertools.chain.from_iterable(map(yield_lines, iterable))
+
+
+@yield_lines.register(str)
+def _(text: str) -> Iterator[str]:
+    return filter(_nonblank, map(str.strip, text.splitlines()))
+
+
+def split_sections(
+    s: str | Iterator[str],
+) -> Generator[tuple[str | None, list[str]], None, None]:
+    """Split a string or iterable thereof into (section, content) pairs
+    Each ``section`` is a stripped version of the section header ("[section]")
+    and each ``content`` is a list of stripped lines excluding blank lines and
+    comment-only lines.  If there are any such lines before the first section
+    header, they're returned in a first ``section`` of ``None``.
+    """
+    section = None
+    content: list[str] = []
+    for line in yield_lines(s):
+        if line.startswith("["):
+            if line.endswith("]"):
+                if section or content:
+                    yield section, content
+                section = line[1:-1].strip()
+                content = []
+            else:
+                raise ValueError("Invalid section heading", line)
+        else:
+            content.append(line)
+
+    # wrap up last segment
+    yield section, content
+
+
+def safe_extra(extra: str) -> str:
+    """Convert an arbitrary string to a standard 'extra' name
+    Any runs of non-alphanumeric characters are replaced with a single '_',
+    and the result is always lowercased.
+    """
+    return re.sub("[^A-Za-z0-9.-]+", "_", extra).lower()
+
+
+def safe_name(name: str) -> str:
+    """Convert an arbitrary string to a standard distribution name
+    Any runs of non-alphanumeric/. characters are replaced with a single '-'.
+    """
+    return re.sub("[^A-Za-z0-9.]+", "-", name)
+
+
+def requires_to_requires_dist(requirement: Requirement) -> str:
+    """Return the version specifier for a requirement in PEP 345/566 fashion."""
+    if requirement.url:
+        return " @ " + requirement.url
+
+    requires_dist: list[str] = []
+    for spec in requirement.specifier:
+        requires_dist.append(spec.operator + spec.version)
+
+    if requires_dist:
+        return " " + ",".join(sorted(requires_dist))
+    else:
+        return ""
+
+
+def convert_requirements(requirements: list[str]) -> Iterator[str]:
+    """Yield Requires-Dist: strings for parsed requirements strings."""
+    for req in requirements:
+        parsed_requirement = Requirement(req)
+        spec = requires_to_requires_dist(parsed_requirement)
+        extras = ",".join(sorted(safe_extra(e) for e in parsed_requirement.extras))
+        if extras:
+            extras = f"[{extras}]"
+
+        yield safe_name(parsed_requirement.name) + extras + spec
+
+
+def generate_requirements(
+    extras_require: dict[str | None, list[str]],
+) -> Iterator[tuple[str, str]]:
+    """
+    Convert requirements from a setup()-style dictionary to
+    ('Requires-Dist', 'requirement') and ('Provides-Extra', 'extra') tuples.
+
+    extras_require is a dictionary of {extra: [requirements]} as passed to setup(),
+    using the empty extra {'': [requirements]} to hold install_requires.
+    """
+    for extra, depends in extras_require.items():
+        condition = ""
+        extra = extra or ""
+        if ":" in extra:  # setuptools extra:condition syntax
+            extra, condition = extra.split(":", 1)
+
+        extra = safe_extra(extra)
+        if extra:
+            yield "Provides-Extra", extra
+            if condition:
+                condition = "(" + condition + ") and "
+            condition += f"extra == '{extra}'"
+
+        if condition:
+            condition = " ; " + condition
+
+        for new_req in convert_requirements(depends):
+            canonical_req = str(Requirement(new_req + condition))
+            yield "Requires-Dist", canonical_req
+
+
+def pkginfo_to_metadata(egg_info_path: str, pkginfo_path: str) -> Message:
+    """
+    Convert .egg-info directory with PKG-INFO to the Metadata 2.1 format
+    """
+    with open(pkginfo_path, encoding="utf-8") as headers:
+        pkg_info = Parser().parse(headers)
+
+    pkg_info.replace_header("Metadata-Version", "2.1")
+    # Those will be regenerated from `requires.txt`.
+    del pkg_info["Provides-Extra"]
+    del pkg_info["Requires-Dist"]
+    requires_path = os.path.join(egg_info_path, "requires.txt")
+    if os.path.exists(requires_path):
+        with open(requires_path, encoding="utf-8") as requires_file:
+            requires = requires_file.read()
+
+        parsed_requirements = sorted(split_sections(requires), key=lambda x: x[0] or "")
+        for extra, reqs in parsed_requirements:
+            for key, value in generate_requirements({extra: reqs}):
+                if (key, value) not in pkg_info.items():
+                    pkg_info[key] = value
+
+    description = pkg_info["Description"]
+    if description:
+        description_lines = pkg_info["Description"].splitlines()
+        dedented_description = "\n".join(
+            # if the first line of long_description is blank,
+            # the first line here will be indented.
+            (
+                description_lines[0].lstrip(),
+                textwrap.dedent("\n".join(description_lines[1:])),
+                "\n",
+            )
+        )
+        pkg_info.set_payload(dedented_description)
+        del pkg_info["Description"]
+
+    return pkg_info
diff --git a/setuptools/_vendor/wheel/_setuptools_logging.py b/setuptools/_vendor/wheel/_setuptools_logging.py
new file mode 100644
index 0000000000..a1a2482ba2
--- /dev/null
+++ b/setuptools/_vendor/wheel/_setuptools_logging.py
@@ -0,0 +1,26 @@
+# copied from setuptools.logging, omitting monkeypatching
+from __future__ import annotations
+
+import logging
+import sys
+
+
+def _not_warning(record: logging.LogRecord) -> bool:
+    return record.levelno < logging.WARNING
+
+
+def configure() -> None:
+    """
+    Configure logging to emit warning and above to stderr
+    and everything else to stdout. This behavior is provided
+    for compatibility with distutils.log but may change in
+    the future.
+    """
+    err_handler = logging.StreamHandler()
+    err_handler.setLevel(logging.WARNING)
+    out_handler = logging.StreamHandler(sys.stdout)
+    out_handler.addFilter(_not_warning)
+    handlers = err_handler, out_handler
+    logging.basicConfig(
+        format="{message}", style="{", handlers=handlers, level=logging.DEBUG
+    )
diff --git a/setuptools/_vendor/wheel/bdist_wheel.py b/setuptools/_vendor/wheel/bdist_wheel.py
new file mode 100644
index 0000000000..24199c246d
--- /dev/null
+++ b/setuptools/_vendor/wheel/bdist_wheel.py
@@ -0,0 +1,26 @@
+from typing import TYPE_CHECKING
+from warnings import warn
+
+warn(
+    "The 'wheel' package is no longer the canonical location of the 'bdist_wheel' "
+    "command, and will be removed in a future release. Please update to setuptools "
+    "v70.1 or later which contains an integrated version of this command.",
+    FutureWarning,
+    stacklevel=1,
+)
+
+if TYPE_CHECKING:
+    from ._bdist_wheel import bdist_wheel as bdist_wheel
+else:
+    try:
+        # Better integration/compatibility with setuptools:
+        # in the case new fixes or PEPs are implemented in setuptools
+        # there is no need to backport them to the deprecated code base.
+        # This is useful in the case of old packages in the ecosystem
+        # that are still used but have low maintenance.
+        from setuptools.command.bdist_wheel import bdist_wheel
+    except ImportError:
+        # Only used in the case of old setuptools versions.
+        # If the user wants to get the latest fixes/PEPs,
+        # they are encouraged to address the deprecation warning.
+        from ._bdist_wheel import bdist_wheel as bdist_wheel
diff --git a/setuptools/_vendor/wheel/macosx_libfile.py b/setuptools/_vendor/wheel/macosx_libfile.py
new file mode 100644
index 0000000000..06e51af299
--- /dev/null
+++ b/setuptools/_vendor/wheel/macosx_libfile.py
@@ -0,0 +1,486 @@
+"""
+IMPORTANT: DO NOT IMPORT THIS MODULE DIRECTLY.
+THIS IS ONLY KEPT IN PLACE FOR BACKWARDS COMPATIBILITY WITH
+setuptools.command.bdist_wheel.
+
+This module contains function to analyse dynamic library
+headers to extract system information
+
+Currently only for MacOSX
+
+Library file on macosx system starts with Mach-O or Fat field.
+This can be distinguish by first 32 bites and it is called magic number.
+Proper value of magic number is with suffix _MAGIC. Suffix _CIGAM means
+reversed bytes order.
+Both fields can occur in two types: 32 and 64 bytes.
+
+FAT field inform that this library contains few version of library
+(typically for different types version). It contains
+information where Mach-O headers starts.
+
+Each section started with Mach-O header contains one library
+(So if file starts with this field it contains only one version).
+
+After filed Mach-O there are section fields.
+Each of them starts with two fields:
+cmd - magic number for this command
+cmdsize - total size occupied by this section information.
+
+In this case only sections LC_VERSION_MIN_MACOSX (for macosx 10.13 and earlier)
+and LC_BUILD_VERSION (for macosx 10.14 and newer) are interesting,
+because them contains information about minimal system version.
+
+Important remarks:
+- For fat files this implementation looks for maximum number version.
+  It not check if it is 32 or 64 and do not compare it with currently built package.
+  So it is possible to false report higher version that needed.
+- All structures signatures are taken form macosx header files.
+- I think that binary format will be more stable than `otool` output.
+  and if apple introduce some changes both implementation will need to be updated.
+- The system compile will set the deployment target no lower than
+  11.0 for arm64 builds. For "Universal 2" builds use the x86_64 deployment
+  target when the arm64 target is 11.0.
+"""
+
+from __future__ import annotations
+
+import ctypes
+import os
+import sys
+from io import BufferedIOBase
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Union
+
+    StrPath = Union[str, os.PathLike[str]]
+
+"""here the needed const and struct from mach-o header files"""
+
+FAT_MAGIC = 0xCAFEBABE
+FAT_CIGAM = 0xBEBAFECA
+FAT_MAGIC_64 = 0xCAFEBABF
+FAT_CIGAM_64 = 0xBFBAFECA
+MH_MAGIC = 0xFEEDFACE
+MH_CIGAM = 0xCEFAEDFE
+MH_MAGIC_64 = 0xFEEDFACF
+MH_CIGAM_64 = 0xCFFAEDFE
+
+LC_VERSION_MIN_MACOSX = 0x24
+LC_BUILD_VERSION = 0x32
+
+CPU_TYPE_ARM64 = 0x0100000C
+
+mach_header_fields = [
+    ("magic", ctypes.c_uint32),
+    ("cputype", ctypes.c_int),
+    ("cpusubtype", ctypes.c_int),
+    ("filetype", ctypes.c_uint32),
+    ("ncmds", ctypes.c_uint32),
+    ("sizeofcmds", ctypes.c_uint32),
+    ("flags", ctypes.c_uint32),
+]
+"""
+struct mach_header {
+    uint32_t	magic;		/* mach magic number identifier */
+    cpu_type_t	cputype;	/* cpu specifier */
+    cpu_subtype_t	cpusubtype;	/* machine specifier */
+    uint32_t	filetype;	/* type of file */
+    uint32_t	ncmds;		/* number of load commands */
+    uint32_t	sizeofcmds;	/* the size of all the load commands */
+    uint32_t	flags;		/* flags */
+};
+typedef integer_t cpu_type_t;
+typedef integer_t cpu_subtype_t;
+"""
+
+mach_header_fields_64 = mach_header_fields + [("reserved", ctypes.c_uint32)]
+"""
+struct mach_header_64 {
+    uint32_t	magic;		/* mach magic number identifier */
+    cpu_type_t	cputype;	/* cpu specifier */
+    cpu_subtype_t	cpusubtype;	/* machine specifier */
+    uint32_t	filetype;	/* type of file */
+    uint32_t	ncmds;		/* number of load commands */
+    uint32_t	sizeofcmds;	/* the size of all the load commands */
+    uint32_t	flags;		/* flags */
+    uint32_t	reserved;	/* reserved */
+};
+"""
+
+fat_header_fields = [("magic", ctypes.c_uint32), ("nfat_arch", ctypes.c_uint32)]
+"""
+struct fat_header {
+    uint32_t	magic;		/* FAT_MAGIC or FAT_MAGIC_64 */
+    uint32_t	nfat_arch;	/* number of structs that follow */
+};
+"""
+
+fat_arch_fields = [
+    ("cputype", ctypes.c_int),
+    ("cpusubtype", ctypes.c_int),
+    ("offset", ctypes.c_uint32),
+    ("size", ctypes.c_uint32),
+    ("align", ctypes.c_uint32),
+]
+"""
+struct fat_arch {
+    cpu_type_t	cputype;	/* cpu specifier (int) */
+    cpu_subtype_t	cpusubtype;	/* machine specifier (int) */
+    uint32_t	offset;		/* file offset to this object file */
+    uint32_t	size;		/* size of this object file */
+    uint32_t	align;		/* alignment as a power of 2 */
+};
+"""
+
+fat_arch_64_fields = [
+    ("cputype", ctypes.c_int),
+    ("cpusubtype", ctypes.c_int),
+    ("offset", ctypes.c_uint64),
+    ("size", ctypes.c_uint64),
+    ("align", ctypes.c_uint32),
+    ("reserved", ctypes.c_uint32),
+]
+"""
+struct fat_arch_64 {
+    cpu_type_t	cputype;	/* cpu specifier (int) */
+    cpu_subtype_t	cpusubtype;	/* machine specifier (int) */
+    uint64_t	offset;		/* file offset to this object file */
+    uint64_t	size;		/* size of this object file */
+    uint32_t	align;		/* alignment as a power of 2 */
+    uint32_t	reserved;	/* reserved */
+};
+"""
+
+segment_base_fields = [("cmd", ctypes.c_uint32), ("cmdsize", ctypes.c_uint32)]
+"""base for reading segment info"""
+
+segment_command_fields = [
+    ("cmd", ctypes.c_uint32),
+    ("cmdsize", ctypes.c_uint32),
+    ("segname", ctypes.c_char * 16),
+    ("vmaddr", ctypes.c_uint32),
+    ("vmsize", ctypes.c_uint32),
+    ("fileoff", ctypes.c_uint32),
+    ("filesize", ctypes.c_uint32),
+    ("maxprot", ctypes.c_int),
+    ("initprot", ctypes.c_int),
+    ("nsects", ctypes.c_uint32),
+    ("flags", ctypes.c_uint32),
+]
+"""
+struct segment_command { /* for 32-bit architectures */
+    uint32_t	cmd;		/* LC_SEGMENT */
+    uint32_t	cmdsize;	/* includes sizeof section structs */
+    char		segname[16];	/* segment name */
+    uint32_t	vmaddr;		/* memory address of this segment */
+    uint32_t	vmsize;		/* memory size of this segment */
+    uint32_t	fileoff;	/* file offset of this segment */
+    uint32_t	filesize;	/* amount to map from the file */
+    vm_prot_t	maxprot;	/* maximum VM protection */
+    vm_prot_t	initprot;	/* initial VM protection */
+    uint32_t	nsects;		/* number of sections in segment */
+    uint32_t	flags;		/* flags */
+};
+typedef int vm_prot_t;
+"""
+
+segment_command_fields_64 = [
+    ("cmd", ctypes.c_uint32),
+    ("cmdsize", ctypes.c_uint32),
+    ("segname", ctypes.c_char * 16),
+    ("vmaddr", ctypes.c_uint64),
+    ("vmsize", ctypes.c_uint64),
+    ("fileoff", ctypes.c_uint64),
+    ("filesize", ctypes.c_uint64),
+    ("maxprot", ctypes.c_int),
+    ("initprot", ctypes.c_int),
+    ("nsects", ctypes.c_uint32),
+    ("flags", ctypes.c_uint32),
+]
+"""
+struct segment_command_64 { /* for 64-bit architectures */
+    uint32_t	cmd;		/* LC_SEGMENT_64 */
+    uint32_t	cmdsize;	/* includes sizeof section_64 structs */
+    char		segname[16];	/* segment name */
+    uint64_t	vmaddr;		/* memory address of this segment */
+    uint64_t	vmsize;		/* memory size of this segment */
+    uint64_t	fileoff;	/* file offset of this segment */
+    uint64_t	filesize;	/* amount to map from the file */
+    vm_prot_t	maxprot;	/* maximum VM protection */
+    vm_prot_t	initprot;	/* initial VM protection */
+    uint32_t	nsects;		/* number of sections in segment */
+    uint32_t	flags;		/* flags */
+};
+"""
+
+version_min_command_fields = segment_base_fields + [
+    ("version", ctypes.c_uint32),
+    ("sdk", ctypes.c_uint32),
+]
+"""
+struct version_min_command {
+    uint32_t	cmd;		/* LC_VERSION_MIN_MACOSX or
+                               LC_VERSION_MIN_IPHONEOS or
+                               LC_VERSION_MIN_WATCHOS or
+                               LC_VERSION_MIN_TVOS */
+    uint32_t	cmdsize;	/* sizeof(struct min_version_command) */
+    uint32_t	version;	/* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+    uint32_t	sdk;		/* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+};
+"""
+
+build_version_command_fields = segment_base_fields + [
+    ("platform", ctypes.c_uint32),
+    ("minos", ctypes.c_uint32),
+    ("sdk", ctypes.c_uint32),
+    ("ntools", ctypes.c_uint32),
+]
+"""
+struct build_version_command {
+    uint32_t	cmd;		/* LC_BUILD_VERSION */
+    uint32_t	cmdsize;	/* sizeof(struct build_version_command) plus */
+                                /* ntools * sizeof(struct build_tool_version) */
+    uint32_t	platform;	/* platform */
+    uint32_t	minos;		/* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+    uint32_t	sdk;		/* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+    uint32_t	ntools;		/* number of tool entries following this */
+};
+"""
+
+
+def swap32(x: int) -> int:
+    return (
+        ((x << 24) & 0xFF000000)
+        | ((x << 8) & 0x00FF0000)
+        | ((x >> 8) & 0x0000FF00)
+        | ((x >> 24) & 0x000000FF)
+    )
+
+
+def get_base_class_and_magic_number(
+    lib_file: BufferedIOBase,
+    seek: int | None = None,
+) -> tuple[type[ctypes.Structure], int]:
+    if seek is None:
+        seek = lib_file.tell()
+    else:
+        lib_file.seek(seek)
+    magic_number = ctypes.c_uint32.from_buffer_copy(
+        lib_file.read(ctypes.sizeof(ctypes.c_uint32))
+    ).value
+
+    # Handle wrong byte order
+    if magic_number in [FAT_CIGAM, FAT_CIGAM_64, MH_CIGAM, MH_CIGAM_64]:
+        if sys.byteorder == "little":
+            BaseClass = ctypes.BigEndianStructure
+        else:
+            BaseClass = ctypes.LittleEndianStructure
+
+        magic_number = swap32(magic_number)
+    else:
+        BaseClass = ctypes.Structure
+
+    lib_file.seek(seek)
+    return BaseClass, magic_number
+
+
+def read_data(struct_class: type[ctypes.Structure], lib_file: BufferedIOBase):
+    return struct_class.from_buffer_copy(lib_file.read(ctypes.sizeof(struct_class)))
+
+
+def extract_macosx_min_system_version(path_to_lib: str):
+    with open(path_to_lib, "rb") as lib_file:
+        BaseClass, magic_number = get_base_class_and_magic_number(lib_file, 0)
+        if magic_number not in [FAT_MAGIC, FAT_MAGIC_64, MH_MAGIC, MH_MAGIC_64]:
+            return
+
+        if magic_number in [FAT_MAGIC, FAT_CIGAM_64]:
+
+            class FatHeader(BaseClass):
+                _fields_ = fat_header_fields
+
+            fat_header = read_data(FatHeader, lib_file)
+            if magic_number == FAT_MAGIC:
+
+                class FatArch(BaseClass):
+                    _fields_ = fat_arch_fields
+
+            else:
+
+                class FatArch(BaseClass):
+                    _fields_ = fat_arch_64_fields
+
+            fat_arch_list = [
+                read_data(FatArch, lib_file) for _ in range(fat_header.nfat_arch)
+            ]
+
+            versions_list: list[tuple[int, int, int]] = []
+            for el in fat_arch_list:
+                try:
+                    version = read_mach_header(lib_file, el.offset)
+                    if version is not None:
+                        if el.cputype == CPU_TYPE_ARM64 and len(fat_arch_list) != 1:
+                            # Xcode will not set the deployment target below 11.0.0
+                            # for the arm64 architecture. Ignore the arm64 deployment
+                            # in fat binaries when the target is 11.0.0, that way
+                            # the other architectures can select a lower deployment
+                            # target.
+                            # This is safe because there is no arm64 variant for
+                            # macOS 10.15 or earlier.
+                            if version == (11, 0, 0):
+                                continue
+                        versions_list.append(version)
+                except ValueError:
+                    pass
+
+            if len(versions_list) > 0:
+                return max(versions_list)
+            else:
+                return None
+
+        else:
+            try:
+                return read_mach_header(lib_file, 0)
+            except ValueError:
+                """when some error during read library files"""
+                return None
+
+
+def read_mach_header(
+    lib_file: BufferedIOBase,
+    seek: int | None = None,
+) -> tuple[int, int, int] | None:
+    """
+    This function parses a Mach-O header and extracts
+    information about the minimal macOS version.
+
+    :param lib_file: reference to opened library file with pointer
+    """
+    base_class, magic_number = get_base_class_and_magic_number(lib_file, seek)
+    arch = "32" if magic_number == MH_MAGIC else "64"
+
+    class SegmentBase(base_class):
+        _fields_ = segment_base_fields
+
+    if arch == "32":
+
+        class MachHeader(base_class):
+            _fields_ = mach_header_fields
+
+    else:
+
+        class MachHeader(base_class):
+            _fields_ = mach_header_fields_64
+
+    mach_header = read_data(MachHeader, lib_file)
+    for _i in range(mach_header.ncmds):
+        pos = lib_file.tell()
+        segment_base = read_data(SegmentBase, lib_file)
+        lib_file.seek(pos)
+        if segment_base.cmd == LC_VERSION_MIN_MACOSX:
+
+            class VersionMinCommand(base_class):
+                _fields_ = version_min_command_fields
+
+            version_info = read_data(VersionMinCommand, lib_file)
+            return parse_version(version_info.version)
+        elif segment_base.cmd == LC_BUILD_VERSION:
+
+            class VersionBuild(base_class):
+                _fields_ = build_version_command_fields
+
+            version_info = read_data(VersionBuild, lib_file)
+            return parse_version(version_info.minos)
+        else:
+            lib_file.seek(pos + segment_base.cmdsize)
+            continue
+
+
+def parse_version(version: int) -> tuple[int, int, int]:
+    x = (version & 0xFFFF0000) >> 16
+    y = (version & 0x0000FF00) >> 8
+    z = version & 0x000000FF
+    return x, y, z
+
+
+def calculate_macosx_platform_tag(archive_root: StrPath, platform_tag: str) -> str:
+    """
+    Calculate proper macosx platform tag basing on files which are included to wheel
+
+    Example platform tag `macosx-10.14-x86_64`
+    """
+    prefix, base_version, suffix = platform_tag.split("-")
+    base_version = tuple(int(x) for x in base_version.split("."))
+    base_version = base_version[:2]
+    if base_version[0] > 10:
+        base_version = (base_version[0], 0)
+    assert len(base_version) == 2
+    if "MACOSX_DEPLOYMENT_TARGET" in os.environ:
+        deploy_target = tuple(
+            int(x) for x in os.environ["MACOSX_DEPLOYMENT_TARGET"].split(".")
+        )
+        deploy_target = deploy_target[:2]
+        if deploy_target[0] > 10:
+            deploy_target = (deploy_target[0], 0)
+        if deploy_target < base_version:
+            sys.stderr.write(
+                "[WARNING] MACOSX_DEPLOYMENT_TARGET is set to a lower value ({}) than "
+                "the version on which the Python interpreter was compiled ({}), and "
+                "will be ignored.\n".format(
+                    ".".join(str(x) for x in deploy_target),
+                    ".".join(str(x) for x in base_version),
+                )
+            )
+        else:
+            base_version = deploy_target
+
+    assert len(base_version) == 2
+    start_version = base_version
+    versions_dict: dict[str, tuple[int, int]] = {}
+    for dirpath, _dirnames, filenames in os.walk(archive_root):
+        for filename in filenames:
+            if filename.endswith(".dylib") or filename.endswith(".so"):
+                lib_path = os.path.join(dirpath, filename)
+                min_ver = extract_macosx_min_system_version(lib_path)
+                if min_ver is not None:
+                    min_ver = min_ver[0:2]
+                    if min_ver[0] > 10:
+                        min_ver = (min_ver[0], 0)
+                    versions_dict[lib_path] = min_ver
+
+    if len(versions_dict) > 0:
+        base_version = max(base_version, max(versions_dict.values()))
+
+    # macosx platform tag do not support minor bugfix release
+    fin_base_version = "_".join([str(x) for x in base_version])
+    if start_version < base_version:
+        problematic_files = [k for k, v in versions_dict.items() if v > start_version]
+        problematic_files = "\n".join(problematic_files)
+        if len(problematic_files) == 1:
+            files_form = "this file"
+        else:
+            files_form = "these files"
+        error_message = (
+            "[WARNING] This wheel needs a higher macOS version than {}  "
+            "To silence this warning, set MACOSX_DEPLOYMENT_TARGET to at least "
+            + fin_base_version
+            + " or recreate "
+            + files_form
+            + " with lower "
+            "MACOSX_DEPLOYMENT_TARGET:  \n" + problematic_files
+        )
+
+        if "MACOSX_DEPLOYMENT_TARGET" in os.environ:
+            error_message = error_message.format(
+                "is set in MACOSX_DEPLOYMENT_TARGET variable."
+            )
+        else:
+            error_message = error_message.format(
+                "the version your Python interpreter is compiled against."
+            )
+
+        sys.stderr.write(error_message)
+
+    platform_tag = prefix + "_" + fin_base_version + "_" + suffix
+    return platform_tag
diff --git a/setuptools/_vendor/wheel/metadata.py b/setuptools/_vendor/wheel/metadata.py
new file mode 100644
index 0000000000..e27900a256
--- /dev/null
+++ b/setuptools/_vendor/wheel/metadata.py
@@ -0,0 +1,17 @@
+from warnings import warn
+
+from ._metadata import convert_requirements as convert_requirements
+from ._metadata import generate_requirements as generate_requirements
+from ._metadata import pkginfo_to_metadata as pkginfo_to_metadata
+from ._metadata import requires_to_requires_dist as requires_to_requires_dist
+from ._metadata import safe_extra as safe_extra
+from ._metadata import safe_name as safe_name
+from ._metadata import split_sections as split_sections
+
+warn(
+    f"The {__name__!r} package has been made private and should no longer be imported. "
+    f"Please either copy the code or find an alternative library to import it from, as "
+    f"this warning will be removed in a future version of 'wheel'.",
+    DeprecationWarning,
+    stacklevel=2,
+)
diff --git a/setuptools/_vendor/wheel/wheelfile.py b/setuptools/_vendor/wheel/wheelfile.py
new file mode 100644
index 0000000000..7b6fd71621
--- /dev/null
+++ b/setuptools/_vendor/wheel/wheelfile.py
@@ -0,0 +1,241 @@
+from __future__ import annotations
+
+__all__ = ["WHEEL_INFO_RE", "WheelFile", "WheelError"]
+
+import base64
+import csv
+import hashlib
+import logging
+import os.path
+import re
+import stat
+import time
+from io import StringIO, TextIOWrapper
+from typing import IO, TYPE_CHECKING, Literal
+from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo
+
+if TYPE_CHECKING:
+    from _typeshed import SizedBuffer, StrPath
+
+
+# Non-greedy matching of an optional build number may be too clever (more
+# invalid wheel filenames will match). Separate regex for .dist-info?
+WHEEL_INFO_RE = re.compile(
+    r"""^(?P(?P[^\s-]+?)-(?P[^\s-]+?))(-(?P\d[^\s-]*))?
+     -(?P[^\s-]+?)-(?P[^\s-]+?)-(?P\S+)\.whl$""",
+    re.VERBOSE,
+)
+MINIMUM_TIMESTAMP = 315532800  # 1980-01-01 00:00:00 UTC
+
+log = logging.getLogger("wheel")
+
+
+class WheelError(Exception):
+    pass
+
+
+def urlsafe_b64encode(data: bytes) -> bytes:
+    """urlsafe_b64encode without padding"""
+    return base64.urlsafe_b64encode(data).rstrip(b"=")
+
+
+def urlsafe_b64decode(data: bytes) -> bytes:
+    """urlsafe_b64decode without padding"""
+    pad = b"=" * (4 - (len(data) & 3))
+    return base64.urlsafe_b64decode(data + pad)
+
+
+def get_zipinfo_datetime(
+    timestamp: float | None = None,
+) -> tuple[int, int, int, int, int]:
+    # Some applications need reproducible .whl files, but they can't do this without
+    # forcing the timestamp of the individual ZipInfo objects. See issue #143.
+    timestamp = int(os.environ.get("SOURCE_DATE_EPOCH", timestamp or time.time()))
+    timestamp = max(timestamp, MINIMUM_TIMESTAMP)
+    return time.gmtime(timestamp)[0:6]
+
+
+class WheelFile(ZipFile):
+    """A ZipFile derivative class that also reads SHA-256 hashes from
+    .dist-info/RECORD and checks any read files against those.
+    """
+
+    _default_algorithm = hashlib.sha256
+
+    def __init__(
+        self,
+        file: StrPath,
+        mode: Literal["r", "w", "x", "a"] = "r",
+        compression: int = ZIP_DEFLATED,
+    ):
+        basename = os.path.basename(file)
+        self.parsed_filename = WHEEL_INFO_RE.match(basename)
+        if not basename.endswith(".whl") or self.parsed_filename is None:
+            raise WheelError(f"Bad wheel filename {basename!r}")
+
+        ZipFile.__init__(self, file, mode, compression=compression, allowZip64=True)
+
+        self.dist_info_path = "{}.dist-info".format(
+            self.parsed_filename.group("namever")
+        )
+        self.record_path = self.dist_info_path + "/RECORD"
+        self._file_hashes: dict[str, tuple[None, None] | tuple[int, bytes]] = {}
+        self._file_sizes = {}
+        if mode == "r":
+            # Ignore RECORD and any embedded wheel signatures
+            self._file_hashes[self.record_path] = None, None
+            self._file_hashes[self.record_path + ".jws"] = None, None
+            self._file_hashes[self.record_path + ".p7s"] = None, None
+
+            # Fill in the expected hashes by reading them from RECORD
+            try:
+                record = self.open(self.record_path)
+            except KeyError:
+                raise WheelError(f"Missing {self.record_path} file") from None
+
+            with record:
+                for line in csv.reader(
+                    TextIOWrapper(record, newline="", encoding="utf-8")
+                ):
+                    path, hash_sum, size = line
+                    if not hash_sum:
+                        continue
+
+                    algorithm, hash_sum = hash_sum.split("=")
+                    try:
+                        hashlib.new(algorithm)
+                    except ValueError:
+                        raise WheelError(
+                            f"Unsupported hash algorithm: {algorithm}"
+                        ) from None
+
+                    if algorithm.lower() in {"md5", "sha1"}:
+                        raise WheelError(
+                            f"Weak hash algorithm ({algorithm}) is not permitted by "
+                            f"PEP 427"
+                        )
+
+                    self._file_hashes[path] = (
+                        algorithm,
+                        urlsafe_b64decode(hash_sum.encode("ascii")),
+                    )
+
+    def open(
+        self,
+        name_or_info: str | ZipInfo,
+        mode: Literal["r", "w"] = "r",
+        pwd: bytes | None = None,
+    ) -> IO[bytes]:
+        def _update_crc(newdata: bytes) -> None:
+            eof = ef._eof
+            update_crc_orig(newdata)
+            running_hash.update(newdata)
+            if eof and running_hash.digest() != expected_hash:
+                raise WheelError(f"Hash mismatch for file '{ef_name}'")
+
+        ef_name = (
+            name_or_info.filename if isinstance(name_or_info, ZipInfo) else name_or_info
+        )
+        if (
+            mode == "r"
+            and not ef_name.endswith("/")
+            and ef_name not in self._file_hashes
+        ):
+            raise WheelError(f"No hash found for file '{ef_name}'")
+
+        ef = ZipFile.open(self, name_or_info, mode, pwd)
+        if mode == "r" and not ef_name.endswith("/"):
+            algorithm, expected_hash = self._file_hashes[ef_name]
+            if expected_hash is not None:
+                # Monkey patch the _update_crc method to also check for the hash from
+                # RECORD
+                running_hash = hashlib.new(algorithm)
+                update_crc_orig, ef._update_crc = ef._update_crc, _update_crc
+
+        return ef
+
+    def write_files(self, base_dir: str) -> None:
+        log.info("creating %r and adding %r to it", self.filename, base_dir)
+        deferred: list[tuple[str, str]] = []
+        for root, dirnames, filenames in os.walk(base_dir):
+            # Sort the directory names so that `os.walk` will walk them in a
+            # defined order on the next iteration.
+            dirnames.sort()
+            for name in sorted(filenames):
+                path = os.path.normpath(os.path.join(root, name))
+                if os.path.isfile(path):
+                    arcname = os.path.relpath(path, base_dir).replace(os.path.sep, "/")
+                    if arcname == self.record_path:
+                        pass
+                    elif root.endswith(".dist-info"):
+                        deferred.append((path, arcname))
+                    else:
+                        self.write(path, arcname)
+
+        deferred.sort()
+        for path, arcname in deferred:
+            self.write(path, arcname)
+
+    def write(
+        self,
+        filename: str,
+        arcname: str | None = None,
+        compress_type: int | None = None,
+    ) -> None:
+        with open(filename, "rb") as f:
+            st = os.fstat(f.fileno())
+            data = f.read()
+
+        zinfo = ZipInfo(
+            arcname or filename, date_time=get_zipinfo_datetime(st.st_mtime)
+        )
+        zinfo.external_attr = (stat.S_IMODE(st.st_mode) | stat.S_IFMT(st.st_mode)) << 16
+        zinfo.compress_type = compress_type or self.compression
+        self.writestr(zinfo, data, compress_type)
+
+    def writestr(
+        self,
+        zinfo_or_arcname: str | ZipInfo,
+        data: SizedBuffer | str,
+        compress_type: int | None = None,
+    ) -> None:
+        if isinstance(zinfo_or_arcname, str):
+            zinfo_or_arcname = ZipInfo(
+                zinfo_or_arcname, date_time=get_zipinfo_datetime()
+            )
+            zinfo_or_arcname.compress_type = self.compression
+            zinfo_or_arcname.external_attr = (0o664 | stat.S_IFREG) << 16
+
+        if isinstance(data, str):
+            data = data.encode("utf-8")
+
+        ZipFile.writestr(self, zinfo_or_arcname, data, compress_type)
+        fname = (
+            zinfo_or_arcname.filename
+            if isinstance(zinfo_or_arcname, ZipInfo)
+            else zinfo_or_arcname
+        )
+        log.info("adding %r", fname)
+        if fname != self.record_path:
+            hash_ = self._default_algorithm(data)
+            self._file_hashes[fname] = (
+                hash_.name,
+                urlsafe_b64encode(hash_.digest()).decode("ascii"),
+            )
+            self._file_sizes[fname] = len(data)
+
+    def close(self) -> None:
+        # Write RECORD
+        if self.fp is not None and self.mode == "w" and self._file_hashes:
+            data = StringIO()
+            writer = csv.writer(data, delimiter=",", quotechar='"', lineterminator="\n")
+            writer.writerows(
+                (
+                    (fname, algorithm + "=" + hash_, self._file_sizes[fname])
+                    for fname, (algorithm, hash_) in self._file_hashes.items()
+                )
+            )
+            writer.writerow((format(self.record_path), "", ""))
+            self.writestr(self.record_path, data.getvalue())
+
+        ZipFile.close(self)
diff --git a/setuptools/_vendor/zipp-3.23.0.dist-info/INSTALLER b/setuptools/_vendor/zipp-3.23.0.dist-info/INSTALLER
new file mode 100644
index 0000000000..5c69047b2e
--- /dev/null
+++ b/setuptools/_vendor/zipp-3.23.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/setuptools/_vendor/zipp-3.23.0.dist-info/METADATA b/setuptools/_vendor/zipp-3.23.0.dist-info/METADATA
new file mode 100644
index 0000000000..6420117987
--- /dev/null
+++ b/setuptools/_vendor/zipp-3.23.0.dist-info/METADATA
@@ -0,0 +1,106 @@
+Metadata-Version: 2.4
+Name: zipp
+Version: 3.23.0
+Summary: Backport of pathlib-compatible object wrapper for zip files
+Author-email: "Jason R. Coombs" 
+License-Expression: MIT
+Project-URL: Source, https://github.com/jaraco/zipp
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Requires-Python: >=3.9
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Provides-Extra: test
+Requires-Dist: pytest!=8.1.*,>=6; extra == "test"
+Requires-Dist: jaraco.itertools; extra == "test"
+Requires-Dist: jaraco.functools; extra == "test"
+Requires-Dist: more_itertools; extra == "test"
+Requires-Dist: big-O; extra == "test"
+Requires-Dist: pytest-ignore-flaky; extra == "test"
+Requires-Dist: jaraco.test; extra == "test"
+Provides-Extra: doc
+Requires-Dist: sphinx>=3.5; extra == "doc"
+Requires-Dist: jaraco.packaging>=9.3; extra == "doc"
+Requires-Dist: rst.linker>=1.9; extra == "doc"
+Requires-Dist: furo; extra == "doc"
+Requires-Dist: sphinx-lint; extra == "doc"
+Requires-Dist: jaraco.tidelift>=1.4; extra == "doc"
+Provides-Extra: check
+Requires-Dist: pytest-checkdocs>=2.4; extra == "check"
+Requires-Dist: pytest-ruff>=0.2.1; sys_platform != "cygwin" and extra == "check"
+Provides-Extra: cover
+Requires-Dist: pytest-cov; extra == "cover"
+Provides-Extra: enabler
+Requires-Dist: pytest-enabler>=2.2; extra == "enabler"
+Provides-Extra: type
+Requires-Dist: pytest-mypy; extra == "type"
+Dynamic: license-file
+
+.. image:: https://img.shields.io/pypi/v/zipp.svg
+   :target: https://pypi.org/project/zipp
+
+.. image:: https://img.shields.io/pypi/pyversions/zipp.svg
+
+.. image:: https://github.com/jaraco/zipp/actions/workflows/main.yml/badge.svg
+   :target: https://github.com/jaraco/zipp/actions?query=workflow%3A%22tests%22
+   :alt: tests
+
+.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json
+    :target: https://github.com/astral-sh/ruff
+    :alt: Ruff
+
+.. image:: https://readthedocs.org/projects/zipp/badge/?version=latest
+..    :target: https://zipp.readthedocs.io/en/latest/?badge=latest
+
+.. image:: https://img.shields.io/badge/skeleton-2025-informational
+   :target: https://blog.jaraco.com/skeleton
+
+.. image:: https://tidelift.com/badges/package/pypi/zipp
+   :target: https://tidelift.com/subscription/pkg/pypi-zipp?utm_source=pypi-zipp&utm_medium=readme
+
+
+A pathlib-compatible Zipfile object wrapper. Official backport of the standard library
+`Path object `_.
+
+
+Compatibility
+=============
+
+New features are introduced in this third-party library and later merged
+into CPython. The following table indicates which versions of this library
+were contributed to different versions in the standard library:
+
+.. list-table::
+   :header-rows: 1
+
+   * - zipp
+     - stdlib
+   * - 3.18
+     - 3.13
+   * - 3.16
+     - 3.12
+   * - 3.5
+     - 3.11
+   * - 3.2
+     - 3.10
+   * - 3.3 ??
+     - 3.9
+   * - 1.0
+     - 3.8
+
+
+Usage
+=====
+
+Use ``zipp.Path`` in place of ``zipfile.Path`` on any Python.
+
+For Enterprise
+==============
+
+Available as part of the Tidelift Subscription.
+
+This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
+
+`Learn more `_.
diff --git a/setuptools/_vendor/zipp-3.23.0.dist-info/RECORD b/setuptools/_vendor/zipp-3.23.0.dist-info/RECORD
new file mode 100644
index 0000000000..167e234a53
--- /dev/null
+++ b/setuptools/_vendor/zipp-3.23.0.dist-info/RECORD
@@ -0,0 +1,14 @@
+zipp-3.23.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+zipp-3.23.0.dist-info/METADATA,sha256=vdZ9TRbPC_O4k-fRjNPS13StuC837Zhbx3cMYHIms1s,3563
+zipp-3.23.0.dist-info/RECORD,,
+zipp-3.23.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+zipp-3.23.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
+zipp-3.23.0.dist-info/licenses/LICENSE,sha256=WlfLTbheKi3YjCkGKJCK3VfjRRRJ4KmnH9-zh3b9dZ0,1076
+zipp-3.23.0.dist-info/top_level.txt,sha256=iAbdoSHfaGqBfVb2XuR9JqSQHCoOsOtG6y9C_LSpqFw,5
+zipp/__init__.py,sha256=ieXh9GIMdABjKRX_JUJtP9k5wdBLK4Mt5X4nszSkmYE,11976
+zipp/_functools.py,sha256=f6Kt9LxZ4TE-cY1lJVdXSId3memSXmH9IdgMbU-_x2k,575
+zipp/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+zipp/compat/overlay.py,sha256=oEIGAnbr8yGjuKTrVSO2ByewPui71uppbX18BLnYTKE,783
+zipp/compat/py310.py,sha256=S7i6N9mToEn3asNb2ILyjnzvITOXrATD_J4emjyBbDU,256
+zipp/compat/py313.py,sha256=RndvDNtuY7H2D9ecnnzcPBMZ8mZc42gmXD_IwQAXXAE,654
+zipp/glob.py,sha256=DLV9LBsDxA6YVW82e3-tkoNrus1h4R-j3BR6VqS0AzE,3382
diff --git a/setuptools/_vendor/tomli-2.0.1.dist-info/REQUESTED b/setuptools/_vendor/zipp-3.23.0.dist-info/REQUESTED
similarity index 100%
rename from setuptools/_vendor/tomli-2.0.1.dist-info/REQUESTED
rename to setuptools/_vendor/zipp-3.23.0.dist-info/REQUESTED
diff --git a/setuptools/_vendor/zipp-3.23.0.dist-info/WHEEL b/setuptools/_vendor/zipp-3.23.0.dist-info/WHEEL
new file mode 100644
index 0000000000..e7fa31b6f3
--- /dev/null
+++ b/setuptools/_vendor/zipp-3.23.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (80.9.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/setuptools/_vendor/zipp-3.23.0.dist-info/licenses/LICENSE b/setuptools/_vendor/zipp-3.23.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000..f60bd57201
--- /dev/null
+++ b/setuptools/_vendor/zipp-3.23.0.dist-info/licenses/LICENSE
@@ -0,0 +1,18 @@
+MIT License
+
+Copyright (c) 2025 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
+following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial
+portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
+LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
+EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/pkg_resources/_vendor/zipp-3.7.0.dist-info/top_level.txt b/setuptools/_vendor/zipp-3.23.0.dist-info/top_level.txt
similarity index 100%
rename from pkg_resources/_vendor/zipp-3.7.0.dist-info/top_level.txt
rename to setuptools/_vendor/zipp-3.23.0.dist-info/top_level.txt
diff --git a/setuptools/_vendor/zipp-3.7.0.dist-info/INSTALLER b/setuptools/_vendor/zipp-3.7.0.dist-info/INSTALLER
deleted file mode 100644
index a1b589e38a..0000000000
--- a/setuptools/_vendor/zipp-3.7.0.dist-info/INSTALLER
+++ /dev/null
@@ -1 +0,0 @@
-pip
diff --git a/setuptools/_vendor/zipp-3.7.0.dist-info/LICENSE b/setuptools/_vendor/zipp-3.7.0.dist-info/LICENSE
deleted file mode 100644
index 353924be0e..0000000000
--- a/setuptools/_vendor/zipp-3.7.0.dist-info/LICENSE
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright Jason R. Coombs
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to
-deal in the Software without restriction, including without limitation the
-rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-sell copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-IN THE SOFTWARE.
diff --git a/setuptools/_vendor/zipp-3.7.0.dist-info/METADATA b/setuptools/_vendor/zipp-3.7.0.dist-info/METADATA
deleted file mode 100644
index b1308b5f6e..0000000000
--- a/setuptools/_vendor/zipp-3.7.0.dist-info/METADATA
+++ /dev/null
@@ -1,58 +0,0 @@
-Metadata-Version: 2.1
-Name: zipp
-Version: 3.7.0
-Summary: Backport of pathlib-compatible object wrapper for zip files
-Home-page: https://github.com/jaraco/zipp
-Author: Jason R. Coombs
-Author-email: jaraco@jaraco.com
-License: UNKNOWN
-Platform: UNKNOWN
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: MIT License
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3 :: Only
-Requires-Python: >=3.7
-License-File: LICENSE
-Provides-Extra: docs
-Requires-Dist: sphinx ; extra == 'docs'
-Requires-Dist: jaraco.packaging (>=8.2) ; extra == 'docs'
-Requires-Dist: rst.linker (>=1.9) ; extra == 'docs'
-Provides-Extra: testing
-Requires-Dist: pytest (>=6) ; extra == 'testing'
-Requires-Dist: pytest-checkdocs (>=2.4) ; extra == 'testing'
-Requires-Dist: pytest-flake8 ; extra == 'testing'
-Requires-Dist: pytest-cov ; extra == 'testing'
-Requires-Dist: pytest-enabler (>=1.0.1) ; extra == 'testing'
-Requires-Dist: jaraco.itertools ; extra == 'testing'
-Requires-Dist: func-timeout ; extra == 'testing'
-Requires-Dist: pytest-black (>=0.3.7) ; (platform_python_implementation != "PyPy") and extra == 'testing'
-Requires-Dist: pytest-mypy ; (platform_python_implementation != "PyPy") and extra == 'testing'
-
-.. image:: https://img.shields.io/pypi/v/zipp.svg
-   :target: `PyPI link`_
-
-.. image:: https://img.shields.io/pypi/pyversions/zipp.svg
-   :target: `PyPI link`_
-
-.. _PyPI link: https://pypi.org/project/zipp
-
-.. image:: https://github.com/jaraco/zipp/workflows/tests/badge.svg
-   :target: https://github.com/jaraco/zipp/actions?query=workflow%3A%22tests%22
-   :alt: tests
-
-.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
-   :target: https://github.com/psf/black
-   :alt: Code style: Black
-
-.. .. image:: https://readthedocs.org/projects/skeleton/badge/?version=latest
-..    :target: https://skeleton.readthedocs.io/en/latest/?badge=latest
-
-.. image:: https://img.shields.io/badge/skeleton-2021-informational
-   :target: https://blog.jaraco.com/skeleton
-
-
-A pathlib-compatible Zipfile object wrapper. Official backport of the standard library
-`Path object `_.
-
-
diff --git a/setuptools/_vendor/zipp-3.7.0.dist-info/RECORD b/setuptools/_vendor/zipp-3.7.0.dist-info/RECORD
deleted file mode 100644
index 0a88551ce0..0000000000
--- a/setuptools/_vendor/zipp-3.7.0.dist-info/RECORD
+++ /dev/null
@@ -1,9 +0,0 @@
-__pycache__/zipp.cpython-311.pyc,,
-zipp-3.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-zipp-3.7.0.dist-info/LICENSE,sha256=2z8CRrH5J48VhFuZ_sR4uLUG63ZIeZNyL4xuJUKF-vg,1050
-zipp-3.7.0.dist-info/METADATA,sha256=ZLzgaXTyZX_MxTU0lcGfhdPY4CjFrT_3vyQ2Fo49pl8,2261
-zipp-3.7.0.dist-info/RECORD,,
-zipp-3.7.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-zipp-3.7.0.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
-zipp-3.7.0.dist-info/top_level.txt,sha256=iAbdoSHfaGqBfVb2XuR9JqSQHCoOsOtG6y9C_LSpqFw,5
-zipp.py,sha256=ajztOH-9I7KA_4wqDYygtHa6xUBVZgFpmZ8FE74HHHI,8425
diff --git a/setuptools/_vendor/zipp-3.7.0.dist-info/REQUESTED b/setuptools/_vendor/zipp-3.7.0.dist-info/REQUESTED
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/setuptools/_vendor/zipp-3.7.0.dist-info/WHEEL b/setuptools/_vendor/zipp-3.7.0.dist-info/WHEEL
deleted file mode 100644
index becc9a66ea..0000000000
--- a/setuptools/_vendor/zipp-3.7.0.dist-info/WHEEL
+++ /dev/null
@@ -1,5 +0,0 @@
-Wheel-Version: 1.0
-Generator: bdist_wheel (0.37.1)
-Root-Is-Purelib: true
-Tag: py3-none-any
-
diff --git a/setuptools/_vendor/zipp-3.7.0.dist-info/top_level.txt b/setuptools/_vendor/zipp-3.7.0.dist-info/top_level.txt
deleted file mode 100644
index e82f676f82..0000000000
--- a/setuptools/_vendor/zipp-3.7.0.dist-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-zipp
diff --git a/setuptools/_vendor/zipp.py b/setuptools/_vendor/zipp/__init__.py
similarity index 55%
rename from setuptools/_vendor/zipp.py
rename to setuptools/_vendor/zipp/__init__.py
index 26b723c1fd..ed5b214632 100644
--- a/setuptools/_vendor/zipp.py
+++ b/setuptools/_vendor/zipp/__init__.py
@@ -1,16 +1,25 @@
+"""
+A Path-like interface for zipfiles.
+
+This codebase is shared between zipfile.Path in the stdlib
+and zipp in PyPI. See
+https://github.com/python/importlib_metadata/wiki/Development-Methodology
+for more detail.
+"""
+
+import functools
 import io
-import posixpath
-import zipfile
 import itertools
-import contextlib
-import sys
 import pathlib
+import posixpath
+import re
+import stat
+import sys
+import zipfile
 
-if sys.version_info < (3, 7):
-    from collections import OrderedDict
-else:
-    OrderedDict = dict
-
+from ._functools import save_method_args
+from .compat.py310 import text_encoding
+from .glob import Translator
 
 __all__ = ['Path']
 
@@ -37,7 +46,7 @@ def _parents(path):
 def _ancestry(path):
     """
     Given a path with elements separated by
-    posixpath.sep, generate all elements of that path
+    posixpath.sep, generate all elements of that path.
 
     >>> list(_ancestry('b/d'))
     ['b/d', 'b']
@@ -49,14 +58,19 @@ def _ancestry(path):
     ['b']
     >>> list(_ancestry(''))
     []
+
+    Multiple separators are treated like a single.
+
+    >>> list(_ancestry('//b//d///f//'))
+    ['//b//d///f', '//b//d', '//b']
     """
     path = path.rstrip(posixpath.sep)
-    while path and path != posixpath.sep:
+    while path.rstrip(posixpath.sep):
         yield path
         path, tail = posixpath.split(path)
 
 
-_dedupe = OrderedDict.fromkeys
+_dedupe = dict.fromkeys
 """Deduplicate an iterable in original order"""
 
 
@@ -68,10 +82,32 @@ def _difference(minuend, subtrahend):
     return itertools.filterfalse(set(subtrahend).__contains__, minuend)
 
 
-class CompleteDirs(zipfile.ZipFile):
+class InitializedState:
+    """
+    Mix-in to save the initialization state for pickling.
+    """
+
+    @save_method_args
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+
+    def __getstate__(self):
+        return self._saved___init__.args, self._saved___init__.kwargs
+
+    def __setstate__(self, state):
+        args, kwargs = state
+        super().__init__(*args, **kwargs)
+
+
+class CompleteDirs(InitializedState, zipfile.ZipFile):
     """
     A ZipFile subclass that ensures that implied directories
     are always included in the namelist.
+
+    >>> list(CompleteDirs._implied_dirs(['foo/bar.txt', 'foo/bar/baz.txt']))
+    ['foo/', 'foo/bar/']
+    >>> list(CompleteDirs._implied_dirs(['foo/bar.txt', 'foo/bar/baz.txt', 'foo/bar/']))
+    ['foo/']
     """
 
     @staticmethod
@@ -81,7 +117,7 @@ def _implied_dirs(names):
         return _dedupe(_difference(as_dirs, names))
 
     def namelist(self):
-        names = super(CompleteDirs, self).namelist()
+        names = super().namelist()
         return names + list(self._implied_dirs(names))
 
     def _name_set(self):
@@ -97,6 +133,17 @@ def resolve_dir(self, name):
         dir_match = name not in names and dirname in names
         return dirname if dir_match else name
 
+    def getinfo(self, name):
+        """
+        Supplement getinfo for implied dirs.
+        """
+        try:
+            return super().getinfo(name)
+        except KeyError:
+            if not name.endswith('/') or name not in self._name_set():
+                raise
+            return zipfile.ZipInfo(filename=name)
+
     @classmethod
     def make(cls, source):
         """
@@ -107,7 +154,7 @@ def make(cls, source):
             return source
 
         if not isinstance(source, zipfile.ZipFile):
-            return cls(_pathlib_compat(source))
+            return cls(source)
 
         # Only allow for FastLookup when supplied zipfile is read-only
         if 'r' not in source.mode:
@@ -116,6 +163,16 @@ def make(cls, source):
         source.__class__ = cls
         return source
 
+    @classmethod
+    def inject(cls, zf: zipfile.ZipFile) -> zipfile.ZipFile:
+        """
+        Given a writable zip file zf, inject directory entries for
+        any directories implied by the presence of children.
+        """
+        for name in cls._implied_dirs(zf.namelist()):
+            zf.writestr(name, b"")
+        return zf
+
 
 class FastLookup(CompleteDirs):
     """
@@ -124,32 +181,36 @@ class FastLookup(CompleteDirs):
     """
 
     def namelist(self):
-        with contextlib.suppress(AttributeError):
-            return self.__names
-        self.__names = super(FastLookup, self).namelist()
-        return self.__names
+        return self._namelist
+
+    @functools.cached_property
+    def _namelist(self):
+        return super().namelist()
 
     def _name_set(self):
-        with contextlib.suppress(AttributeError):
-            return self.__lookup
-        self.__lookup = super(FastLookup, self)._name_set()
-        return self.__lookup
+        return self._name_set_prop
 
+    @functools.cached_property
+    def _name_set_prop(self):
+        return super()._name_set()
 
-def _pathlib_compat(path):
-    """
-    For path-like objects, convert to a filename for compatibility
-    on Python 3.6.1 and earlier.
-    """
-    try:
-        return path.__fspath__()
-    except AttributeError:
-        return str(path)
+
+def _extract_text_encoding(encoding=None, *args, **kwargs):
+    # compute stack level so that the caller of the caller sees any warning.
+    is_pypy = sys.implementation.name == 'pypy'
+    # PyPy no longer special cased after 7.3.19 (or maybe 7.3.18)
+    # See jaraco/zipp#143
+    is_old_pypi = is_pypy and sys.pypy_version_info < (7, 3, 19)
+    stack_level = 3 + is_old_pypi
+    return text_encoding(encoding, stack_level), args, kwargs
 
 
 class Path:
     """
-    A pathlib-compatible interface for zip files.
+    A :class:`importlib.resources.abc.Traversable` interface for zip files.
+
+    Implements many of the features users enjoy from
+    :class:`pathlib.Path`.
 
     Consider a zip file with this structure::
 
@@ -169,13 +230,13 @@ class Path:
 
     Path accepts the zipfile object itself or a filename
 
-    >>> root = Path(zf)
+    >>> path = Path(zf)
 
     From there, several path operations are available.
 
     Directory iteration (including the zip file itself):
 
-    >>> a, b = root.iterdir()
+    >>> a, b = path.iterdir()
     >>> a
     Path('mem/abcde.zip', 'a.txt')
     >>> b
@@ -196,7 +257,7 @@ class Path:
 
     Read text:
 
-    >>> c.read_text()
+    >>> c.read_text(encoding='utf-8')
     'content of c'
 
     existence:
@@ -213,16 +274,38 @@ class Path:
     'mem/abcde.zip/b/c.txt'
 
     At the root, ``name``, ``filename``, and ``parent``
-    resolve to the zipfile. Note these attributes are not
-    valid and will raise a ``ValueError`` if the zipfile
-    has no filename.
+    resolve to the zipfile.
 
-    >>> root.name
+    >>> str(path)
+    'mem/abcde.zip/'
+    >>> path.name
     'abcde.zip'
-    >>> str(root.filename).replace(os.sep, posixpath.sep)
-    'mem/abcde.zip'
-    >>> str(root.parent)
+    >>> path.filename == pathlib.Path('mem/abcde.zip')
+    True
+    >>> str(path.parent)
     'mem'
+
+    If the zipfile has no filename, such attributes are not
+    valid and accessing them will raise an Exception.
+
+    >>> zf.filename = None
+    >>> path.name
+    Traceback (most recent call last):
+    ...
+    TypeError: ...
+
+    >>> path.filename
+    Traceback (most recent call last):
+    ...
+    TypeError: ...
+
+    >>> path.parent
+    Traceback (most recent call last):
+    ...
+    TypeError: ...
+
+    # workaround python/cpython#106763
+    >>> pass
     """
 
     __repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})"
@@ -240,6 +323,18 @@ def __init__(self, root, at=""):
         self.root = FastLookup.make(root)
         self.at = at
 
+    def __eq__(self, other):
+        """
+        >>> Path(zipfile.ZipFile(io.BytesIO(), 'w')) == 'foo'
+        False
+        """
+        if self.__class__ is not other.__class__:
+            return NotImplemented
+        return (self.root, self.at) == (other.root, other.at)
+
+    def __hash__(self):
+        return hash((self.root, self.at))
+
     def open(self, mode='r', *args, pwd=None, **kwargs):
         """
         Open this entry as text or binary following the semantics
@@ -249,37 +344,43 @@ def open(self, mode='r', *args, pwd=None, **kwargs):
         if self.is_dir():
             raise IsADirectoryError(self)
         zip_mode = mode[0]
-        if not self.exists() and zip_mode == 'r':
+        if zip_mode == 'r' and not self.exists():
             raise FileNotFoundError(self)
         stream = self.root.open(self.at, zip_mode, pwd=pwd)
         if 'b' in mode:
             if args or kwargs:
                 raise ValueError("encoding args invalid for binary operation")
             return stream
-        return io.TextIOWrapper(stream, *args, **kwargs)
+        # Text mode:
+        encoding, args, kwargs = _extract_text_encoding(*args, **kwargs)
+        return io.TextIOWrapper(stream, encoding, *args, **kwargs)
+
+    def _base(self):
+        return pathlib.PurePosixPath(self.at) if self.at else self.filename
 
     @property
     def name(self):
-        return pathlib.Path(self.at).name or self.filename.name
+        return self._base().name
 
     @property
     def suffix(self):
-        return pathlib.Path(self.at).suffix or self.filename.suffix
+        return self._base().suffix
 
     @property
     def suffixes(self):
-        return pathlib.Path(self.at).suffixes or self.filename.suffixes
+        return self._base().suffixes
 
     @property
     def stem(self):
-        return pathlib.Path(self.at).stem or self.filename.stem
+        return self._base().stem
 
     @property
     def filename(self):
         return pathlib.Path(self.root.filename).joinpath(self.at)
 
     def read_text(self, *args, **kwargs):
-        with self.open('r', *args, **kwargs) as strm:
+        encoding, args, kwargs = _extract_text_encoding(*args, **kwargs)
+        with self.open('r', encoding, *args, **kwargs) as strm:
             return strm.read()
 
     def read_bytes(self):
@@ -307,6 +408,32 @@ def iterdir(self):
         subs = map(self._next, self.root.namelist())
         return filter(self._is_child, subs)
 
+    def match(self, path_pattern):
+        return pathlib.PurePosixPath(self.at).match(path_pattern)
+
+    def is_symlink(self):
+        """
+        Return whether this path is a symlink.
+        """
+        info = self.root.getinfo(self.at)
+        mode = info.external_attr >> 16
+        return stat.S_ISLNK(mode)
+
+    def glob(self, pattern):
+        if not pattern:
+            raise ValueError(f"Unacceptable pattern: {pattern!r}")
+
+        prefix = re.escape(self.at)
+        tr = Translator(seps='/')
+        matches = re.compile(prefix + tr.translate(pattern)).fullmatch
+        return map(self._next, filter(matches, self.root.namelist()))
+
+    def rglob(self, pattern):
+        return self.glob(f'**/{pattern}')
+
+    def relative_to(self, other, *extra):
+        return posixpath.relpath(str(self), str(other.joinpath(*extra)))
+
     def __str__(self):
         return posixpath.join(self.root.filename, self.at)
 
@@ -314,7 +441,7 @@ def __repr__(self):
         return self.__repr.format(self=self)
 
     def joinpath(self, *other):
-        next = posixpath.join(self.at, *map(_pathlib_compat, other))
+        next = posixpath.join(self.at, *other)
         return self._next(self.root.resolve_dir(next))
 
     __truediv__ = joinpath
diff --git a/setuptools/_vendor/zipp/_functools.py b/setuptools/_vendor/zipp/_functools.py
new file mode 100644
index 0000000000..7390be2187
--- /dev/null
+++ b/setuptools/_vendor/zipp/_functools.py
@@ -0,0 +1,20 @@
+import collections
+import functools
+
+
+# from jaraco.functools 4.0.2
+def save_method_args(method):
+    """
+    Wrap a method such that when it is called, the args and kwargs are
+    saved on the method.
+    """
+    args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs')  # noqa: PYI024
+
+    @functools.wraps(method)
+    def wrapper(self, /, *args, **kwargs):
+        attr_name = '_saved_' + method.__name__
+        attr = args_and_kwargs(args, kwargs)
+        setattr(self, attr_name, attr)
+        return method(self, *args, **kwargs)
+
+    return wrapper
diff --git a/pkg_resources/_vendor/importlib_resources/tests/data01/subdirectory/__init__.py b/setuptools/_vendor/zipp/compat/__init__.py
similarity index 100%
rename from pkg_resources/_vendor/importlib_resources/tests/data01/subdirectory/__init__.py
rename to setuptools/_vendor/zipp/compat/__init__.py
diff --git a/setuptools/_vendor/zipp/compat/overlay.py b/setuptools/_vendor/zipp/compat/overlay.py
new file mode 100644
index 0000000000..5a97ee7cd8
--- /dev/null
+++ b/setuptools/_vendor/zipp/compat/overlay.py
@@ -0,0 +1,37 @@
+"""
+Expose zipp.Path as .zipfile.Path.
+
+Includes everything else in ``zipfile`` to match future usage. Just
+use:
+
+>>> from zipp.compat.overlay import zipfile
+
+in place of ``import zipfile``.
+
+Relative imports are supported too.
+
+>>> from zipp.compat.overlay.zipfile import ZipInfo
+
+The ``zipfile`` object added to ``sys.modules`` needs to be
+hashable (#126).
+
+>>> _ = hash(sys.modules['zipp.compat.overlay.zipfile'])
+"""
+
+import importlib
+import sys
+import types
+
+import zipp
+
+
+class HashableNamespace(types.SimpleNamespace):
+    def __hash__(self):
+        return hash(tuple(vars(self)))
+
+
+zipfile = HashableNamespace(**vars(importlib.import_module('zipfile')))
+zipfile.Path = zipp.Path
+zipfile._path = zipp
+
+sys.modules[__name__ + '.zipfile'] = zipfile  # type: ignore[assignment]
diff --git a/setuptools/_vendor/zipp/compat/py310.py b/setuptools/_vendor/zipp/compat/py310.py
new file mode 100644
index 0000000000..e1e7ec2290
--- /dev/null
+++ b/setuptools/_vendor/zipp/compat/py310.py
@@ -0,0 +1,13 @@
+import io
+import sys
+
+
+def _text_encoding(encoding, stacklevel=2, /):  # pragma: no cover
+    return encoding
+
+
+text_encoding = (
+    io.text_encoding  # type: ignore[unused-ignore, attr-defined]
+    if sys.version_info > (3, 10)
+    else _text_encoding
+)
diff --git a/setuptools/_vendor/zipp/compat/py313.py b/setuptools/_vendor/zipp/compat/py313.py
new file mode 100644
index 0000000000..ae45869055
--- /dev/null
+++ b/setuptools/_vendor/zipp/compat/py313.py
@@ -0,0 +1,34 @@
+import functools
+import sys
+
+
+# from jaraco.functools 4.1
+def identity(x):
+    return x
+
+
+# from jaraco.functools 4.1
+def apply(transform):
+    def wrap(func):
+        return functools.wraps(func)(compose(transform, func))
+
+    return wrap
+
+
+# from jaraco.functools 4.1
+def compose(*funcs):
+    def compose_two(f1, f2):
+        return lambda *args, **kwargs: f1(f2(*args, **kwargs))
+
+    return functools.reduce(compose_two, funcs)
+
+
+def replace(pattern):
+    r"""
+    >>> replace(r'foo\z')
+    'foo\\Z'
+    """
+    return pattern[:-2] + pattern[-2:].replace(r'\z', r'\Z')
+
+
+legacy_end_marker = apply(replace) if sys.version_info < (3, 14) else identity
diff --git a/setuptools/_vendor/zipp/glob.py b/setuptools/_vendor/zipp/glob.py
new file mode 100644
index 0000000000..1b4ffb3318
--- /dev/null
+++ b/setuptools/_vendor/zipp/glob.py
@@ -0,0 +1,116 @@
+import os
+import re
+
+from .compat.py313 import legacy_end_marker
+
+_default_seps = os.sep + str(os.altsep) * bool(os.altsep)
+
+
+class Translator:
+    """
+    >>> Translator('xyz')
+    Traceback (most recent call last):
+    ...
+    AssertionError: Invalid separators
+
+    >>> Translator('')
+    Traceback (most recent call last):
+    ...
+    AssertionError: Invalid separators
+    """
+
+    seps: str
+
+    def __init__(self, seps: str = _default_seps):
+        assert seps and set(seps) <= set(_default_seps), "Invalid separators"
+        self.seps = seps
+
+    def translate(self, pattern):
+        """
+        Given a glob pattern, produce a regex that matches it.
+        """
+        return self.extend(self.match_dirs(self.translate_core(pattern)))
+
+    @legacy_end_marker
+    def extend(self, pattern):
+        r"""
+        Extend regex for pattern-wide concerns.
+
+        Apply '(?s:)' to create a non-matching group that
+        matches newlines (valid on Unix).
+
+        Append '\z' to imply fullmatch even when match is used.
+        """
+        return rf'(?s:{pattern})\z'
+
+    def match_dirs(self, pattern):
+        """
+        Ensure that zipfile.Path directory names are matched.
+
+        zipfile.Path directory names always end in a slash.
+        """
+        return rf'{pattern}[/]?'
+
+    def translate_core(self, pattern):
+        r"""
+        Given a glob pattern, produce a regex that matches it.
+
+        >>> t = Translator()
+        >>> t.translate_core('*.txt').replace('\\\\', '')
+        '[^/]*\\.txt'
+        >>> t.translate_core('a?txt')
+        'a[^/]txt'
+        >>> t.translate_core('**/*').replace('\\\\', '')
+        '.*/[^/][^/]*'
+        """
+        self.restrict_rglob(pattern)
+        return ''.join(map(self.replace, separate(self.star_not_empty(pattern))))
+
+    def replace(self, match):
+        """
+        Perform the replacements for a match from :func:`separate`.
+        """
+        return match.group('set') or (
+            re.escape(match.group(0))
+            .replace('\\*\\*', r'.*')
+            .replace('\\*', rf'[^{re.escape(self.seps)}]*')
+            .replace('\\?', r'[^/]')
+        )
+
+    def restrict_rglob(self, pattern):
+        """
+        Raise ValueError if ** appears in anything but a full path segment.
+
+        >>> Translator().translate('**foo')
+        Traceback (most recent call last):
+        ...
+        ValueError: ** must appear alone in a path segment
+        """
+        seps_pattern = rf'[{re.escape(self.seps)}]+'
+        segments = re.split(seps_pattern, pattern)
+        if any('**' in segment and segment != '**' for segment in segments):
+            raise ValueError("** must appear alone in a path segment")
+
+    def star_not_empty(self, pattern):
+        """
+        Ensure that * will not match an empty segment.
+        """
+
+        def handle_segment(match):
+            segment = match.group(0)
+            return '?*' if segment == '*' else segment
+
+        not_seps_pattern = rf'[^{re.escape(self.seps)}]+'
+        return re.sub(not_seps_pattern, handle_segment, pattern)
+
+
+def separate(pattern):
+    """
+    Separate out character sets to avoid translating their contents.
+
+    >>> [m.group(0) for m in separate('*.txt')]
+    ['*.txt']
+    >>> [m.group(0) for m in separate('a[?]txt')]
+    ['a', '[?]', 'txt']
+    """
+    return re.finditer(r'([^\[]+)|(?P[\[].*?[\]])|([\[][^\]]*$)', pattern)
diff --git a/setuptools/archive_util.py b/setuptools/archive_util.py
index 6b8460bd92..1a02010bb2 100644
--- a/setuptools/archive_util.py
+++ b/setuptools/archive_util.py
@@ -1,15 +1,16 @@
 """Utilities for extracting common archive formats"""
 
-import zipfile
-import tarfile
+import contextlib
 import os
-import shutil
 import posixpath
-import contextlib
-from distutils.errors import DistutilsError
+import shutil
+import tarfile
+import zipfile
 
 from ._path import ensure_directory
 
+from distutils.errors import DistutilsError
+
 __all__ = [
     "unpack_archive",
     "unpack_zipfile",
@@ -30,7 +31,9 @@ def default_filter(src, dst):
     return dst
 
 
-def unpack_archive(filename, extract_dir, progress_filter=default_filter, drivers=None):
+def unpack_archive(
+    filename, extract_dir, progress_filter=default_filter, drivers=None
+) -> None:
     """Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat``
 
     `progress_filter` is a function taking two arguments: a source path
@@ -59,16 +62,16 @@ def unpack_archive(filename, extract_dir, progress_filter=default_filter, driver
         else:
             return
     else:
-        raise UnrecognizedFormat("Not a recognized archive type: %s" % filename)
+        raise UnrecognizedFormat(f"Not a recognized archive type: {filename}")
 
 
-def unpack_directory(filename, extract_dir, progress_filter=default_filter):
+def unpack_directory(filename, extract_dir, progress_filter=default_filter) -> None:
     """ "Unpack" a directory, using the same interface as for archives
 
     Raises ``UnrecognizedFormat`` if `filename` is not a directory
     """
     if not os.path.isdir(filename):
-        raise UnrecognizedFormat("%s is not a directory" % filename)
+        raise UnrecognizedFormat(f"{filename} is not a directory")
 
     paths = {
         filename: ('', extract_dir),
@@ -89,7 +92,7 @@ def unpack_directory(filename, extract_dir, progress_filter=default_filter):
             shutil.copystat(f, target)
 
 
-def unpack_zipfile(filename, extract_dir, progress_filter=default_filter):
+def unpack_zipfile(filename, extract_dir, progress_filter=default_filter) -> None:
     """Unpack zip `filename` to `extract_dir`
 
     Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
@@ -98,7 +101,7 @@ def unpack_zipfile(filename, extract_dir, progress_filter=default_filter):
     """
 
     if not zipfile.is_zipfile(filename):
-        raise UnrecognizedFormat("%s is not a zip file" % (filename,))
+        raise UnrecognizedFormat(f"{filename} is not a zip file")
 
     with zipfile.ZipFile(filename) as z:
         _unpack_zipfile_obj(z, extract_dir, progress_filter)
@@ -184,7 +187,7 @@ def _iter_open_tar(tar_obj, extract_dir, progress_filter):
             yield member, final_dst
 
 
-def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
+def unpack_tarfile(filename, extract_dir, progress_filter=default_filter) -> bool:
     """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
 
     Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
@@ -195,7 +198,7 @@ def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
         tarobj = tarfile.open(filename)
     except tarfile.TarError as e:
         raise UnrecognizedFormat(
-            "%s is not a compressed or uncompressed tar file" % (filename,)
+            f"{filename} is not a compressed or uncompressed tar file"
         ) from e
 
     for member, final_dst in _iter_open_tar(
diff --git a/setuptools/build_meta.py b/setuptools/build_meta.py
index 9267cf312f..c80f53321c 100644
--- a/setuptools/build_meta.py
+++ b/setuptools/build_meta.py
@@ -2,7 +2,7 @@
 
 Previously, when a user or a command line tool (let's call it a "frontend")
 needed to make a request of setuptools to take a certain action, for
-example, generating a list of installation requirements, the frontend would
+example, generating a list of installation requirements, the frontend
 would call "setup.py egg_info" or "setup.py bdist_wheel" on the command line.
 
 PEP 517 defines a different method of interfacing with setuptools. Rather
@@ -26,26 +26,33 @@
 Again, this is not a formal definition! Just a "taste" of the module.
 """
 
+from __future__ import annotations
+
+import contextlib
 import io
 import os
 import shlex
-import sys
-import tokenize
 import shutil
-import contextlib
+import sys
 import tempfile
+import tokenize
 import warnings
+from collections.abc import Iterable, Iterator, Mapping
 from pathlib import Path
-from typing import Dict, Iterator, List, Optional, Union
+from typing import TYPE_CHECKING, NoReturn
 
 import setuptools
-import distutils
+
 from . import errors
-from ._path import same_path
+from ._path import StrPath, same_path
 from ._reqs import parse_strings
 from .warnings import SetuptoolsDeprecationWarning
+
+import distutils
 from distutils.util import strtobool
 
+if TYPE_CHECKING:
+    from typing import TypeAlias
 
 __all__ = [
     'get_requires_for_build_sdist',
@@ -60,35 +67,32 @@
     'SetupRequirementsError',
 ]
 
-SETUPTOOLS_ENABLE_FEATURES = os.getenv("SETUPTOOLS_ENABLE_FEATURES", "").lower()
-LEGACY_EDITABLE = "legacy-editable" in SETUPTOOLS_ENABLE_FEATURES.replace("_", "-")
-
 
 class SetupRequirementsError(BaseException):
-    def __init__(self, specifiers):
+    def __init__(self, specifiers) -> None:
         self.specifiers = specifiers
 
 
 class Distribution(setuptools.dist.Distribution):
-    def fetch_build_eggs(self, specifiers):
+    def fetch_build_eggs(self, specifiers) -> NoReturn:
         specifier_list = list(parse_strings(specifiers))
 
         raise SetupRequirementsError(specifier_list)
 
     @classmethod
     @contextlib.contextmanager
-    def patch(cls):
+    def patch(cls) -> Iterator[None]:
         """
         Replace
         distutils.dist.Distribution with this class
         for the duration of this context.
         """
         orig = distutils.core.Distribution
-        distutils.core.Distribution = cls
+        distutils.core.Distribution = cls  # type: ignore[misc] # monkeypatching
         try:
             yield
         finally:
-            distutils.core.Distribution = orig
+            distutils.core.Distribution = orig  # type: ignore[misc] # monkeypatching
 
 
 @contextlib.contextmanager
@@ -113,7 +117,7 @@ def _get_immediate_subdirectories(a_dir):
     ]
 
 
-def _file_with_extension(directory, extension):
+def _file_with_extension(directory: StrPath, extension: str | tuple[str, ...]):
     matching = (f for f in os.listdir(directory) if f.endswith(extension))
     try:
         (file,) = matching
@@ -121,16 +125,16 @@ def _file_with_extension(directory, extension):
         raise ValueError(
             'No distribution was found. Ensure that `setup.py` '
             'is not empty and that it calls `setup()`.'
-        )
+        ) from None
     return file
 
 
 def _open_setup_script(setup_script):
     if not os.path.exists(setup_script):
         # Supply a default setup.py
-        return io.StringIO(u"from setuptools import setup; setup()")
+        return io.StringIO("from setuptools import setup; setup()")
 
-    return getattr(tokenize, 'open', open)(setup_script)
+    return tokenize.open(setup_script)
 
 
 @contextlib.contextmanager
@@ -140,7 +144,7 @@ def suppress_known_deprecation():
         yield
 
 
-_ConfigSettings = Optional[Dict[str, Union[str, List[str], None]]]
+_ConfigSettings: TypeAlias = Mapping[str, str | list[str] | None] | None
 """
 Currently the user can run::
 
@@ -163,7 +167,7 @@ class _ConfigSettingsTranslator:
 
     # See pypa/setuptools#1928 pypa/setuptools#2491
 
-    def _get_config(self, key: str, config_settings: _ConfigSettings) -> List[str]:
+    def _get_config(self, key: str, config_settings: _ConfigSettings) -> list[str]:
         """
         Get the value of a specific key in ``config_settings`` as a list of strings.
 
@@ -185,11 +189,6 @@ def _get_config(self, key: str, config_settings: _ConfigSettings) -> List[str]:
         opts = cfg.get(key) or []
         return shlex.split(opts) if isinstance(opts, str) else opts
 
-    def _valid_global_options(self):
-        """Global options accepted by setuptools (e.g. quiet or verbose)."""
-        options = (opt[:2] for opt in setuptools.dist.Distribution.global_options)
-        return {flag for long_and_short in options for flag in long_and_short if flag}
-
     def _global_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
         """
         Let the user specify ``verbose`` or ``quiet`` + escape hatch via
@@ -220,9 +219,7 @@ def _global_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
             level = str(cfg.get("quiet") or cfg.get("--quiet") or "1")
             yield ("-v" if level.lower() in falsey else "-q")
 
-        valid = self._valid_global_options()
-        args = self._get_config("--global-option", config_settings)
-        yield from (arg for arg in args if arg.strip("-") in valid)
+        yield from self._get_config("--global-option", config_settings)
 
     def __dist_info_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
         """
@@ -284,41 +281,20 @@ def _arbitrary_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
         ['foo']
         >>> list(fn({'--build-option': 'foo bar'}))
         ['foo', 'bar']
-        >>> warnings.simplefilter('error', SetuptoolsDeprecationWarning)
-        >>> list(fn({'--global-option': 'foo'}))  # doctest: +IGNORE_EXCEPTION_DETAIL
-        Traceback (most recent call last):
-        SetuptoolsDeprecationWarning: ...arguments given via `--global-option`...
+        >>> list(fn({'--global-option': 'foo'}))
+        []
         """
-        args = self._get_config("--global-option", config_settings)
-        global_opts = self._valid_global_options()
-        bad_args = []
-
-        for arg in args:
-            if arg.strip("-") not in global_opts:
-                bad_args.append(arg)
-                yield arg
-
         yield from self._get_config("--build-option", config_settings)
 
-        if bad_args:
-            SetuptoolsDeprecationWarning.emit(
-                "Incompatible `config_settings` passed to build backend.",
-                f"""
-                The arguments {bad_args!r} were given via `--global-option`.
-                Please use `--build-option` instead,
-                `--global-option` is reserved for flags like `--verbose` or `--quiet`.
-                """,
-                due_date=(2023, 9, 26),  # Warning introduced in v64.0.1, 11/Aug/2022.
-            )
-
 
 class _BuildMetaBackend(_ConfigSettingsTranslator):
-    def _get_build_requires(self, config_settings, requirements):
+    def _get_build_requires(
+        self, config_settings: _ConfigSettings, requirements: list[str]
+    ):
         sys.argv = [
             *sys.argv[:1],
             *self._global_args(config_settings),
             "egg_info",
-            *self._arbitrary_args(config_settings),
         ]
         try:
             with Distribution.patch():
@@ -328,7 +304,7 @@ def _get_build_requires(self, config_settings, requirements):
 
         return requirements
 
-    def run_setup(self, setup_script='setup.py'):
+    def run_setup(self, setup_script: str = 'setup.py') -> None:
         # Note that we can reuse our build directory between calls
         # Correctness comes first, then optimization later
         __file__ = os.path.abspath(setup_script)
@@ -351,13 +327,19 @@ def run_setup(self, setup_script='setup.py'):
                 "setup-py-deprecated.html",
             )
 
-    def get_requires_for_build_wheel(self, config_settings=None):
-        return self._get_build_requires(config_settings, requirements=['wheel'])
+    def get_requires_for_build_wheel(
+        self, config_settings: _ConfigSettings = None
+    ) -> list[str]:
+        return self._get_build_requires(config_settings, requirements=[])
 
-    def get_requires_for_build_sdist(self, config_settings=None):
+    def get_requires_for_build_sdist(
+        self, config_settings: _ConfigSettings = None
+    ) -> list[str]:
         return self._get_build_requires(config_settings, requirements=[])
 
-    def _bubble_up_info_directory(self, metadata_directory: str, suffix: str) -> str:
+    def _bubble_up_info_directory(
+        self, metadata_directory: StrPath, suffix: str
+    ) -> str:
         """
         PEP 517 requires that the .dist-info directory be placed in the
         metadata_directory. To comply, we MUST copy the directory to the root.
@@ -370,26 +352,28 @@ def _bubble_up_info_directory(self, metadata_directory: str, suffix: str) -> str
             # PEP 517 allow other files and dirs to exist in metadata_directory
         return info_dir.name
 
-    def _find_info_directory(self, metadata_directory: str, suffix: str) -> Path:
+    def _find_info_directory(self, metadata_directory: StrPath, suffix: str) -> Path:
         for parent, dirs, _ in os.walk(metadata_directory):
             candidates = [f for f in dirs if f.endswith(suffix)]
 
             if len(candidates) != 0 or len(dirs) != 1:
-                assert len(candidates) == 1, f"Multiple {suffix} directories found"
+                assert len(candidates) == 1, (
+                    f"Exactly one {suffix} should have been produced, but found {len(candidates)}: {candidates}"
+                )
                 return Path(parent, candidates[0])
 
         msg = f"No {suffix} directory found in {metadata_directory}"
         raise errors.InternalError(msg)
 
     def prepare_metadata_for_build_wheel(
-        self, metadata_directory, config_settings=None
-    ):
+        self, metadata_directory: StrPath, config_settings: _ConfigSettings = None
+    ) -> str:
         sys.argv = [
             *sys.argv[:1],
             *self._global_args(config_settings),
             "dist_info",
             "--output-dir",
-            metadata_directory,
+            str(metadata_directory),
             "--keep-egg-info",
         ]
         with no_install_setup_requires():
@@ -399,21 +383,28 @@ def prepare_metadata_for_build_wheel(
         return self._bubble_up_info_directory(metadata_directory, ".dist-info")
 
     def _build_with_temp_dir(
-        self, setup_command, result_extension, result_directory, config_settings
+        self,
+        setup_command: Iterable[str],
+        result_extension: str | tuple[str, ...],
+        result_directory: StrPath,
+        config_settings: _ConfigSettings,
+        arbitrary_args: Iterable[str] = (),
     ):
         result_directory = os.path.abspath(result_directory)
 
         # Build in a temporary directory, then copy to the target.
         os.makedirs(result_directory, exist_ok=True)
-        temp_opts = {"prefix": ".tmp-", "dir": result_directory}
-        with tempfile.TemporaryDirectory(**temp_opts) as tmp_dist_dir:
+
+        with tempfile.TemporaryDirectory(
+            prefix=".tmp-", dir=result_directory
+        ) as tmp_dist_dir:
             sys.argv = [
                 *sys.argv[:1],
                 *self._global_args(config_settings),
                 *setup_command,
                 "--dist-dir",
                 tmp_dist_dir,
-                *self._arbitrary_args(config_settings),
+                *arbitrary_args,
             ]
             with no_install_setup_requires():
                 self.run_setup()
@@ -428,51 +419,73 @@ def _build_with_temp_dir(
         return result_basename
 
     def build_wheel(
-        self, wheel_directory, config_settings=None, metadata_directory=None
-    ):
-        with suppress_known_deprecation():
-            return self._build_with_temp_dir(
-                ['bdist_wheel'], '.whl', wheel_directory, config_settings
-            )
+        self,
+        wheel_directory: StrPath,
+        config_settings: _ConfigSettings = None,
+        metadata_directory: StrPath | None = None,
+    ) -> str:
+        def _build(cmd: list[str]):
+            with suppress_known_deprecation():
+                return self._build_with_temp_dir(
+                    cmd,
+                    '.whl',
+                    wheel_directory,
+                    config_settings,
+                    self._arbitrary_args(config_settings),
+                )
+
+        if metadata_directory is None:
+            return _build(['bdist_wheel'])
+
+        try:
+            return _build(['bdist_wheel', '--dist-info-dir', str(metadata_directory)])
+        except SystemExit as ex:  # pragma: nocover
+            # pypa/setuptools#4683
+            if "--dist-info-dir not recognized" not in str(ex):
+                raise
+            _IncompatibleBdistWheel.emit()
+            return _build(['bdist_wheel'])
 
-    def build_sdist(self, sdist_directory, config_settings=None):
+    def build_sdist(
+        self, sdist_directory: StrPath, config_settings: _ConfigSettings = None
+    ) -> str:
         return self._build_with_temp_dir(
             ['sdist', '--formats', 'gztar'], '.tar.gz', sdist_directory, config_settings
         )
 
-    def _get_dist_info_dir(self, metadata_directory: Optional[str]) -> Optional[str]:
+    def _get_dist_info_dir(self, metadata_directory: StrPath | None) -> str | None:
         if not metadata_directory:
             return None
         dist_info_candidates = list(Path(metadata_directory).glob("*.dist-info"))
         assert len(dist_info_candidates) <= 1
         return str(dist_info_candidates[0]) if dist_info_candidates else None
 
-    if not LEGACY_EDITABLE:
-        # PEP660 hooks:
-        # build_editable
-        # get_requires_for_build_editable
-        # prepare_metadata_for_build_editable
-        def build_editable(
-            self, wheel_directory, config_settings=None, metadata_directory=None
-        ):
-            # XXX can or should we hide our editable_wheel command normally?
-            info_dir = self._get_dist_info_dir(metadata_directory)
-            opts = ["--dist-info-dir", info_dir] if info_dir else []
-            cmd = ["editable_wheel", *opts, *self._editable_args(config_settings)]
-            with suppress_known_deprecation():
-                return self._build_with_temp_dir(
-                    cmd, ".whl", wheel_directory, config_settings
-                )
+    def build_editable(
+        self,
+        wheel_directory: StrPath,
+        config_settings: _ConfigSettings = None,
+        metadata_directory: StrPath | None = None,
+    ) -> str:
+        # XXX can or should we hide our editable_wheel command normally?
+        info_dir = self._get_dist_info_dir(metadata_directory)
+        opts = ["--dist-info-dir", info_dir] if info_dir else []
+        cmd = ["editable_wheel", *opts, *self._editable_args(config_settings)]
+        with suppress_known_deprecation():
+            return self._build_with_temp_dir(
+                cmd, ".whl", wheel_directory, config_settings
+            )
 
-        def get_requires_for_build_editable(self, config_settings=None):
-            return self.get_requires_for_build_wheel(config_settings)
+    def get_requires_for_build_editable(
+        self, config_settings: _ConfigSettings = None
+    ) -> list[str]:
+        return self.get_requires_for_build_wheel(config_settings)
 
-        def prepare_metadata_for_build_editable(
-            self, metadata_directory, config_settings=None
-        ):
-            return self.prepare_metadata_for_build_wheel(
-                metadata_directory, config_settings
-            )
+    def prepare_metadata_for_build_editable(
+        self, metadata_directory: StrPath, config_settings: _ConfigSettings = None
+    ) -> str:
+        return self.prepare_metadata_for_build_wheel(
+            metadata_directory, config_settings
+        )
 
 
 class _BuildMetaLegacyBackend(_BuildMetaBackend):
@@ -487,7 +500,7 @@ class _BuildMetaLegacyBackend(_BuildMetaBackend):
     and will eventually be removed.
     """
 
-    def run_setup(self, setup_script='setup.py'):
+    def run_setup(self, setup_script: str = 'setup.py') -> None:
         # In order to maintain compatibility with scripts assuming that
         # the setup.py script is in a directory on the PYTHONPATH, inject
         # '' into sys.path. (pypa/setuptools#1642)
@@ -504,7 +517,7 @@ def run_setup(self, setup_script='setup.py'):
         sys.argv[0] = setup_script
 
         try:
-            super(_BuildMetaLegacyBackend, self).run_setup(setup_script=setup_script)
+            super().run_setup(setup_script=setup_script)
         finally:
             # While PEP 517 frontends should be calling each hook in a fresh
             # subprocess according to the standard (and thus it should not be
@@ -515,6 +528,17 @@ def run_setup(self, setup_script='setup.py'):
             sys.argv[0] = sys_argv_0
 
 
+class _IncompatibleBdistWheel(SetuptoolsDeprecationWarning):
+    _SUMMARY = "wheel.bdist_wheel is deprecated, please import it from setuptools"
+    _DETAILS = """
+    Ensure that any custom bdist_wheel implementation is a subclass of
+    setuptools.command.bdist_wheel.bdist_wheel.
+    """
+    _DUE_DATE = (2025, 10, 15)
+    # Initially introduced in 2024/10/15, but maybe too disruptive to be enforced?
+    _SEE_URL = "https://github.com/pypa/wheel/pull/631"
+
+
 # The primary backend
 _BACKEND = _BuildMetaBackend()
 
@@ -523,11 +547,9 @@ def run_setup(self, setup_script='setup.py'):
 prepare_metadata_for_build_wheel = _BACKEND.prepare_metadata_for_build_wheel
 build_wheel = _BACKEND.build_wheel
 build_sdist = _BACKEND.build_sdist
-
-if not LEGACY_EDITABLE:
-    get_requires_for_build_editable = _BACKEND.get_requires_for_build_editable
-    prepare_metadata_for_build_editable = _BACKEND.prepare_metadata_for_build_editable
-    build_editable = _BACKEND.build_editable
+get_requires_for_build_editable = _BACKEND.get_requires_for_build_editable
+prepare_metadata_for_build_editable = _BACKEND.prepare_metadata_for_build_editable
+build_editable = _BACKEND.build_editable
 
 
 # The legacy backend
diff --git a/setuptools/command/__init__.py b/setuptools/command/__init__.py
index 5acd7687d6..50e6c2f54f 100644
--- a/setuptools/command/__init__.py
+++ b/setuptools/command/__init__.py
@@ -1,11 +1,20 @@
-from distutils.command.bdist import bdist
+# mypy: disable_error_code=call-overload
+# pyright: reportCallIssue=false, reportArgumentType=false
+# Can't disable on the exact line because distutils doesn't exists on Python 3.12
+# and type-checkers aren't aware of distutils_hack,
+# causing distutils.command.bdist.bdist.format_commands to be Any.
+
 import sys
 
+from distutils.command.bdist import bdist
+
 if 'egg' not in bdist.format_commands:
     try:
+        # format_commands is a dict in vendored distutils
+        # It used to be a list in older (stdlib) distutils
+        # We support both for backwards compatibility
         bdist.format_commands['egg'] = ('bdist_egg', "Python .egg file")
     except TypeError:
-        # For backward compatibility with older distutils (stdlib)
         bdist.format_command['egg'] = ('bdist_egg', "Python .egg file")
         bdist.format_commands.append('egg')
 
diff --git a/setuptools/command/_requirestxt.py b/setuptools/command/_requirestxt.py
index d223737fd4..9029b12514 100644
--- a/setuptools/command/_requirestxt.py
+++ b/setuptools/command/_requirestxt.py
@@ -6,25 +6,29 @@
 
 See https://setuptools.pypa.io/en/latest/deprecated/python_eggs.html#requires-txt
 """
+
+from __future__ import annotations
+
 import io
 from collections import defaultdict
+from collections.abc import Mapping
 from itertools import filterfalse
-from typing import Dict, List, Tuple, Mapping, TypeVar
+from typing import TypeVar
 
-from ..extern.jaraco.text import yield_lines
-from ..extern.packaging.requirements import Requirement
+from jaraco.text import yield_lines
+from packaging.requirements import Requirement
 
+from .. import _reqs
+from .._reqs import _StrOrIter
 
 # dict can work as an ordered set
 _T = TypeVar("_T")
-_Ordered = Dict[_T, None]
-_ordered = dict
+_Ordered = dict[_T, None]
 
 
 def _prepare(
-    install_requires: Dict[str, Requirement],
-    extras_require: Mapping[str, Dict[str, Requirement]],
-) -> Tuple[List[str], Dict[str, List[str]]]:
+    install_requires: _StrOrIter, extras_require: Mapping[str, _StrOrIter]
+) -> tuple[list[str], dict[str, list[str]]]:
     """Given values for ``install_requires`` and ``extras_require``
     create modified versions in a way that can be written in ``requires.txt``
     """
@@ -33,27 +37,26 @@ def _prepare(
 
 
 def _convert_extras_requirements(
-    extras_require: Dict[str, Dict[str, Requirement]],
-) -> Mapping[str, _Ordered[Requirement]]:
+    extras_require: Mapping[str, _StrOrIter],
+) -> defaultdict[str, _Ordered[Requirement]]:
     """
     Convert requirements in `extras_require` of the form
     `"extra": ["barbazquux; {marker}"]` to
     `"extra:{marker}": ["barbazquux"]`.
     """
-    output: Mapping[str, _Ordered[Requirement]] = defaultdict(dict)
+    output = defaultdict[str, _Ordered[Requirement]](dict)
     for section, v in extras_require.items():
         # Do not strip empty sections.
         output[section]
-        for r in v.values():
+        for r in _reqs.parse(v):
             output[section + _suffix_for(r)].setdefault(r)
 
     return output
 
 
 def _move_install_requirements_markers(
-    install_requires: Dict[str, Requirement],
-    extras_require: Mapping[str, _Ordered[Requirement]],
-) -> Tuple[List[str], Dict[str, List[str]]]:
+    install_requires: _StrOrIter, extras_require: Mapping[str, _Ordered[Requirement]]
+) -> tuple[list[str], dict[str, list[str]]]:
     """
     The ``requires.txt`` file has an specific format:
         - Environment markers need to be part of the section headers and
@@ -66,7 +69,7 @@ def _move_install_requirements_markers(
     # divide the install_requires into two sets, simple ones still
     # handled by install_requires and more complex ones handled by extras_require.
 
-    inst_reqs = install_requires.values()
+    inst_reqs = list(_reqs.parse(install_requires))
     simple_reqs = filter(_no_marker, inst_reqs)
     complex_reqs = filterfalse(_no_marker, inst_reqs)
     simple_install_requires = list(map(str, simple_reqs))
@@ -90,7 +93,7 @@ def _suffix_for(req):
 
 def _clean_req(req):
     """Given a Requirement, remove environment markers and return it"""
-    r = Requirement(str(req))  # create a copy before modifying.
+    r = Requirement(str(req))  # create a copy before modifying
     r.marker = None
     return r
 
@@ -111,10 +114,9 @@ def append_cr(line):
 
 def write_requirements(cmd, basename, filename):
     dist = cmd.distribution
-    meta = dist.metadata
     data = io.StringIO()
     install_requires, extras_require = _prepare(
-        meta._normalized_install_requires, meta._normalized_extras_require
+        dist.install_requires or (), dist.extras_require or {}
     )
     _write_requirements(data, install_requires)
     for extra in sorted(extras_require):
diff --git a/setuptools/command/alias.py b/setuptools/command/alias.py
index e7b4d5456a..0ffa3116d6 100644
--- a/setuptools/command/alias.py
+++ b/setuptools/command/alias.py
@@ -1,6 +1,6 @@
-from distutils.errors import DistutilsOptionError
+from setuptools.command.setopt import config_file, edit_config, option_base
 
-from setuptools.command.setopt import edit_config, option_base, config_file
+from distutils.errors import DistutilsOptionError
 
 
 def shquote(arg):
@@ -30,15 +30,14 @@ def initialize_options(self):
         self.args = None
         self.remove = None
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         option_base.finalize_options(self)
         if self.remove and len(self.args) != 1:
             raise DistutilsOptionError(
-                "Must specify exactly one argument (the alias name) when "
-                "using --remove"
+                "Must specify exactly one argument (the alias name) when using --remove"
             )
 
-    def run(self):
+    def run(self) -> None:
         aliases = self.distribution.get_option_dict('aliases')
 
         if not self.args:
@@ -56,13 +55,13 @@ def run(self):
                 print("setup.py alias", format_alias(alias, aliases))
                 return
             else:
-                print("No alias definition found for %r" % alias)
+                print(f"No alias definition found for {alias!r}")
                 return
         else:
             alias = self.args[0]
             command = ' '.join(map(shquote, self.args[1:]))
 
-        edit_config(self.filename, {'aliases': {alias: command}}, self.dry_run)
+        edit_config(self.filename, {'aliases': {alias: command}})
 
 
 def format_alias(name, aliases):
@@ -74,5 +73,5 @@ def format_alias(name, aliases):
     elif source == config_file('local'):
         source = ''
     else:
-        source = '--filename=%r' % source
+        source = f'--filename={source!r}'
     return source + name + ' ' + command
diff --git a/setuptools/command/bdist_egg.py b/setuptools/command/bdist_egg.py
index bdece56bc9..02c94faff0 100644
--- a/setuptools/command/bdist_egg.py
+++ b/setuptools/command/bdist_egg.py
@@ -2,20 +2,33 @@
 
 Build .egg distributions"""
 
-from distutils.dir_util import remove_tree, mkpath
-from distutils import log
-from types import CodeType
-import sys
+from __future__ import annotations
+
+import marshal
 import os
 import re
+import sys
 import textwrap
-import marshal
+from collections.abc import Iterator
+from sysconfig import get_path, get_platform, get_python_version
+from types import CodeType
+from typing import TYPE_CHECKING, AnyStr, Literal
 
-from setuptools.extension import Library
 from setuptools import Command
-from .._path import ensure_directory
+from setuptools.extension import Library
 
-from sysconfig import get_path, get_python_version
+from .._path import StrPath, StrPathT, ensure_directory
+
+from distutils import log
+from distutils.dir_util import mkpath, remove_tree
+
+if TYPE_CHECKING:
+    from typing import TypeAlias
+
+    from _typeshed import GenericPath
+
+# Same as zipfile._ZipFileMode from typeshed
+_ZipFileMode: TypeAlias = Literal["r", "w", "x", "a"]
 
 
 def _get_purelib():
@@ -25,12 +38,13 @@ def _get_purelib():
 def strip_module(filename):
     if '.' in filename:
         filename = os.path.splitext(filename)[0]
-    if filename.endswith('module'):
-        filename = filename[:-6]
+    filename = filename.removesuffix('module')
     return filename
 
 
-def sorted_walk(dir):
+def sorted_walk(
+    dir: GenericPath[AnyStr],
+) -> Iterator[tuple[AnyStr, list[AnyStr], list[AnyStr]]]:
     """Do os.walk in a reproducible way,
     independent of indeterministic filesystem readdir order
     """
@@ -40,26 +54,26 @@ def sorted_walk(dir):
         yield base, dirs, files
 
 
-def write_stub(resource, pyfile):
+def write_stub(resource, pyfile) -> None:
     _stub_template = textwrap.dedent(
         """
         def __bootstrap__():
             global __bootstrap__, __loader__, __file__
-            import sys, pkg_resources, importlib.util
-            __file__ = pkg_resources.resource_filename(__name__, %r)
-            __loader__ = None; del __bootstrap__, __loader__
-            spec = importlib.util.spec_from_file_location(__name__,__file__)
-            mod = importlib.util.module_from_spec(spec)
-            spec.loader.exec_module(mod)
+            import sys, importlib.resources as irs, importlib.util
+            with irs.as_file(irs.files(__name__).joinpath(%r)) as __file__:
+                __loader__ = None; del __bootstrap__, __loader__
+                spec = importlib.util.spec_from_file_location(__name__,__file__)
+                mod = importlib.util.module_from_spec(spec)
+                spec.loader.exec_module(mod)
         __bootstrap__()
         """
     ).lstrip()
-    with open(pyfile, 'w') as f:
+    with open(pyfile, 'w', encoding="utf-8") as f:
         f.write(_stub_template % resource)
 
 
 class bdist_egg(Command):
-    description = "create an \"egg\" distribution"
+    description = 'create an "egg" distribution'
 
     user_options = [
         ('bdist-dir=', 'b', "temporary directory for creating the distribution"),
@@ -67,14 +81,14 @@ class bdist_egg(Command):
             'plat-name=',
             'p',
             "platform name to embed in generated filenames "
-            "(by default uses `pkg_resources.get_build_platform()`)",
+            "(by default uses `sysconfig.get_platform()`)",
         ),
         ('exclude-source-files', None, "remove all .py files from the generated egg"),
         (
             'keep-temp',
             'k',
             "keep the pseudo-installation tree around after "
-            + "creating the distribution archive",
+            "creating the distribution archive",
         ),
         ('dist-dir=', 'd', "directory to put final built distributions in"),
         ('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
@@ -85,13 +99,13 @@ class bdist_egg(Command):
     def initialize_options(self):
         self.bdist_dir = None
         self.plat_name = None
-        self.keep_temp = 0
+        self.keep_temp = False
         self.dist_dir = None
-        self.skip_build = 0
+        self.skip_build = False
         self.egg_output = None
         self.exclude_source_files = None
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         ei_cmd = self.ei_cmd = self.get_finalized_command("egg_info")
         self.egg_info = ei_cmd.egg_info
 
@@ -100,9 +114,7 @@ def finalize_options(self):
             self.bdist_dir = os.path.join(bdist_base, 'egg')
 
         if self.plat_name is None:
-            from pkg_resources import get_build_platform
-
-            self.plat_name = get_build_platform()
+            self.plat_name = get_platform()
 
         self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
 
@@ -115,7 +127,7 @@ def finalize_options(self):
 
             self.egg_output = os.path.join(self.dist_dir, basename + '.egg')
 
-    def do_install_data(self):
+    def do_install_data(self) -> None:
         # Hack for packages that install data to install's --install-lib
         self.get_finalized_command('install').install_lib = self.bdist_dir
 
@@ -136,7 +148,7 @@ def do_install_data(self):
 
         try:
             log.info("installing package data to %s", self.bdist_dir)
-            self.call_command('install_data', force=0, root=None)
+            self.call_command('install_data', force=False, root=None)
         finally:
             self.distribution.data_files = old
 
@@ -148,12 +160,11 @@ def call_command(self, cmdname, **kw):
         for dirname in INSTALL_DIRECTORY_ATTRS:
             kw.setdefault(dirname, self.bdist_dir)
         kw.setdefault('skip_build', self.skip_build)
-        kw.setdefault('dry_run', self.dry_run)
         cmd = self.reinitialize_command(cmdname, **kw)
         self.run_command(cmdname)
         return cmd
 
-    def run(self):  # noqa: C901  # is too complex (14)  # FIXME
+    def run(self) -> None:  # noqa: C901  # is too complex (14)  # FIXME
         # Generate metadata first
         self.run_command("egg_info")
         # We run install_lib before install_data, because some data hacks
@@ -164,19 +175,18 @@ def run(self):  # noqa: C901  # is too complex (14)  # FIXME
         instcmd.root = None
         if self.distribution.has_c_libraries() and not self.skip_build:
             self.run_command('build_clib')
-        cmd = self.call_command('install_lib', warn_dir=0)
+        cmd = self.call_command('install_lib', warn_dir=False)
         instcmd.root = old_root
 
         all_outputs, ext_outputs = self.get_ext_outputs()
         self.stubs = []
         to_compile = []
         for p, ext_name in enumerate(ext_outputs):
-            filename, ext = os.path.splitext(ext_name)
+            filename, _ext = os.path.splitext(ext_name)
             pyfile = os.path.join(self.bdist_dir, strip_module(filename) + '.py')
             self.stubs.append(pyfile)
             log.info("creating stub loader for %s", ext_name)
-            if not self.dry_run:
-                write_stub(os.path.basename(ext_name), pyfile)
+            write_stub(os.path.basename(ext_name), pyfile)
             to_compile.append(pyfile)
             ext_outputs[p] = ext_name.replace(os.sep, '/')
 
@@ -192,22 +202,19 @@ def run(self):  # noqa: C901  # is too complex (14)  # FIXME
         if self.distribution.scripts:
             script_dir = os.path.join(egg_info, 'scripts')
             log.info("installing scripts to %s", script_dir)
-            self.call_command('install_scripts', install_dir=script_dir, no_ep=1)
+            self.call_command('install_scripts', install_dir=script_dir, no_ep=True)
 
         self.copy_metadata_to(egg_info)
         native_libs = os.path.join(egg_info, "native_libs.txt")
         if all_outputs:
             log.info("writing %s", native_libs)
-            if not self.dry_run:
-                ensure_directory(native_libs)
-                libs_file = open(native_libs, 'wt')
+            ensure_directory(native_libs)
+            with open(native_libs, 'wt', encoding="utf-8") as libs_file:
                 libs_file.write('\n'.join(all_outputs))
                 libs_file.write('\n')
-                libs_file.close()
         elif os.path.isfile(native_libs):
             log.info("removing %s", native_libs)
-            if not self.dry_run:
-                os.unlink(native_libs)
+            os.unlink(native_libs)
 
         write_safety_flag(os.path.join(archive_root, 'EGG-INFO'), self.zip_safe())
 
@@ -225,18 +232,19 @@ def run(self):  # noqa: C901  # is too complex (14)  # FIXME
             self.egg_output,
             archive_root,
             verbose=self.verbose,
-            dry_run=self.dry_run,
             mode=self.gen_header(),
         )
         if not self.keep_temp:
-            remove_tree(self.bdist_dir, dry_run=self.dry_run)
+            remove_tree(self.bdist_dir)
 
         # Add to 'Distribution.dist_files' so that the "upload" command works
-        getattr(self.distribution, 'dist_files', []).append(
-            ('bdist_egg', get_python_version(), self.egg_output)
-        )
+        getattr(self.distribution, 'dist_files', []).append((
+            'bdist_egg',
+            get_python_version(),
+            self.egg_output,
+        ))
 
-    def zap_pyfiles(self):
+    def zap_pyfiles(self) -> None:
         log.info("Removing .py files from temporary directory")
         for base, dirs, files in walk_egg(self.bdist_dir):
             for name in files:
@@ -251,8 +259,10 @@ def zap_pyfiles(self):
 
                     pattern = r'(?P.+)\.(?P[^.]+)\.pyc'
                     m = re.match(pattern, name)
+                    # We shouldn't find any non-pyc files in __pycache__
+                    assert m is not None
                     path_new = os.path.join(base, os.pardir, m.group('name') + '.pyc')
-                    log.info("Renaming file from [%s] to [%s]" % (path_old, path_new))
+                    log.info(f"Renaming file from [{path_old}] to [{path_new}]")
                     try:
                         os.remove(path_new)
                     except OSError:
@@ -266,10 +276,10 @@ def zip_safe(self):
         log.warn("zip_safe flag not set; analyzing archive contents...")
         return analyze_egg(self.bdist_dir, self.stubs)
 
-    def gen_header(self):
+    def gen_header(self) -> Literal["w"]:
         return 'w'
 
-    def copy_metadata_to(self, target_dir):
+    def copy_metadata_to(self, target_dir) -> None:
         "Copy metadata (egg info) to the target_dir"
         # normalize the path (so that a forward-slash in egg_info will
         # match using startswith below)
@@ -289,9 +299,11 @@ def get_ext_outputs(self):
 
         paths = {self.bdist_dir: ''}
         for base, dirs, files in sorted_walk(self.bdist_dir):
-            for filename in files:
-                if os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS:
-                    all_outputs.append(paths[base] + filename)
+            all_outputs.extend(
+                paths[base] + filename
+                for filename in files
+                if os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS
+            )
             for filename in dirs:
                 paths[os.path.join(base, filename)] = paths[base] + filename + '/'
 
@@ -309,18 +321,17 @@ def get_ext_outputs(self):
         return all_outputs, ext_outputs
 
 
-NATIVE_EXTENSIONS = dict.fromkeys('.dll .so .dylib .pyd'.split())
+NATIVE_EXTENSIONS: dict[str, None] = dict.fromkeys('.dll .so .dylib .pyd'.split())
 
 
-def walk_egg(egg_dir):
+def walk_egg(egg_dir: StrPath) -> Iterator[tuple[str, list[str], list[str]]]:
     """Walk an unpacked egg's contents, skipping the metadata directory"""
     walker = sorted_walk(egg_dir)
     base, dirs, files = next(walker)
     if 'EGG-INFO' in dirs:
         dirs.remove('EGG-INFO')
     yield base, dirs, files
-    for bdf in walker:
-        yield bdf
+    yield from walker
 
 
 def analyze_egg(egg_dir, stubs):
@@ -333,15 +344,15 @@ def analyze_egg(egg_dir, stubs):
     safe = True
     for base, dirs, files in walk_egg(egg_dir):
         for name in files:
-            if name.endswith('.py') or name.endswith('.pyw'):
+            if name.endswith(('.py', '.pyw')):
                 continue
-            elif name.endswith('.pyc') or name.endswith('.pyo'):
+            elif name.endswith(('.pyc', '.pyo')):
                 # always scan, even if we already know we're not safe
                 safe = scan_module(egg_dir, base, name, stubs) and safe
     return safe
 
 
-def write_safety_flag(egg_dir, safe):
+def write_safety_flag(egg_dir, safe) -> None:
     # Write or remove zip safety flag file(s)
     for flag, fn in safety_flags.items():
         fn = os.path.join(egg_dir, fn)
@@ -349,9 +360,8 @@ def write_safety_flag(egg_dir, safe):
             if safe is None or bool(safe) != flag:
                 os.unlink(fn)
         elif safe is not None and bool(safe) == flag:
-            f = open(fn, 'wt')
-            f.write('\n')
-            f.close()
+            with open(fn, 'wt', encoding="utf-8") as f:
+                f.write('\n')
 
 
 safety_flags = {
@@ -368,10 +378,7 @@ def scan_module(egg_dir, base, name, stubs):
         return True  # Extension module
     pkg = base[len(egg_dir) + 1 :].replace(os.sep, '.')
     module = pkg + (pkg and '.' or '') + os.path.splitext(name)[0]
-    if sys.version_info < (3, 7):
-        skip = 12  # skip magic & date & file size
-    else:
-        skip = 16  # skip magic & reserved? & date & file size
+    skip = 16  # skip magic & reserved? & date & file size
     f = open(filename, 'rb')
     f.read(skip)
     code = marshal.load(f)
@@ -386,8 +393,9 @@ def scan_module(egg_dir, base, name, stubs):
         for bad in [
             'getsource',
             'getabsfile',
+            'getfile',
             'getsourcefile',
-            'getfile' 'getsourcelines',
+            'getsourcelines',
             'findsource',
             'getcomments',
             'getframeinfo',
@@ -402,19 +410,17 @@ def scan_module(egg_dir, base, name, stubs):
     return safe
 
 
-def iter_symbols(code):
+def iter_symbols(code: CodeType) -> Iterator[str]:
     """Yield names and strings used by `code` and its nested code objects"""
-    for name in code.co_names:
-        yield name
+    yield from code.co_names
     for const in code.co_consts:
         if isinstance(const, str):
             yield const
         elif isinstance(const, CodeType):
-            for name in iter_symbols(const):
-                yield name
+            yield from iter_symbols(const)
 
 
-def can_scan():
+def can_scan() -> bool:
     if not sys.platform.startswith('java') and sys.platform != 'cli':
         # CPython, PyPy, etc.
         return True
@@ -423,6 +429,7 @@ def can_scan():
         "Please ask the author to include a 'zip_safe'"
         " setting (either True or False) in the package's setup.py"
     )
+    return False
 
 
 # Attribute names of options for commands that might need to be convinced to
@@ -431,7 +438,13 @@ def can_scan():
 INSTALL_DIRECTORY_ATTRS = ['install_lib', 'install_dir', 'install_data', 'install_base']
 
 
-def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=True, mode='w'):
+def make_zipfile(
+    zip_filename: StrPathT,
+    base_dir,
+    verbose: bool = False,
+    compress=True,
+    mode: _ZipFileMode = 'w',
+) -> StrPathT:
     """Create a zip file from all the files under 'base_dir'.  The output
     zip file will be named 'base_dir' + ".zip".  Uses either the "zipfile"
     Python module (if available) or the InfoZIP "zip" utility (if installed
@@ -440,7 +453,7 @@ def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=True, mo
     """
     import zipfile
 
-    mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
+    mkpath(os.path.dirname(zip_filename))  # type: ignore[arg-type] # python/mypy#18075
     log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
 
     def visit(z, dirname, names):
@@ -448,17 +461,12 @@ def visit(z, dirname, names):
             path = os.path.normpath(os.path.join(dirname, name))
             if os.path.isfile(path):
                 p = path[len(base_dir) + 1 :]
-                if not dry_run:
-                    z.write(path, p)
+                z.write(path, p)
                 log.debug("adding '%s'", p)
 
     compression = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED
-    if not dry_run:
-        z = zipfile.ZipFile(zip_filename, mode, compression=compression)
-        for dirname, dirs, files in sorted_walk(base_dir):
-            visit(z, dirname, files)
-        z.close()
-    else:
-        for dirname, dirs, files in sorted_walk(base_dir):
-            visit(None, dirname, files)
+    z = zipfile.ZipFile(zip_filename, mode, compression=compression)
+    for dirname, dirs, files in sorted_walk(base_dir):
+        visit(z, dirname, files)
+    z.close()
     return zip_filename
diff --git a/setuptools/command/bdist_rpm.py b/setuptools/command/bdist_rpm.py
index 30b7c23385..6dbb27002a 100644
--- a/setuptools/command/bdist_rpm.py
+++ b/setuptools/command/bdist_rpm.py
@@ -1,7 +1,8 @@
-import distutils.command.bdist_rpm as orig
-
+from ..dist import Distribution
 from ..warnings import SetuptoolsDeprecationWarning
 
+import distutils.command.bdist_rpm as orig
+
 
 class bdist_rpm(orig.bdist_rpm):
     """
@@ -12,7 +13,9 @@ class bdist_rpm(orig.bdist_rpm):
        disable eggs in RPM distributions.
     """
 
-    def run(self):
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+
+    def run(self) -> None:
         SetuptoolsDeprecationWarning.emit(
             "Deprecated command",
             """
@@ -30,11 +33,10 @@ def run(self):
 
     def _make_spec_file(self):
         spec = orig.bdist_rpm._make_spec_file(self)
-        spec = [
+        return [
             line.replace(
                 "setup.py install ",
                 "setup.py install --single-version-externally-managed ",
             ).replace("%setup", "%setup -n %{name}-%{unmangled_version}")
             for line in spec
         ]
-        return spec
diff --git a/setuptools/command/bdist_wheel.py b/setuptools/command/bdist_wheel.py
new file mode 100644
index 0000000000..3bdfa0b35a
--- /dev/null
+++ b/setuptools/command/bdist_wheel.py
@@ -0,0 +1,603 @@
+"""
+Create a wheel (.whl) distribution.
+
+A wheel is a built archive format.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import shutil
+import struct
+import sys
+import sysconfig
+import warnings
+from collections.abc import Iterable, Sequence
+from email.generator import BytesGenerator
+from glob import iglob
+from typing import Literal, cast
+from zipfile import ZIP_DEFLATED, ZIP_STORED
+
+from packaging import tags, version as _packaging_version
+from wheel.wheelfile import WheelFile
+
+from .. import Command, __version__, _shutil
+from .._core_metadata import _safe_license_file
+from .._normalization import safer_name
+from ..warnings import SetuptoolsDeprecationWarning
+from .egg_info import egg_info as egg_info_cls
+
+from distutils import log
+
+
+def safe_version(version: str) -> str:
+    """
+    Convert an arbitrary string to a standard version string
+    """
+    try:
+        # normalize the version
+        return str(_packaging_version.Version(version))
+    except _packaging_version.InvalidVersion:
+        version = version.replace(" ", ".")
+        return re.sub("[^A-Za-z0-9.]+", "-", version)
+
+
+setuptools_major_version = int(__version__.split(".")[0])
+
+PY_LIMITED_API_PATTERN = r"cp3\d"
+
+
+def _is_32bit_interpreter() -> bool:
+    return struct.calcsize("P") == 4
+
+
+def python_tag() -> str:
+    return f"py{sys.version_info.major}"
+
+
+def get_platform(archive_root: str | None) -> str:
+    """Return our platform name 'win32', 'linux_x86_64'"""
+    result = sysconfig.get_platform()
+    if result.startswith("macosx") and archive_root is not None:  # pragma: no cover
+        from wheel.macosx_libfile import calculate_macosx_platform_tag
+
+        result = calculate_macosx_platform_tag(archive_root, result)
+    elif _is_32bit_interpreter():
+        if result == "linux-x86_64":
+            # pip pull request #3497
+            result = "linux-i686"
+        elif result == "linux-aarch64":
+            # packaging pull request #234
+            # TODO armv8l, packaging pull request #690 => this did not land
+            # in pip/packaging yet
+            result = "linux-armv7l"
+
+    return result.replace("-", "_")
+
+
+def get_flag(
+    var: str, fallback: bool, expected: bool = True, warn: bool = True
+) -> bool:
+    """Use a fallback value for determining SOABI flags if the needed config
+    var is unset or unavailable."""
+    val = sysconfig.get_config_var(var)
+    if val is None:
+        if warn:
+            warnings.warn(
+                f"Config variable '{var}' is unset, Python ABI tag may be incorrect",
+                RuntimeWarning,
+                stacklevel=2,
+            )
+        return fallback
+    return val == expected
+
+
+def get_abi_tag() -> str | None:
+    """Return the ABI tag based on SOABI (if available) or emulate SOABI (PyPy2)."""
+    soabi: str = sysconfig.get_config_var("SOABI")
+    impl = tags.interpreter_name()
+    if not soabi and impl in ("cp", "pp") and hasattr(sys, "maxunicode"):
+        d = ""
+        u = ""
+        if get_flag("Py_DEBUG", hasattr(sys, "gettotalrefcount"), warn=(impl == "cp")):
+            d = "d"
+
+        abi = f"{impl}{tags.interpreter_version()}{d}{u}"
+    elif soabi and impl == "cp" and soabi.startswith("cpython"):
+        # non-Windows
+        abi = "cp" + soabi.split("-")[1]
+    elif soabi and impl == "cp" and soabi.startswith("cp"):
+        # Windows
+        abi = soabi.split("-")[0]
+        if hasattr(sys, "gettotalrefcount"):
+            # using debug build; append "d" flag
+            abi += "d"
+    elif soabi and impl == "pp":
+        # we want something like pypy36-pp73
+        abi = "-".join(soabi.split("-")[:2])
+        abi = abi.replace(".", "_").replace("-", "_")
+    elif soabi and impl == "graalpy":
+        abi = "-".join(soabi.split("-")[:3])
+        abi = abi.replace(".", "_").replace("-", "_")
+    elif soabi:
+        abi = soabi.replace(".", "_").replace("-", "_")
+    else:
+        abi = None
+
+    return abi
+
+
+def safer_version(version: str) -> str:
+    return safe_version(version).replace("-", "_")
+
+
+class bdist_wheel(Command):
+    description = "create a wheel distribution"
+
+    supported_compressions = {
+        "stored": ZIP_STORED,
+        "deflated": ZIP_DEFLATED,
+    }
+
+    user_options = [
+        ("bdist-dir=", "b", "temporary directory for creating the distribution"),
+        (
+            "plat-name=",
+            "p",
+            "platform name to embed in generated filenames "
+            f"[default: {get_platform(None)}]",
+        ),
+        (
+            "keep-temp",
+            "k",
+            "keep the pseudo-installation tree around after "
+            "creating the distribution archive",
+        ),
+        ("dist-dir=", "d", "directory to put final built distributions in"),
+        ("skip-build", None, "skip rebuilding everything (for testing/debugging)"),
+        (
+            "relative",
+            None,
+            "build the archive using relative paths [default: false]",
+        ),
+        (
+            "owner=",
+            "u",
+            "Owner name used when creating a tar file [default: current user]",
+        ),
+        (
+            "group=",
+            "g",
+            "Group name used when creating a tar file [default: current group]",
+        ),
+        ("universal", None, "*DEPRECATED* make a universal wheel [default: false]"),
+        (
+            "compression=",
+            None,
+            f"zipfile compression (one of: {', '.join(supported_compressions)}) [default: 'deflated']",
+        ),
+        (
+            "python-tag=",
+            None,
+            f"Python implementation compatibility tag [default: '{python_tag()}']",
+        ),
+        (
+            "build-number=",
+            None,
+            "Build number for this particular version. "
+            "As specified in PEP-0427, this must start with a digit. "
+            "[default: None]",
+        ),
+        (
+            "py-limited-api=",
+            None,
+            "Python tag (cp32|cp33|cpNN) for abi3 wheel tag [default: false]",
+        ),
+        (
+            "dist-info-dir=",
+            None,
+            "directory where a pre-generated dist-info can be found (e.g. as a "
+            "result of calling the PEP517 'prepare_metadata_for_build_wheel' "
+            "method)",
+        ),
+    ]
+
+    boolean_options = ["keep-temp", "skip-build", "relative", "universal"]
+
+    def initialize_options(self) -> None:
+        self.bdist_dir: str | None = None
+        self.data_dir = ""
+        self.plat_name: str | None = None
+        self.plat_tag: str | None = None
+        self.format = "zip"
+        self.keep_temp = False
+        self.dist_dir: str | None = None
+        self.dist_info_dir = None
+        self.egginfo_dir: str | None = None
+        self.root_is_pure: bool | None = None
+        self.skip_build = False
+        self.relative = False
+        self.owner = None
+        self.group = None
+        self.universal = False
+        self.compression: str | int = "deflated"
+        self.python_tag = python_tag()
+        self.build_number: str | None = None
+        self.py_limited_api: str | Literal[False] = False
+        self.plat_name_supplied = False
+
+    def finalize_options(self) -> None:
+        if not self.bdist_dir:
+            bdist_base = self.get_finalized_command("bdist").bdist_base
+            self.bdist_dir = os.path.join(bdist_base, "wheel")
+
+        if self.dist_info_dir is None:
+            egg_info = cast(egg_info_cls, self.distribution.get_command_obj("egg_info"))
+            egg_info.ensure_finalized()  # needed for correct `wheel_dist_name`
+
+        self.data_dir = self.wheel_dist_name + ".data"
+        self.plat_name_supplied = bool(self.plat_name)
+
+        need_options = ("dist_dir", "plat_name", "skip_build")
+
+        self.set_undefined_options("bdist", *zip(need_options, need_options))
+
+        self.root_is_pure = not (
+            self.distribution.has_ext_modules() or self.distribution.has_c_libraries()
+        )
+
+        self._validate_py_limited_api()
+
+        # Support legacy [wheel] section for setting universal
+        wheel = self.distribution.get_option_dict("wheel")
+        if "universal" in wheel:  # pragma: no cover
+            # please don't define this in your global configs
+            log.warn("The [wheel] section is deprecated. Use [bdist_wheel] instead.")
+            val = wheel["universal"][1].strip()
+            if val.lower() in ("1", "true", "yes"):
+                self.universal = True
+
+        if self.universal:
+            SetuptoolsDeprecationWarning.emit(
+                "bdist_wheel.universal is deprecated",
+                """
+                With Python 2.7 end-of-life, support for building universal wheels
+                (i.e., wheels that support both Python 2 and Python 3)
+                is being obviated.
+                Please discontinue using this option, or if you still need it,
+                file an issue with pypa/setuptools describing your use case.
+                """,
+                due_date=(2025, 8, 30),  # Introduced in 2024-08-30
+            )
+
+        if self.build_number is not None and not self.build_number[:1].isdigit():
+            raise ValueError("Build tag (build-number) must start with a digit.")
+
+    def _validate_py_limited_api(self) -> None:
+        if not self.py_limited_api:
+            return
+
+        if not re.match(PY_LIMITED_API_PATTERN, self.py_limited_api):
+            raise ValueError(f"py-limited-api must match '{PY_LIMITED_API_PATTERN}'")
+
+        if sysconfig.get_config_var("Py_GIL_DISABLED"):
+            raise ValueError(
+                f"`py_limited_api={self.py_limited_api!r}` not supported. "
+                "`Py_LIMITED_API` is currently incompatible with "
+                "`Py_GIL_DISABLED`. "
+                "See https://github.com/python/cpython/issues/111506."
+            )
+
+    @property
+    def wheel_dist_name(self) -> str:
+        """Return distribution full name with - replaced with _"""
+        components = [
+            safer_name(self.distribution.get_name()),
+            safer_version(self.distribution.get_version()),
+        ]
+        if self.build_number:
+            components.append(self.build_number)
+        return "-".join(components)
+
+    def get_tag(self) -> tuple[str, str, str]:
+        # bdist sets self.plat_name if unset, we should only use it for purepy
+        # wheels if the user supplied it.
+        if self.plat_name_supplied and self.plat_name:
+            plat_name = self.plat_name
+        elif self.root_is_pure:
+            plat_name = "any"
+        else:
+            # macosx contains system version in platform name so need special handle
+            if self.plat_name and not self.plat_name.startswith("macosx"):
+                plat_name = self.plat_name
+            else:
+                # on macosx always limit the platform name to comply with any
+                # c-extension modules in bdist_dir, since the user can specify
+                # a higher MACOSX_DEPLOYMENT_TARGET via tools like CMake
+
+                # on other platforms, and on macosx if there are no c-extension
+                # modules, use the default platform name.
+                plat_name = get_platform(self.bdist_dir)
+
+            if _is_32bit_interpreter():
+                if plat_name in ("linux-x86_64", "linux_x86_64"):
+                    plat_name = "linux_i686"
+                if plat_name in ("linux-aarch64", "linux_aarch64"):
+                    # TODO armv8l, packaging pull request #690 => this did not land
+                    # in pip/packaging yet
+                    plat_name = "linux_armv7l"
+
+        plat_name = (
+            plat_name.lower().replace("-", "_").replace(".", "_").replace(" ", "_")
+        )
+
+        if self.root_is_pure:
+            if self.universal:
+                impl = "py2.py3"
+            else:
+                impl = self.python_tag
+            tag = (impl, "none", plat_name)
+        else:
+            impl_name = tags.interpreter_name()
+            impl_ver = tags.interpreter_version()
+            impl = impl_name + impl_ver
+            # We don't work on CPython 3.1, 3.0.
+            if self.py_limited_api and (impl_name + impl_ver).startswith("cp3"):
+                impl = self.py_limited_api
+                abi_tag = "abi3"
+            else:
+                abi_tag = str(get_abi_tag()).lower()
+            tag = (impl, abi_tag, plat_name)
+            # issue gh-374: allow overriding plat_name
+            supported_tags = [
+                (t.interpreter, t.abi, plat_name) for t in tags.sys_tags()
+            ]
+            assert tag in supported_tags, (
+                f"would build wheel with unsupported tag {tag}"
+            )
+        return tag
+
+    def run(self):
+        build_scripts = self.reinitialize_command("build_scripts")
+        build_scripts.executable = "python"
+        build_scripts.force = True
+
+        build_ext = self.reinitialize_command("build_ext")
+        build_ext.inplace = False
+
+        if not self.skip_build:
+            self.run_command("build")
+
+        install = self.reinitialize_command("install", reinit_subcommands=True)
+        install.root = self.bdist_dir
+        install.compile = False
+        install.skip_build = self.skip_build
+        install.warn_dir = False
+
+        # A wheel without setuptools scripts is more cross-platform.
+        # Use the (undocumented) `no_ep` option to setuptools'
+        # install_scripts command to avoid creating entry point scripts.
+        install_scripts = self.reinitialize_command("install_scripts")
+        install_scripts.no_ep = True
+
+        # Use a custom scheme for the archive, because we have to decide
+        # at installation time which scheme to use.
+        for key in ("headers", "scripts", "data", "purelib", "platlib"):
+            setattr(install, "install_" + key, os.path.join(self.data_dir, key))
+
+        basedir_observed = ""
+
+        if os.name == "nt":
+            # win32 barfs if any of these are ''; could be '.'?
+            # (distutils.command.install:change_roots bug)
+            basedir_observed = os.path.normpath(os.path.join(self.data_dir, ".."))
+            self.install_libbase = self.install_lib = basedir_observed
+
+        setattr(
+            install,
+            "install_purelib" if self.root_is_pure else "install_platlib",
+            basedir_observed,
+        )
+
+        log.info(f"installing to {self.bdist_dir}")
+
+        self.run_command("install")
+
+        impl_tag, abi_tag, plat_tag = self.get_tag()
+        archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}"
+        if not self.relative:
+            archive_root = self.bdist_dir
+        else:
+            archive_root = os.path.join(
+                self.bdist_dir, self._ensure_relative(install.install_base)
+            )
+
+        self.set_undefined_options("install_egg_info", ("target", "egginfo_dir"))
+        distinfo_dirname = (
+            f"{safer_name(self.distribution.get_name())}-"
+            f"{safer_version(self.distribution.get_version())}.dist-info"
+        )
+        distinfo_dir = os.path.join(self.bdist_dir, distinfo_dirname)
+        if self.dist_info_dir:
+            # Use the given dist-info directly.
+            log.debug(f"reusing {self.dist_info_dir}")
+            shutil.copytree(self.dist_info_dir, distinfo_dir)
+            # Egg info is still generated, so remove it now to avoid it getting
+            # copied into the wheel.
+            _shutil.rmtree(self.egginfo_dir)
+        else:
+            # Convert the generated egg-info into dist-info.
+            self.egg2dist(self.egginfo_dir, distinfo_dir)
+
+        self.write_wheelfile(distinfo_dir)
+
+        # Make the archive
+        if not os.path.exists(self.dist_dir):
+            os.makedirs(self.dist_dir)
+
+        wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl")
+        with WheelFile(wheel_path, "w", self._zip_compression()) as wf:
+            wf.write_files(archive_root)
+
+        # Add to 'Distribution.dist_files' so that the "upload" command works
+        getattr(self.distribution, "dist_files", []).append((
+            "bdist_wheel",
+            f"{sys.version_info.major}.{sys.version_info.minor}",
+            wheel_path,
+        ))
+
+        if not self.keep_temp:
+            log.info(f"removing {self.bdist_dir}")
+            _shutil.rmtree(self.bdist_dir)
+
+    def write_wheelfile(
+        self, wheelfile_base: str, generator: str = f"setuptools ({__version__})"
+    ) -> None:
+        from email.message import Message
+
+        msg = Message()
+        msg["Wheel-Version"] = "1.0"  # of the spec
+        msg["Generator"] = generator
+        msg["Root-Is-Purelib"] = str(self.root_is_pure).lower()
+        if self.build_number is not None:
+            msg["Build"] = self.build_number
+
+        # Doesn't work for bdist_wininst
+        impl_tag, abi_tag, plat_tag = self.get_tag()
+        for impl in impl_tag.split("."):
+            for abi in abi_tag.split("."):
+                for plat in plat_tag.split("."):
+                    msg["Tag"] = "-".join((impl, abi, plat))
+
+        wheelfile_path = os.path.join(wheelfile_base, "WHEEL")
+        log.info(f"creating {wheelfile_path}")
+        with open(wheelfile_path, "wb") as f:
+            BytesGenerator(f, maxheaderlen=0).flatten(msg)
+
+    def _ensure_relative(self, path: str) -> str:
+        # copied from dir_util, deleted
+        drive, path = os.path.splitdrive(path)
+        if path[0:1] == os.sep:
+            path = drive + path[1:]
+        return path
+
+    @property
+    def license_paths(self) -> Iterable[str]:
+        if setuptools_major_version >= 57:
+            # Setuptools has resolved any patterns to actual file names
+            return self.distribution.metadata.license_files or ()
+
+        files = set[str]()
+        metadata = self.distribution.get_option_dict("metadata")
+        if setuptools_major_version >= 42:
+            # Setuptools recognizes the license_files option but does not do globbing
+            patterns = cast(Sequence[str], self.distribution.metadata.license_files)
+        else:
+            # Prior to those, wheel is entirely responsible for handling license files
+            if "license_files" in metadata:
+                patterns = metadata["license_files"][1].split()
+            else:
+                patterns = ()
+
+        if "license_file" in metadata:
+            warnings.warn(
+                'The "license_file" option is deprecated. Use "license_files" instead.',
+                DeprecationWarning,
+                stacklevel=2,
+            )
+            files.add(metadata["license_file"][1])
+
+        if not files and not patterns and not isinstance(patterns, list):
+            patterns = ("LICEN[CS]E*", "COPYING*", "NOTICE*", "AUTHORS*")
+
+        for pattern in patterns:
+            for path in iglob(pattern):
+                if path.endswith("~"):
+                    log.debug(
+                        f'ignoring license file "{path}" as it looks like a backup'
+                    )
+                    continue
+
+                if path not in files and os.path.isfile(path):
+                    log.info(
+                        f'adding license file "{path}" (matched pattern "{pattern}")'
+                    )
+                    files.add(path)
+
+        return files
+
+    def egg2dist(self, egginfo_path: str, distinfo_path: str) -> None:
+        """Convert an .egg-info directory into a .dist-info directory"""
+
+        def adios(p: str) -> None:
+            """Appropriately delete directory, file or link."""
+            if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):
+                _shutil.rmtree(p)
+            elif os.path.exists(p):
+                os.unlink(p)
+
+        adios(distinfo_path)
+
+        if not os.path.exists(egginfo_path):
+            # There is no egg-info. This is probably because the egg-info
+            # file/directory is not named matching the distribution name used
+            # to name the archive file. Check for this case and report
+            # accordingly.
+            import glob
+
+            pat = os.path.join(os.path.dirname(egginfo_path), "*.egg-info")
+            possible = glob.glob(pat)
+            err = f"Egg metadata expected at {egginfo_path} but not found"
+            if possible:
+                alt = os.path.basename(possible[0])
+                err += f" ({alt} found - possible misnamed archive file?)"
+
+            raise ValueError(err)
+
+        # .egg-info is a directory
+        pkginfo_path = os.path.join(egginfo_path, "PKG-INFO")
+
+        # ignore common egg metadata that is useless to wheel
+        shutil.copytree(
+            egginfo_path,
+            distinfo_path,
+            ignore=lambda x, y: {
+                "PKG-INFO",
+                "requires.txt",
+                "SOURCES.txt",
+                "not-zip-safe",
+            },
+        )
+
+        # delete dependency_links if it is only whitespace
+        dependency_links_path = os.path.join(distinfo_path, "dependency_links.txt")
+        with open(dependency_links_path, encoding="utf-8") as dependency_links_file:
+            dependency_links = dependency_links_file.read().strip()
+        if not dependency_links:
+            adios(dependency_links_path)
+
+        metadata_path = os.path.join(distinfo_path, "METADATA")
+        shutil.copy(pkginfo_path, metadata_path)
+
+        licenses_folder_path = os.path.join(distinfo_path, "licenses")
+        for license_path in self.license_paths:
+            safe_path = _safe_license_file(license_path)
+            dist_info_license_path = os.path.join(licenses_folder_path, safe_path)
+            os.makedirs(os.path.dirname(dist_info_license_path), exist_ok=True)
+            shutil.copy(license_path, dist_info_license_path)
+
+        adios(egginfo_path)
+
+    def _zip_compression(self) -> int:
+        if (
+            isinstance(self.compression, int)
+            and self.compression in self.supported_compressions.values()
+        ):
+            return self.compression
+
+        compression = self.supported_compressions.get(str(self.compression))
+        if compression is not None:
+            return compression
+
+        raise ValueError(f"Unsupported compression: {self.compression!r}")
diff --git a/setuptools/command/build.py b/setuptools/command/build.py
index 0f1d688e17..54cbb8d2e7 100644
--- a/setuptools/command/build.py
+++ b/setuptools/command/build.py
@@ -1,40 +1,20 @@
-import sys
-from typing import TYPE_CHECKING, List, Dict
-from distutils.command.build import build as _build
+from __future__ import annotations
 
-from ..warnings import SetuptoolsDeprecationWarning
+from typing import Protocol
 
-if sys.version_info >= (3, 8):
-    from typing import Protocol
-elif TYPE_CHECKING:
-    from typing_extensions import Protocol
-else:
-    from abc import ABC as Protocol
+from ..dist import Distribution
 
+from distutils.command.build import build as _build
 
 _ORIGINAL_SUBCOMMANDS = {"build_py", "build_clib", "build_ext", "build_scripts"}
 
 
 class build(_build):
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+
     # copy to avoid sharing the object with parent class
     sub_commands = _build.sub_commands[:]
 
-    def get_sub_commands(self):
-        subcommands = {cmd[0] for cmd in _build.sub_commands}
-        if subcommands - _ORIGINAL_SUBCOMMANDS:
-            SetuptoolsDeprecationWarning.emit(
-                "Direct usage of `distutils` commands",
-                """
-                It seems that you are using `distutils.command.build` to add
-                new subcommands. Using `distutils` directly is considered deprecated,
-                please use `setuptools.command.build`.
-                """,
-                due_date=(2023, 12, 13),  # Warning introduced in 13 Jun 2022.
-                see_url="https://peps.python.org/pep-0632/",
-            )
-            self.sub_commands = _build.sub_commands
-        return super().get_sub_commands()
-
 
 class SubCommand(Protocol):
     """In order to support editable installations (see :pep:`660`) all
@@ -105,16 +85,19 @@ def finalize_options(self):
             ...
     """
 
-    def initialize_options(self):
+    def initialize_options(self) -> None:
         """(Required by the original :class:`setuptools.Command` interface)"""
+        ...
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         """(Required by the original :class:`setuptools.Command` interface)"""
+        ...
 
-    def run(self):
+    def run(self) -> None:
         """(Required by the original :class:`setuptools.Command` interface)"""
+        ...
 
-    def get_source_files(self) -> List[str]:
+    def get_source_files(self) -> list[str]:
         """
         Return a list of all files that are used by the command to create the expected
         outputs.
@@ -124,8 +107,9 @@ def get_source_files(self) -> List[str]:
         with all the files necessary to build the distribution.
         All files should be strings relative to the project root directory.
         """
+        ...
 
-    def get_outputs(self) -> List[str]:
+    def get_outputs(self) -> list[str]:
         """
         Return a list of files intended for distribution as they would have been
         produced by the build.
@@ -137,8 +121,9 @@ def get_outputs(self) -> List[str]:
            in ``get_output_mapping()`` plus files that are generated during the build
            and don't correspond to any source file already present in the project.
         """
+        ...
 
-    def get_output_mapping(self) -> Dict[str, str]:
+    def get_output_mapping(self) -> dict[str, str]:
         """
         Return a mapping between destination files as they would be produced by the
         build (dict keys) into the respective existing (source) files (dict values).
@@ -147,3 +132,4 @@ def get_output_mapping(self) -> Dict[str, str]:
         Destination files should be strings in the form of
         ``"{build_lib}/destination/file/path"``.
         """
+        ...
diff --git a/setuptools/command/build_clib.py b/setuptools/command/build_clib.py
index 5f4229b276..f376f4ce4d 100644
--- a/setuptools/command/build_clib.py
+++ b/setuptools/command/build_clib.py
@@ -1,7 +1,9 @@
+from ..dist import Distribution
+from ..modified import newer_pairwise_group
+
 import distutils.command.build_clib as orig
-from distutils.errors import DistutilsSetupError
 from distutils import log
-from setuptools.dep_util import newer_pairwise_group
+from distutils.errors import DistutilsSetupError
 
 
 class build_clib(orig.build_clib):
@@ -20,14 +22,16 @@ class build_clib(orig.build_clib):
                      the compiler.
     """
 
-    def build_libraries(self, libraries):
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+
+    def build_libraries(self, libraries) -> None:
         for lib_name, build_info in libraries:
             sources = build_info.get('sources')
             if sources is None or not isinstance(sources, (list, tuple)):
                 raise DistutilsSetupError(
-                    "in 'libraries' option (library '%s'), "
+                    f"in 'libraries' option (library '{lib_name}'), "
                     "'sources' must be present and must be "
-                    "a list of source filenames" % lib_name
+                    "a list of source filenames"
                 )
             sources = sorted(list(sources))
 
@@ -39,9 +43,9 @@ def build_libraries(self, libraries):
             obj_deps = build_info.get('obj_deps', dict())
             if not isinstance(obj_deps, dict):
                 raise DistutilsSetupError(
-                    "in 'libraries' option (library '%s'), "
+                    f"in 'libraries' option (library '{lib_name}'), "
                     "'obj_deps' must be a dictionary of "
-                    "type 'source: list'" % lib_name
+                    "type 'source: list'"
                 )
             dependencies = []
 
@@ -50,9 +54,9 @@ def build_libraries(self, libraries):
             global_deps = obj_deps.get('', list())
             if not isinstance(global_deps, (list, tuple)):
                 raise DistutilsSetupError(
-                    "in 'libraries' option (library '%s'), "
+                    f"in 'libraries' option (library '{lib_name}'), "
                     "'obj_deps' must be a dictionary of "
-                    "type 'source: list'" % lib_name
+                    "type 'source: list'"
                 )
 
             # Build the list to be used by newer_pairwise_group
@@ -63,9 +67,9 @@ def build_libraries(self, libraries):
                 extra_deps = obj_deps.get(source, list())
                 if not isinstance(extra_deps, (list, tuple)):
                     raise DistutilsSetupError(
-                        "in 'libraries' option (library '%s'), "
+                        f"in 'libraries' option (library '{lib_name}'), "
                         "'obj_deps' must be a dictionary of "
-                        "type 'source: list'" % lib_name
+                        "type 'source: list'"
                     )
                 src_deps.extend(extra_deps)
                 dependencies.append(src_deps)
diff --git a/setuptools/command/build_ext.py b/setuptools/command/build_ext.py
index 9a80781cf4..dbb956db8d 100644
--- a/setuptools/command/build_ext.py
+++ b/setuptools/command/build_ext.py
@@ -1,32 +1,43 @@
+from __future__ import annotations
+
+import itertools
+import operator
 import os
 import sys
-import itertools
+import textwrap
+from collections.abc import Iterator
 from importlib.machinery import EXTENSION_SUFFIXES
 from importlib.util import cache_from_source as _compiled_file_name
-from typing import Dict, Iterator, List, Tuple
 from pathlib import Path
+from typing import TYPE_CHECKING
 
-from distutils.command.build_ext import build_ext as _du_build_ext
-from distutils.ccompiler import new_compiler
-from distutils.sysconfig import customize_compiler, get_config_var
-from distutils import log
-
+from setuptools.dist import Distribution
 from setuptools.errors import BaseError
 from setuptools.extension import Extension, Library
 
-try:
-    # Attempt to use Cython for building extensions, if available
-    from Cython.Distutils.build_ext import build_ext as _build_ext
+from distutils import log
+from distutils.ccompiler import new_compiler
+from distutils.sysconfig import customize_compiler, get_config_var
 
-    # Additionally, assert that the compiler module will load
-    # also. Ref #1229.
-    __import__('Cython.Compiler.Main')
-except ImportError:
-    _build_ext = _du_build_ext
+if TYPE_CHECKING:
+    # Cython not installed on CI tests, causing _build_ext to be `Any`
+    from distutils.command.build_ext import build_ext as _build_ext
+else:
+    try:
+        # Attempt to use Cython for building extensions, if available
+        from Cython.Distutils.build_ext import build_ext as _build_ext
+
+        # Additionally, assert that the compiler module will load
+        # also. Ref #1229.
+        __import__('Cython.Compiler.Main')
+    except ImportError:
+        from distutils.command.build_ext import build_ext as _build_ext
 
 # make sure _config_vars is initialized
 get_config_var("LDSHARED")
-from distutils.sysconfig import _config_vars as _CONFIG_VARS  # noqa
+# Not publicly exposed in typeshed distutils stubs, but this is done on purpose
+# See https://github.com/pypa/setuptools/pull/4228#issuecomment-1959856400
+from distutils.sysconfig import _config_vars as _CONFIG_VARS  # noqa: E402
 
 
 def _customize_compiler_for_shlib(compiler):
@@ -37,9 +48,9 @@ def _customize_compiler_for_shlib(compiler):
         tmp = _CONFIG_VARS.copy()
         try:
             # XXX Help!  I don't have any idea whether these are right...
-            _CONFIG_VARS[
-                'LDSHARED'
-            ] = "gcc -Wl,-x -dynamiclib -undefined dynamic_lookup"
+            _CONFIG_VARS['LDSHARED'] = (
+                "gcc -Wl,-x -dynamiclib -undefined dynamic_lookup"
+            )
             _CONFIG_VARS['CCSHARED'] = " -dynamiclib"
             _CONFIG_VARS['SO'] = ".dylib"
             customize_compiler(compiler)
@@ -58,17 +69,13 @@ def _customize_compiler_for_shlib(compiler):
     use_stubs = True
 elif os.name != 'nt':
     try:
-        import dl
+        import dl  # type: ignore[import-not-found] # https://github.com/python/mypy/issues/13002
 
         use_stubs = have_rtld = hasattr(dl, 'RTLD_NOW')
     except ImportError:
         pass
 
 
-def if_dl(s):
-    return s if have_rtld else ''
-
-
 def get_abi3_suffix():
     """Return the file extension for an abi3-compliant Extension()"""
     for suffix in EXTENSION_SUFFIXES:
@@ -76,21 +83,23 @@ def get_abi3_suffix():
             return suffix
         elif suffix == '.pyd':  # Windows
             return suffix
+    return None
 
 
 class build_ext(_build_ext):
-    editable_mode: bool = False
-    inplace: bool = False
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+    editable_mode = False
+    inplace = False
 
-    def run(self):
+    def run(self) -> None:
         """Build extensions in build directory, then copy if --inplace"""
-        old_inplace, self.inplace = self.inplace, 0
+        old_inplace, self.inplace = self.inplace, False
         _build_ext.run(self)
         self.inplace = old_inplace
         if old_inplace:
             self.copy_extensions_to_source()
 
-    def _get_inplace_equivalent(self, build_py, ext: Extension) -> Tuple[str, str]:
+    def _get_inplace_equivalent(self, build_py, ext: Extension) -> tuple[str, str]:
         fullname = self.get_ext_fullname(ext.name)
         filename = self.get_ext_filename(fullname)
         modpath = fullname.split('.')
@@ -100,7 +109,7 @@ def _get_inplace_equivalent(self, build_py, ext: Extension) -> Tuple[str, str]:
         regular_file = os.path.join(self.build_lib, filename)
         return (inplace_file, regular_file)
 
-    def copy_extensions_to_source(self):
+    def copy_extensions_to_source(self) -> None:
         build_py = self.get_finalized_command('build_py')
         for ext in self.extensions:
             inplace_file, regular_file = self._get_inplace_equivalent(build_py, ext)
@@ -122,7 +131,7 @@ def _get_equivalent_stub(self, ext: Extension, output_file: str) -> str:
         _, _, name = ext.name.rpartition(".")
         return f"{os.path.join(dir_, name)}.py"
 
-    def _get_output_mapping(self) -> Iterator[Tuple[str, str]]:
+    def _get_output_mapping(self) -> Iterator[tuple[str, str]]:
         if not self.inplace:
             return
 
@@ -147,21 +156,25 @@ def _get_output_mapping(self) -> Iterator[Tuple[str, str]]:
                 output_cache = _compiled_file_name(regular_stub, optimization=opt)
                 yield (output_cache, inplace_cache)
 
-    def get_ext_filename(self, fullname):
+    def get_ext_filename(self, fullname: str) -> str:
         so_ext = os.getenv('SETUPTOOLS_EXT_SUFFIX')
         if so_ext:
             filename = os.path.join(*fullname.split('.')) + so_ext
         else:
             filename = _build_ext.get_ext_filename(self, fullname)
-            so_ext = get_config_var('EXT_SUFFIX')
+            ext_suffix = get_config_var('EXT_SUFFIX')
+            if not isinstance(ext_suffix, str):
+                raise OSError(
+                    "Configuration variable EXT_SUFFIX not found for this platform "
+                    "and environment variable SETUPTOOLS_EXT_SUFFIX is missing"
+                )
+            so_ext = ext_suffix
 
         if fullname in self.ext_map:
             ext = self.ext_map[fullname]
-            use_abi3 = getattr(ext, 'py_limited_api') and get_abi3_suffix()
-            if use_abi3:
-                filename = filename[: -len(so_ext)]
-                so_ext = get_abi3_suffix()
-                filename = filename + so_ext
+            abi3_suffix = get_abi3_suffix()
+            if ext.py_limited_api and abi3_suffix:  # Use abi3
+                filename = filename[: -len(so_ext)] + abi3_suffix
             if isinstance(ext, Library):
                 fn, ext = os.path.splitext(filename)
                 return self.shlib_compiler.library_filename(fn, libtype)
@@ -177,7 +190,7 @@ def initialize_options(self):
         self.ext_map = {}
         self.editable_mode = False
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         _build_ext.finalize_options(self)
         self.extensions = self.extensions or []
         self.check_extensions_list(self.extensions)
@@ -208,9 +221,9 @@ def finalize_options(self):
         if self.editable_mode:
             self.inplace = True
 
-    def setup_shlib_compiler(self):
+    def setup_shlib_compiler(self) -> None:
         compiler = self.shlib_compiler = new_compiler(
-            compiler=self.compiler, dry_run=self.dry_run, force=self.force
+            compiler=self.compiler, force=self.force
         )
         _customize_compiler_for_shlib(compiler)
 
@@ -233,14 +246,14 @@ def setup_shlib_compiler(self):
             compiler.set_link_objects(self.link_objects)
 
         # hack so distutils' build_extension() builds a library instead
-        compiler.link_shared_object = link_shared_object.__get__(compiler)
+        compiler.link_shared_object = link_shared_object.__get__(compiler)  # type: ignore[method-assign]
 
     def get_export_symbols(self, ext):
         if isinstance(ext, Library):
             return ext.export_symbols
         return _build_ext.get_export_symbols(self, ext)
 
-    def build_extension(self, ext):
+    def build_extension(self, ext) -> None:
         ext._convert_pyx_sources_to_lang()
         _compiler = self.compiler
         try:
@@ -262,7 +275,7 @@ def links_to_dynamic(self, ext):
         pkg = '.'.join(ext._full_name.split('.')[:-1] + [''])
         return any(pkg + libname in libnames for libname in ext.libraries)
 
-    def get_source_files(self) -> List[str]:
+    def get_source_files(self) -> list[str]:
         return [*_build_ext.get_source_files(self), *self._get_internal_depends()]
 
     def _get_internal_depends(self) -> Iterator[str]:
@@ -303,15 +316,15 @@ def skip(orig_path: str, reason: str) -> None:
 
             yield path.as_posix()
 
-    def get_outputs(self) -> List[str]:
+    def get_outputs(self) -> list[str]:
         if self.inplace:
             return list(self.get_output_mapping().keys())
         return sorted(_build_ext.get_outputs(self) + self.__get_stubs_outputs())
 
-    def get_output_mapping(self) -> Dict[str, str]:
+    def get_output_mapping(self) -> dict[str, str]:
         """See :class:`setuptools.commands.build.SubCommand`"""
         mapping = self._get_output_mapping()
-        return dict(sorted(mapping, key=lambda x: x[0]))
+        return dict(sorted(mapping, key=operator.itemgetter(0)))
 
     def __get_stubs_outputs(self):
         # assemble the base name for each extension that needs a stub
@@ -330,7 +343,7 @@ def __get_output_extensions(self):
         if self.get_finalized_command('build_py').optimize:
             yield '.pyo'
 
-    def write_stub(self, output_dir, ext, compile=False):
+    def write_stub(self, output_dir, ext, compile=False) -> None:
         stub_file = os.path.join(output_dir, *ext._full_name.split('.')) + '.py'
         self._write_stub_file(stub_file, ext, compile)
 
@@ -338,51 +351,52 @@ def _write_stub_file(self, stub_file: str, ext: Extension, compile=False):
         log.info("writing stub loader for %s to %s", ext._full_name, stub_file)
         if compile and os.path.exists(stub_file):
             raise BaseError(stub_file + " already exists! Please delete.")
-        if not self.dry_run:
-            f = open(stub_file, 'w')
-            f.write(
-                '\n'.join(
-                    [
-                        "def __bootstrap__():",
-                        "   global __bootstrap__, __file__, __loader__",
-                        "   import sys, os, pkg_resources, importlib.util"
-                        + if_dl(", dl"),
-                        "   __file__ = pkg_resources.resource_filename"
-                        "(__name__,%r)" % os.path.basename(ext._file_name),
-                        "   del __bootstrap__",
-                        "   if '__loader__' in globals():",
-                        "       del __loader__",
-                        if_dl("   old_flags = sys.getdlopenflags()"),
-                        "   old_dir = os.getcwd()",
-                        "   try:",
-                        "     os.chdir(os.path.dirname(__file__))",
-                        if_dl("     sys.setdlopenflags(dl.RTLD_NOW)"),
-                        "     spec = importlib.util.spec_from_file_location(",
-                        "                __name__, __file__)",
-                        "     mod = importlib.util.module_from_spec(spec)",
-                        "     spec.loader.exec_module(mod)",
-                        "   finally:",
-                        if_dl("     sys.setdlopenflags(old_flags)"),
-                        "     os.chdir(old_dir)",
-                        "__bootstrap__()",
-                        "",  # terminal \n
-                    ]
-                )
+        with open(stub_file, 'w', encoding="utf-8") as f:
+            content = (
+                textwrap
+                .dedent(f"""
+                def __bootstrap__():
+                   global __bootstrap__, __file__, __loader__
+                   import sys, os, importlib.resources as irs, importlib.util
+                #rtld   import dl
+                   with irs.files(__name__).joinpath(
+                     {os.path.basename(ext._file_name)!r}) as __file__:
+                      del __bootstrap__
+                      if '__loader__' in globals():
+                          del __loader__
+                #rtld      old_flags = sys.getdlopenflags()
+                      old_dir = os.getcwd()
+                      try:
+                        os.chdir(os.path.dirname(__file__))
+                #rtld        sys.setdlopenflags(dl.RTLD_NOW)
+                        spec = importlib.util.spec_from_file_location(
+                                   __name__, __file__)
+                        mod = importlib.util.module_from_spec(spec)
+                        spec.loader.exec_module(mod)
+                      finally:
+                #rtld        sys.setdlopenflags(old_flags)
+                        os.chdir(old_dir)
+                __bootstrap__()
+                """)
+                .lstrip()
+                .replace('#rtld', '#rtld' * (not have_rtld))
             )
-            f.close()
+            f.write(content)
         if compile:
             self._compile_and_remove_stub(stub_file)
 
     def _compile_and_remove_stub(self, stub_file: str):
         from distutils.util import byte_compile
 
-        byte_compile([stub_file], optimize=0, force=True, dry_run=self.dry_run)
+        byte_compile([stub_file], optimize=0, force=True)
         optimize = self.get_finalized_command('install_lib').optimize
         if optimize > 0:
             byte_compile(
-                [stub_file], optimize=optimize, force=True, dry_run=self.dry_run
+                [stub_file],
+                optimize=optimize,
+                force=True,
             )
-        if os.path.exists(stub_file) and not self.dry_run:
+        if os.path.exists(stub_file):
             os.unlink(stub_file)
 
 
@@ -398,12 +412,12 @@ def link_shared_object(
         library_dirs=None,
         runtime_library_dirs=None,
         export_symbols=None,
-        debug=0,
+        debug: bool = False,
         extra_preargs=None,
         extra_postargs=None,
         build_temp=None,
         target_lang=None,
-    ):
+    ) -> None:
         self.link(
             self.SHARED_LIBRARY,
             objects,
@@ -433,12 +447,12 @@ def link_shared_object(
         library_dirs=None,
         runtime_library_dirs=None,
         export_symbols=None,
-        debug=0,
+        debug: bool = False,
         extra_preargs=None,
         extra_postargs=None,
         build_temp=None,
         target_lang=None,
-    ):
+    ) -> None:
         # XXX we need to either disallow these attrs on Library instances,
         # or warn/abort here if set, or something...
         # libraries=None, library_dirs=None, runtime_library_dirs=None,
@@ -447,7 +461,7 @@ def link_shared_object(
 
         assert output_dir is None  # distutils build_ext doesn't pass this
         output_dir, filename = os.path.split(output_libname)
-        basename, ext = os.path.splitext(filename)
+        basename, _ext = os.path.splitext(filename)
         if self.library_filename("x").startswith('lib'):
             # strip 'lib' prefix; this is kludgy if some platform uses
             # a different prefix
diff --git a/setuptools/command/build_py.py b/setuptools/command/build_py.py
index 5709eb6d8c..3c7c2d1bd6 100644
--- a/setuptools/command/build_py.py
+++ b/setuptools/command/build_py.py
@@ -1,22 +1,31 @@
-from functools import partial
-from glob import glob
-from distutils.util import convert_path
-import distutils.command.build_py as orig
-import os
+from __future__ import annotations
+
 import fnmatch
-import textwrap
-import io
-import distutils.errors
 import itertools
+import operator
+import os
 import stat
+import textwrap
+from collections.abc import Iterable, Iterator
+from functools import partial
+from glob import glob
 from pathlib import Path
-from typing import Dict, Iterable, Iterator, List, Optional, Tuple
+from typing import Any
+
+from more_itertools import unique_everseen
 
-from ..extern.more_itertools import unique_everseen
+from .._path import StrPath, StrPathT
+from ..dist import Distribution
 from ..warnings import SetuptoolsDeprecationWarning
 
+import distutils.command.build_py as orig
+import distutils.errors
+from distutils.util import convert_path
+
+_IMPLICIT_DATA_FILES = ('*.pyi', 'py.typed')
 
-def make_writable(target):
+
+def make_writable(target) -> None:
     os.chmod(target, os.stat(target).st_mode | stat.S_IWRITE)
 
 
@@ -30,29 +39,35 @@ class build_py(orig.build_py):
     'py_modules' and 'packages' in the same setup operation.
     """
 
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
     editable_mode: bool = False
-    existing_egg_info_dir: Optional[str] = None  #: Private API, internal use only.
+    existing_egg_info_dir: StrPath | None = None  #: Private API, internal use only.
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         orig.build_py.finalize_options(self)
         self.package_data = self.distribution.package_data
         self.exclude_package_data = self.distribution.exclude_package_data or {}
         if 'data_files' in self.__dict__:
             del self.__dict__['data_files']
-        self.__updated_files = []
 
-    def copy_file(
-        self, infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1
-    ):
+    def copy_file(  # type: ignore[override] # No overload, no bytes support
+        self,
+        infile: StrPath,
+        outfile: StrPathT,
+        preserve_mode: bool = True,
+        preserve_times: bool = True,
+        link: str | None = None,
+        level: object = 1,
+    ) -> tuple[StrPathT | str, bool]:
         # Overwrite base class to allow using links
         if link:
             infile = str(Path(infile).resolve())
-            outfile = str(Path(outfile).resolve())
-        return super().copy_file(
+            outfile = str(Path(outfile).resolve())  # type: ignore[assignment] # Re-assigning a str when outfile is StrPath is ok
+        return super().copy_file(  # pyright: ignore[reportReturnType] # pypa/distutils#309
             infile, outfile, preserve_mode, preserve_times, link, level
         )
 
-    def run(self):
+    def run(self) -> None:
         """Build modules, packages, and copy data files to build directory"""
         if not (self.py_modules or self.packages) or self.editable_mode:
             return
@@ -66,27 +81,22 @@ def run(self):
 
         # Only compile actual .py files, using our base class' idea of what our
         # output files are.
-        self.byte_compile(orig.build_py.get_outputs(self, include_bytecode=0))
+        self.byte_compile(orig.build_py.get_outputs(self, include_bytecode=False))
 
-    def __getattr__(self, attr):
+    # Should return "list[tuple[str, str, str, list[str]]] | Any" but can't do without typed distutils on Python 3.12+
+    def __getattr__(self, attr: str) -> Any:
         "lazily compute data files"
         if attr == 'data_files':
             self.data_files = self._get_data_files()
             return self.data_files
         return orig.build_py.__getattr__(self, attr)
 
-    def build_module(self, module, module_file, package):
-        outfile, copied = orig.build_py.build_module(self, module, module_file, package)
-        if copied:
-            self.__updated_files.append(outfile)
-        return outfile, copied
-
     def _get_data_files(self):
         """Generate list of '(package,src_dir,build_dir,filenames)' tuples"""
         self.analyze_manifest()
         return list(map(self._get_pkg_data_files, self.packages or ()))
 
-    def get_data_files_without_manifest(self):
+    def get_data_files_without_manifest(self) -> list[tuple[str, str, str, list[str]]]:
         """
         Generate list of ``(package,src_dir,build_dir,filenames)`` tuples,
         but without triggering any attempt to analyze or build the manifest.
@@ -96,7 +106,7 @@ def get_data_files_without_manifest(self):
         self.__dict__.setdefault('manifest_files', {})
         return list(map(self._get_pkg_data_files, self.packages or ()))
 
-    def _get_pkg_data_files(self, package):
+    def _get_pkg_data_files(self, package: str) -> tuple[str, str, str, list[str]]:
         # Locate package source directory
         src_dir = self.get_package_dir(package)
 
@@ -116,6 +126,7 @@ def find_data_files(self, package, src_dir):
             self.package_data,
             package,
             src_dir,
+            extra_patterns=_IMPLICIT_DATA_FILES,
         )
         globs_expanded = map(partial(glob, recursive=True), patterns)
         # flatten the expanded globs into an iterable of matches
@@ -127,28 +138,28 @@ def find_data_files(self, package, src_dir):
         )
         return self.exclude_data_files(package, src_dir, files)
 
-    def get_outputs(self, include_bytecode=1) -> List[str]:
+    def get_outputs(self, include_bytecode: bool = True) -> list[str]:  # type: ignore[override] # Using a real boolean instead of 0|1
         """See :class:`setuptools.commands.build.SubCommand`"""
         if self.editable_mode:
             return list(self.get_output_mapping().keys())
         return super().get_outputs(include_bytecode)
 
-    def get_output_mapping(self) -> Dict[str, str]:
+    def get_output_mapping(self) -> dict[str, str]:
         """See :class:`setuptools.commands.build.SubCommand`"""
         mapping = itertools.chain(
             self._get_package_data_output_mapping(),
             self._get_module_mapping(),
         )
-        return dict(sorted(mapping, key=lambda x: x[0]))
+        return dict(sorted(mapping, key=operator.itemgetter(0)))
 
-    def _get_module_mapping(self) -> Iterator[Tuple[str, str]]:
+    def _get_module_mapping(self) -> Iterator[tuple[str, str]]:
         """Iterate over all modules producing (dest, src) pairs."""
         for package, module, module_file in self.find_all_modules():
             package = package.split('.')
             filename = self.get_module_outfile(self.build_lib, package, module)
             yield (filename, module_file)
 
-    def _get_package_data_output_mapping(self) -> Iterator[Tuple[str, str]]:
+    def _get_package_data_output_mapping(self) -> Iterator[tuple[str, str]]:
         """Iterate over package data producing (dest, src) pairs."""
         for package, src_dir, build_dir, filenames in self.data_files:
             for filename in filenames:
@@ -156,24 +167,24 @@ def _get_package_data_output_mapping(self) -> Iterator[Tuple[str, str]]:
                 srcfile = os.path.join(src_dir, filename)
                 yield (target, srcfile)
 
-    def build_package_data(self):
+    def build_package_data(self) -> None:
         """Copy data files into build directory"""
         for target, srcfile in self._get_package_data_output_mapping():
             self.mkpath(os.path.dirname(target))
             _outf, _copied = self.copy_file(srcfile, target)
             make_writable(target)
 
-    def analyze_manifest(self):
-        self.manifest_files = mf = {}
+    def analyze_manifest(self) -> None:
+        self.manifest_files: dict[str, list[str]] = {}
         if not self.distribution.include_package_data:
             return
-        src_dirs = {}
+        src_dirs: dict[str, str] = {}
         for package in self.packages or ():
             # Locate package source directory
             src_dirs[assert_relative(self.get_package_dir(package))] = package
 
         if (
-            getattr(self, 'existing_egg_info_dir', None)
+            self.existing_egg_info_dir
             and Path(self.existing_egg_info_dir, "SOURCES.txt").exists()
         ):
             egg_info_dir = self.existing_egg_info_dir
@@ -202,9 +213,11 @@ def analyze_manifest(self):
                     importable = check.importable_subpackage(src_dirs[d], f)
                     if importable:
                         check.warn(importable)
-                mf.setdefault(src_dirs[d], []).append(path)
+                self.manifest_files.setdefault(src_dirs[d], []).append(path)
 
-    def _filter_build_files(self, files: Iterable[str], egg_info: str) -> Iterator[str]:
+    def _filter_build_files(
+        self, files: Iterable[str], egg_info: StrPath
+    ) -> Iterator[str]:
         """
         ``build_meta`` may try to create egg_info outside of the project directory,
         and this can be problematic for certain plugins (reported in issue #3500).
@@ -223,7 +236,7 @@ def _filter_build_files(self, files: Iterable[str], egg_info: str) -> Iterator[s
             if not os.path.isabs(file) or all(d not in norm_path for d in norm_dirs):
                 yield file
 
-    def get_data_files(self):
+    def get_data_files(self) -> None:
         pass  # Lazily compute data files in _get_data_files() function.
 
     def check_package(self, package, package_dir):
@@ -245,14 +258,14 @@ def check_package(self, package, package_dir):
         else:
             return init_py
 
-        with io.open(init_py, 'rb') as f:
+        with open(init_py, 'rb') as f:
             contents = f.read()
         if b'declare_namespace' not in contents:
             raise distutils.errors.DistutilsError(
-                "Namespace package problem: %s is a namespace package, but "
+                f"Namespace package problem: {package} is a namespace package, but "
                 "its\n__init__.py does not call declare_namespace()! Please "
                 'fix it.\n(See the setuptools manual under '
-                '"Namespace Packages" for details.)\n"' % (package,)
+                '"Namespace Packages" for details.)\n"'
             )
         return init_py
 
@@ -262,7 +275,7 @@ def initialize_options(self):
         self.editable_mode = False
         self.existing_egg_info_dir = None
 
-    def get_package_dir(self, package):
+    def get_package_dir(self, package: str) -> str:
         res = orig.build_py.get_package_dir(self, package)
         if self.distribution.src_root is not None:
             return os.path.join(self.distribution.src_root, res)
@@ -285,7 +298,7 @@ def exclude_data_files(self, package, src_dir, files):
         return list(unique_everseen(keepers))
 
     @staticmethod
-    def _get_platform_patterns(spec, package, src_dir):
+    def _get_platform_patterns(spec, package, src_dir, extra_patterns=()):
         """
         yield platform-specific path patterns (suitable for glob
         or fn_match) from a glob-based spec (such as
@@ -293,6 +306,7 @@ def _get_platform_patterns(spec, package, src_dir):
         matching package in src_dir.
         """
         raw_patterns = itertools.chain(
+            extra_patterns,
             spec.get('', []),
             spec.get(package, []),
         )
@@ -370,8 +384,8 @@ class _Warning(SetuptoolsDeprecationWarning):
         # _DUE_DATE: still not defined as this is particularly controversial.
         # Warning initially introduced in May 2022. See issue #3340 for discussion.
 
-    def __init__(self):
-        self._already_warned = set()
+    def __init__(self) -> None:
+        self._already_warned = set[str]()
 
     def is_module(self, file):
         return file.endswith(".py") and file[: -len(".py")].isidentifier()
diff --git a/setuptools/command/develop.py b/setuptools/command/develop.py
index 27bcf9eb5b..2d468845e5 100644
--- a/setuptools/command/develop.py
+++ b/setuptools/command/develop.py
@@ -1,188 +1,58 @@
-from distutils.util import convert_path
-from distutils import log
-from distutils.errors import DistutilsOptionError
-import os
-import glob
-import io
+import site
+import subprocess
+import sys
+from typing import cast
 
-from setuptools.command.easy_install import easy_install
-from setuptools import _path
-from setuptools import namespaces
-import setuptools
+from setuptools import Command
+from setuptools.warnings import SetuptoolsDeprecationWarning
 
 
-class develop(namespaces.DevelopInstaller, easy_install):
+class develop(Command):
     """Set up package for development"""
 
-    description = "install package in 'development mode'"
-
-    user_options = easy_install.user_options + [
-        ("uninstall", "u", "Uninstall this source package"),
-        ("egg-path=", None, "Set the path to be used in the .egg-link file"),
+    user_options = [
+        ("install-dir=", "d", "install package to DIR"),
+        ('no-deps', 'N', "don't install dependencies"),
+        ('user', None, f"install in user site-package '{site.USER_SITE}'"),
+        ('prefix=', None, "installation prefix"),
+        ("index-url=", "i", "base URL of Python Package Index"),
+    ]
+    boolean_options = [
+        'no-deps',
+        'user',
     ]
 
-    boolean_options = easy_install.boolean_options + ['uninstall']
-
-    command_consumes_arguments = False  # override base
-
-    def run(self):
-        if self.uninstall:
-            self.multi_version = True
-            self.uninstall_link()
-            self.uninstall_namespaces()
-        else:
-            self.install_for_development()
-        self.warn_deprecated_options()
-
-    def initialize_options(self):
-        self.uninstall = None
-        self.egg_path = None
-        easy_install.initialize_options(self)
-        self.setup_path = None
-        self.always_copy_from = '.'  # always copy eggs installed in curdir
-
-    def finalize_options(self):
-        import pkg_resources
-
-        ei = self.get_finalized_command("egg_info")
-        self.args = [ei.egg_name]
-
-        easy_install.finalize_options(self)
-        self.expand_basedirs()
-        self.expand_dirs()
-        # pick up setup-dir .egg files only: no .egg-info
-        self.package_index.scan(glob.glob('*.egg'))
-
-        egg_link_fn = ei.egg_name + '.egg-link'
-        self.egg_link = os.path.join(self.install_dir, egg_link_fn)
-        self.egg_base = ei.egg_base
-        if self.egg_path is None:
-            self.egg_path = os.path.abspath(ei.egg_base)
-
-        target = _path.normpath(self.egg_base)
-        egg_path = _path.normpath(os.path.join(self.install_dir, self.egg_path))
-        if egg_path != target:
-            raise DistutilsOptionError(
-                "--egg-path must be a relative path from the install"
-                " directory to " + target
-            )
-
-        # Make a distribution for the package's source
-        self.dist = pkg_resources.Distribution(
-            target,
-            pkg_resources.PathMetadata(target, os.path.abspath(ei.egg_info)),
-            project_name=ei.egg_name,
-        )
-
-        self.setup_path = self._resolve_setup_path(
-            self.egg_base,
-            self.install_dir,
-            self.egg_path,
+    install_dir = None
+    no_deps = False
+    user = False
+    prefix = None
+    index_url = None
+
+    def run(self) -> None:
+        # Casting because mypy doesn't understand bool mult conditionals
+        cmd = cast(
+            list[str],
+            [sys.executable, '-m', 'pip', 'install', '-e', '.', '--use-pep517']
+            + ['--target', self.install_dir] * bool(self.install_dir)
+            + ['--no-deps'] * self.no_deps
+            + ['--user'] * self.user
+            + ['--prefix', self.prefix] * bool(self.prefix)
+            + ['--index-url', self.index_url] * bool(self.index_url),
         )
+        subprocess.check_call(cmd)
 
-    @staticmethod
-    def _resolve_setup_path(egg_base, install_dir, egg_path):
-        """
-        Generate a path from egg_base back to '.' where the
-        setup script resides and ensure that path points to the
-        setup path from $install_dir/$egg_path.
-        """
-        path_to_setup = egg_base.replace(os.sep, '/').rstrip('/')
-        if path_to_setup != os.curdir:
-            path_to_setup = '../' * (path_to_setup.count('/') + 1)
-        resolved = _path.normpath(os.path.join(install_dir, egg_path, path_to_setup))
-        curdir = _path.normpath(os.curdir)
-        if resolved != curdir:
-            raise DistutilsOptionError(
-                "Can't get a consistent path to setup script from"
-                " installation directory",
-                resolved,
-                curdir,
-            )
-        return path_to_setup
-
-    def install_for_development(self):
-        self.run_command('egg_info')
+    def initialize_options(self) -> None:
+        DevelopDeprecationWarning.emit()
 
-        # Build extensions in-place
-        self.reinitialize_command('build_ext', inplace=1)
-        self.run_command('build_ext')
+    def finalize_options(self) -> None:
+        pass
 
-        if setuptools.bootstrap_install_from:
-            self.easy_install(setuptools.bootstrap_install_from)
-            setuptools.bootstrap_install_from = None
 
-        self.install_namespaces()
-
-        # create an .egg-link in the installation dir, pointing to our egg
-        log.info("Creating %s (link to %s)", self.egg_link, self.egg_base)
-        if not self.dry_run:
-            with open(self.egg_link, "w") as f:
-                f.write(self.egg_path + "\n" + self.setup_path)
-        # postprocess the installed distro, fixing up .pth, installing scripts,
-        # and handling requirements
-        self.process_distribution(None, self.dist, not self.no_deps)
-
-    def uninstall_link(self):
-        if os.path.exists(self.egg_link):
-            log.info("Removing %s (link to %s)", self.egg_link, self.egg_base)
-            egg_link_file = open(self.egg_link)
-            contents = [line.rstrip() for line in egg_link_file]
-            egg_link_file.close()
-            if contents not in ([self.egg_path], [self.egg_path, self.setup_path]):
-                log.warn("Link points to %s: uninstall aborted", contents)
-                return
-            if not self.dry_run:
-                os.unlink(self.egg_link)
-        if not self.dry_run:
-            self.update_pth(self.dist)  # remove any .pth link to us
-        if self.distribution.scripts:
-            # XXX should also check for entry point scripts!
-            log.warn("Note: you must uninstall or replace scripts manually!")
-
-    def install_egg_scripts(self, dist):
-        if dist is not self.dist:
-            # Installing a dependency, so fall back to normal behavior
-            return easy_install.install_egg_scripts(self, dist)
-
-        # create wrapper scripts in the script dir, pointing to dist.scripts
-
-        # new-style...
-        self.install_wrapper_scripts(dist)
-
-        # ...and old-style
-        for script_name in self.distribution.scripts or []:
-            script_path = os.path.abspath(convert_path(script_name))
-            script_name = os.path.basename(script_path)
-            with io.open(script_path) as strm:
-                script_text = strm.read()
-            self.install_script(dist, script_name, script_text, script_path)
-
-    def install_wrapper_scripts(self, dist):
-        dist = VersionlessRequirement(dist)
-        return easy_install.install_wrapper_scripts(self, dist)
-
-
-class VersionlessRequirement:
-    """
-    Adapt a pkg_resources.Distribution to simply return the project
-    name as the 'requirement' so that scripts will work across
-    multiple versions.
-
-    >>> from pkg_resources import Distribution
-    >>> dist = Distribution(project_name='foo', version='1.0')
-    >>> str(dist.as_requirement())
-    'foo==1.0'
-    >>> adapted_dist = VersionlessRequirement(dist)
-    >>> str(adapted_dist.as_requirement())
-    'foo'
+class DevelopDeprecationWarning(SetuptoolsDeprecationWarning):
+    _SUMMARY = "develop command is deprecated."
+    _DETAILS = """
+    Please avoid running ``setup.py`` and ``develop``.
+    Instead, use standards-based tools like pip or uv.
     """
-
-    def __init__(self, dist):
-        self.__dist = dist
-
-    def __getattr__(self, name):
-        return getattr(self.__dist, name)
-
-    def as_requirement(self):
-        return self.project_name
+    _SEE_URL = "https://github.com/pypa/setuptools/issues/917"
+    _DUE_DATE = 2025, 10, 31
diff --git a/setuptools/command/dist_info.py b/setuptools/command/dist_info.py
index 9df625cee7..dca01ff0ce 100644
--- a/setuptools/command/dist_info.py
+++ b/setuptools/command/dist_info.py
@@ -5,14 +5,16 @@
 
 import os
 import shutil
-import sys
 from contextlib import contextmanager
-from distutils import log
-from distutils.core import Command
 from pathlib import Path
+from typing import cast
 
 from .. import _normalization
-from ..warnings import SetuptoolsDeprecationWarning
+from .._shutil import rmdir as _rm
+from .egg_info import egg_info as egg_info_cls
+
+from distutils import log
+from distutils.core import Command
 
 
 class dist_info(Command):
@@ -24,18 +26,11 @@ class dist_info(Command):
     description = "DO NOT CALL DIRECTLY, INTERNAL ONLY: create .dist-info directory"
 
     user_options = [
-        (
-            'egg-base=',
-            'e',
-            "directory containing .egg-info directories"
-            " (default: top of the source tree)"
-            " DEPRECATED: use --output-dir.",
-        ),
         (
             'output-dir=',
             'o',
             "directory inside of which the .dist-info will be"
-            "created (default: top of the source tree)",
+            "created [default: top of the source tree]",
         ),
         ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"),
         ('tag-build=', 'b', "Specify explicit tag to add to version number"),
@@ -47,7 +42,6 @@ class dist_info(Command):
     negative_opt = {'no-date': 'tag-date'}
 
     def initialize_options(self):
-        self.egg_base = None
         self.output_dir = None
         self.name = None
         self.dist_info_dir = None
@@ -55,19 +49,12 @@ def initialize_options(self):
         self.tag_build = None
         self.keep_egg_info = False
 
-    def finalize_options(self):
-        if self.egg_base:
-            msg = "--egg-base is deprecated for dist_info command. Use --output-dir."
-            SetuptoolsDeprecationWarning.emit(msg, due_date=(2023, 9, 26))
-            # This command is internal to setuptools, therefore it should be safe
-            # to remove the deprecated support soon.
-            self.output_dir = self.egg_base or self.output_dir
-
+    def finalize_options(self) -> None:
         dist = self.distribution
         project_dir = dist.src_root or os.curdir
         self.output_dir = Path(self.output_dir or project_dir)
 
-        egg_info = self.reinitialize_command("egg_info")
+        egg_info = cast(egg_info_cls, self.reinitialize_command("egg_info"))
         egg_info.egg_base = str(self.output_dir)
 
         if self.tag_date:
@@ -93,7 +80,7 @@ def _maybe_bkp_dir(self, dir_path: str, requires_bkp: bool):
         if requires_bkp:
             bkp_name = f"{dir_path}.__bkp__"
             _rm(bkp_name, ignore_errors=True)
-            _copy(dir_path, bkp_name, dirs_exist_ok=True, symlinks=True)
+            shutil.copytree(dir_path, bkp_name, dirs_exist_ok=True, symlinks=True)
             try:
                 yield
             finally:
@@ -102,26 +89,15 @@ def _maybe_bkp_dir(self, dir_path: str, requires_bkp: bool):
         else:
             yield
 
-    def run(self):
+    def run(self) -> None:
         self.output_dir.mkdir(parents=True, exist_ok=True)
         self.egg_info.run()
         egg_info_dir = self.egg_info.egg_info
         assert os.path.isdir(egg_info_dir), ".egg-info dir should have been created"
 
-        log.info("creating '{}'".format(os.path.abspath(self.dist_info_dir)))
+        log.info(f"creating '{os.path.abspath(self.dist_info_dir)}'")
         bdist_wheel = self.get_finalized_command('bdist_wheel')
 
         # TODO: if bdist_wheel if merged into setuptools, just add "keep_egg_info" there
         with self._maybe_bkp_dir(egg_info_dir, self.keep_egg_info):
             bdist_wheel.egg2dist(egg_info_dir, self.dist_info_dir)
-
-
-def _rm(dir_name, **opts):
-    if os.path.isdir(dir_name):
-        shutil.rmtree(dir_name, **opts)
-
-
-def _copy(src, dst, **opts):
-    if sys.version_info < (3, 8):
-        opts.pop("dirs_exist_ok", None)
-    shutil.copytree(src, dst, **opts)
diff --git a/setuptools/command/easy_install.py b/setuptools/command/easy_install.py
index 8ba4f094de..8765793d4c 100644
--- a/setuptools/command/easy_install.py
+++ b/setuptools/command/easy_install.py
@@ -1,2366 +1,30 @@
-"""
-Easy Install
-------------
-
-A tool for doing automatic download/extract/build of distutils-based Python
-packages.  For detailed documentation, see the accompanying EasyInstall.txt
-file, or visit the `EasyInstall home page`__.
-
-__ https://setuptools.pypa.io/en/latest/deprecated/easy_install.html
-
-"""
-
-from glob import glob
-from distutils.util import get_platform
-from distutils.util import convert_path, subst_vars
-from distutils.errors import (
-    DistutilsArgError,
-    DistutilsOptionError,
-    DistutilsError,
-    DistutilsPlatformError,
-)
-from distutils import log, dir_util
-from distutils.command.build_scripts import first_line_re
-from distutils.spawn import find_executable
-from distutils.command import install
-import sys
 import os
-import zipimport
-import shutil
-import tempfile
-import zipfile
-import re
-import stat
-import random
-import textwrap
-import warnings
-import site
-import struct
-import contextlib
-import subprocess
-import shlex
-import io
-import configparser
-import sysconfig
-
-
-from sysconfig import get_path
+import sys
+import types
 
 from setuptools import Command
-from setuptools.sandbox import run_setup
-from setuptools.command import setopt
-from setuptools.archive_util import unpack_archive
-from setuptools.package_index import (
-    PackageIndex,
-    parse_requirement_arg,
-    URL_SCHEME,
-)
-from setuptools.command import bdist_egg, egg_info
-from setuptools.warnings import SetuptoolsDeprecationWarning, SetuptoolsWarning
-from setuptools.wheel import Wheel
-from pkg_resources import (
-    normalize_path,
-    resource_string,
-    get_distribution,
-    find_distributions,
-    Environment,
-    Requirement,
-    Distribution,
-    PathMetadata,
-    EggMetadata,
-    WorkingSet,
-    DistributionNotFound,
-    VersionConflict,
-    DEVELOP_DIST,
-)
-import pkg_resources
-from .. import py312compat
-from .._path import ensure_directory
-from ..extern.jaraco.text import yield_lines
-
-
-# Turn on PEP440Warnings
-warnings.filterwarnings("default", category=pkg_resources.PEP440Warning)
-
-__all__ = [
-    'easy_install',
-    'PthDistributions',
-    'extract_wininst_cfg',
-    'get_exe_prefixes',
-]
 
-
-def is_64bit():
-    return struct.calcsize("P") == 8
-
-
-def _to_bytes(s):
-    return s.encode('utf8')
-
-
-def isascii(s):
-    try:
-        s.encode('ascii')
-        return True
-    except UnicodeError:
-        return False
-
-
-def _one_liner(text):
-    return textwrap.dedent(text).strip().replace('\n', '; ')
+from .. import _scripts, warnings
 
 
 class easy_install(Command):
-    """Manage a download/build/install process"""
-
-    description = "Find/get/install Python packages"
-    command_consumes_arguments = True
-
-    user_options = [
-        ('prefix=', None, "installation prefix"),
-        ("zip-ok", "z", "install package as a zipfile"),
-        ("multi-version", "m", "make apps have to require() a version"),
-        ("upgrade", "U", "force upgrade (searches PyPI for latest versions)"),
-        ("install-dir=", "d", "install package to DIR"),
-        ("script-dir=", "s", "install scripts to DIR"),
-        ("exclude-scripts", "x", "Don't install scripts"),
-        ("always-copy", "a", "Copy all needed packages to install dir"),
-        ("index-url=", "i", "base URL of Python Package Index"),
-        ("find-links=", "f", "additional URL(s) to search for packages"),
-        ("build-directory=", "b", "download/extract/build in DIR; keep the results"),
-        (
-            'optimize=',
-            'O',
-            "also compile with optimization: -O1 for \"python -O\", "
-            "-O2 for \"python -OO\", and -O0 to disable [default: -O0]",
-        ),
-        ('record=', None, "filename in which to record list of installed files"),
-        ('always-unzip', 'Z', "don't install as a zipfile, no matter what"),
-        ('site-dirs=', 'S', "list of directories where .pth files work"),
-        ('editable', 'e', "Install specified packages in editable form"),
-        ('no-deps', 'N', "don't install dependencies"),
-        ('allow-hosts=', 'H', "pattern(s) that hostnames must match"),
-        ('local-snapshots-ok', 'l', "allow building eggs from local checkouts"),
-        ('version', None, "print version information and exit"),
-        (
-            'no-find-links',
-            None,
-            "Don't load find-links defined in packages being installed",
-        ),
-        ('user', None, "install in user site-package '%s'" % site.USER_SITE),
-    ]
-    boolean_options = [
-        'zip-ok',
-        'multi-version',
-        'exclude-scripts',
-        'upgrade',
-        'always-copy',
-        'editable',
-        'no-deps',
-        'local-snapshots-ok',
-        'version',
-        'user',
-    ]
-
-    negative_opt = {'always-unzip': 'zip-ok'}
-    create_index = PackageIndex
-
-    def initialize_options(self):
-        EasyInstallDeprecationWarning.emit()
-
-        # the --user option seems to be an opt-in one,
-        # so the default should be False.
-        self.user = 0
-        self.zip_ok = self.local_snapshots_ok = None
-        self.install_dir = self.script_dir = self.exclude_scripts = None
-        self.index_url = None
-        self.find_links = None
-        self.build_directory = None
-        self.args = None
-        self.optimize = self.record = None
-        self.upgrade = self.always_copy = self.multi_version = None
-        self.editable = self.no_deps = self.allow_hosts = None
-        self.root = self.prefix = self.no_report = None
-        self.version = None
-        self.install_purelib = None  # for pure module distributions
-        self.install_platlib = None  # non-pure (dists w/ extensions)
-        self.install_headers = None  # for C/C++ headers
-        self.install_lib = None  # set to either purelib or platlib
-        self.install_scripts = None
-        self.install_data = None
-        self.install_base = None
-        self.install_platbase = None
-        self.install_userbase = site.USER_BASE
-        self.install_usersite = site.USER_SITE
-        self.no_find_links = None
-
-        # Options not specifiable via command line
-        self.package_index = None
-        self.pth_file = self.always_copy_from = None
-        self.site_dirs = None
-        self.installed_projects = {}
-        # Always read easy_install options, even if we are subclassed, or have
-        # an independent instance created.  This ensures that defaults will
-        # always come from the standard configuration file(s)' "easy_install"
-        # section, even if this is a "develop" or "install" command, or some
-        # other embedding.
-        self._dry_run = None
-        self.verbose = self.distribution.verbose
-        self.distribution._set_command_options(
-            self, self.distribution.get_option_dict('easy_install')
-        )
-
-    def delete_blockers(self, blockers):
-        extant_blockers = (
-            filename
-            for filename in blockers
-            if os.path.exists(filename) or os.path.islink(filename)
-        )
-        list(map(self._delete_path, extant_blockers))
-
-    def _delete_path(self, path):
-        log.info("Deleting %s", path)
-        if self.dry_run:
-            return
-
-        is_tree = os.path.isdir(path) and not os.path.islink(path)
-        remover = _rmtree if is_tree else os.unlink
-        remover(path)
-
-    @staticmethod
-    def _render_version():
-        """
-        Render the Setuptools version and installation details, then exit.
-        """
-        ver = '{}.{}'.format(*sys.version_info)
-        dist = get_distribution('setuptools')
-        tmpl = 'setuptools {dist.version} from {dist.location} (Python {ver})'
-        print(tmpl.format(**locals()))
-        raise SystemExit()
-
-    def finalize_options(self):  # noqa: C901  # is too complex (25)  # FIXME
-        self.version and self._render_version()
-
-        py_version = sys.version.split()[0]
-
-        self.config_vars = dict(sysconfig.get_config_vars())
-
-        self.config_vars.update(
-            {
-                'dist_name': self.distribution.get_name(),
-                'dist_version': self.distribution.get_version(),
-                'dist_fullname': self.distribution.get_fullname(),
-                'py_version': py_version,
-                'py_version_short': (
-                    f'{sys.version_info.major}.{sys.version_info.minor}'
-                ),
-                'py_version_nodot': f'{sys.version_info.major}{sys.version_info.minor}',
-                'sys_prefix': self.config_vars['prefix'],
-                'sys_exec_prefix': self.config_vars['exec_prefix'],
-                # Only python 3.2+ has abiflags
-                'abiflags': getattr(sys, 'abiflags', ''),
-                'platlibdir': getattr(sys, 'platlibdir', 'lib'),
-            }
-        )
-        with contextlib.suppress(AttributeError):
-            # only for distutils outside stdlib
-            self.config_vars.update(
-                {
-                    'implementation_lower': install._get_implementation().lower(),
-                    'implementation': install._get_implementation(),
-                }
-            )
-
-        # pypa/distutils#113 Python 3.9 compat
-        self.config_vars.setdefault(
-            'py_version_nodot_plat',
-            getattr(sys, 'windir', '').replace('.', ''),
-        )
-
-        self.config_vars['userbase'] = self.install_userbase
-        self.config_vars['usersite'] = self.install_usersite
-        if self.user and not site.ENABLE_USER_SITE:
-            log.warn("WARNING: The user site-packages directory is disabled.")
-
-        self._fix_install_dir_for_user_site()
-
-        self.expand_basedirs()
-        self.expand_dirs()
-
-        self._expand(
-            'install_dir',
-            'script_dir',
-            'build_directory',
-            'site_dirs',
-        )
-        # If a non-default installation directory was specified, default the
-        # script directory to match it.
-        if self.script_dir is None:
-            self.script_dir = self.install_dir
-
-        if self.no_find_links is None:
-            self.no_find_links = False
-
-        # Let install_dir get set by install_lib command, which in turn
-        # gets its info from the install command, and takes into account
-        # --prefix and --home and all that other crud.
-        self.set_undefined_options('install_lib', ('install_dir', 'install_dir'))
-        # Likewise, set default script_dir from 'install_scripts.install_dir'
-        self.set_undefined_options('install_scripts', ('install_dir', 'script_dir'))
-
-        if self.user and self.install_purelib:
-            self.install_dir = self.install_purelib
-            self.script_dir = self.install_scripts
-        # default --record from the install command
-        self.set_undefined_options('install', ('record', 'record'))
-        self.all_site_dirs = get_site_dirs()
-        self.all_site_dirs.extend(self._process_site_dirs(self.site_dirs))
-
-        if not self.editable:
-            self.check_site_dir()
-        default_index = os.getenv("__EASYINSTALL_INDEX", "https://pypi.org/simple/")
-        # ^ Private API for testing purposes only
-        self.index_url = self.index_url or default_index
-        self.shadow_path = self.all_site_dirs[:]
-        for path_item in self.install_dir, normalize_path(self.script_dir):
-            if path_item not in self.shadow_path:
-                self.shadow_path.insert(0, path_item)
-
-        if self.allow_hosts is not None:
-            hosts = [s.strip() for s in self.allow_hosts.split(',')]
-        else:
-            hosts = ['*']
-        if self.package_index is None:
-            self.package_index = self.create_index(
-                self.index_url,
-                search_path=self.shadow_path,
-                hosts=hosts,
-            )
-        self.local_index = Environment(self.shadow_path + sys.path)
-
-        if self.find_links is not None:
-            if isinstance(self.find_links, str):
-                self.find_links = self.find_links.split()
-        else:
-            self.find_links = []
-        if self.local_snapshots_ok:
-            self.package_index.scan_egg_links(self.shadow_path + sys.path)
-        if not self.no_find_links:
-            self.package_index.add_find_links(self.find_links)
-        self.set_undefined_options('install_lib', ('optimize', 'optimize'))
-        self.optimize = self._validate_optimize(self.optimize)
-
-        if self.editable and not self.build_directory:
-            raise DistutilsArgError(
-                "Must specify a build directory (-b) when using --editable"
-            )
-        if not self.args:
-            raise DistutilsArgError(
-                "No urls, filenames, or requirements specified (see --help)"
-            )
-
-        self.outputs = []
-
-    @staticmethod
-    def _process_site_dirs(site_dirs):
-        if site_dirs is None:
-            return
-
-        normpath = map(normalize_path, sys.path)
-        site_dirs = [os.path.expanduser(s.strip()) for s in site_dirs.split(',')]
-        for d in site_dirs:
-            if not os.path.isdir(d):
-                log.warn("%s (in --site-dirs) does not exist", d)
-            elif normalize_path(d) not in normpath:
-                raise DistutilsOptionError(d + " (in --site-dirs) is not on sys.path")
-            else:
-                yield normalize_path(d)
-
-    @staticmethod
-    def _validate_optimize(value):
-        try:
-            value = int(value)
-            if value not in range(3):
-                raise ValueError
-        except ValueError as e:
-            raise DistutilsOptionError("--optimize must be 0, 1, or 2") from e
-
-        return value
-
-    def _fix_install_dir_for_user_site(self):
-        """
-        Fix the install_dir if "--user" was used.
-        """
-        if not self.user:
-            return
-
-        self.create_home_path()
-        if self.install_userbase is None:
-            msg = "User base directory is not specified"
-            raise DistutilsPlatformError(msg)
-        self.install_base = self.install_platbase = self.install_userbase
-        scheme_name = f'{os.name}_user'
-        self.select_scheme(scheme_name)
-
-    def _expand_attrs(self, attrs):
-        for attr in attrs:
-            val = getattr(self, attr)
-            if val is not None:
-                if os.name == 'posix' or os.name == 'nt':
-                    val = os.path.expanduser(val)
-                val = subst_vars(val, self.config_vars)
-                setattr(self, attr, val)
-
-    def expand_basedirs(self):
-        """Calls `os.path.expanduser` on install_base, install_platbase and
-        root."""
-        self._expand_attrs(['install_base', 'install_platbase', 'root'])
-
-    def expand_dirs(self):
-        """Calls `os.path.expanduser` on install dirs."""
-        dirs = [
-            'install_purelib',
-            'install_platlib',
-            'install_lib',
-            'install_headers',
-            'install_scripts',
-            'install_data',
-        ]
-        self._expand_attrs(dirs)
-
-    def run(self, show_deprecation=True):
-        if show_deprecation:
-            self.announce(
-                "WARNING: The easy_install command is deprecated "
-                "and will be removed in a future version.",
-                log.WARN,
-            )
-        if self.verbose != self.distribution.verbose:
-            log.set_verbosity(self.verbose)
-        try:
-            for spec in self.args:
-                self.easy_install(spec, not self.no_deps)
-            if self.record:
-                outputs = self.outputs
-                if self.root:  # strip any package prefix
-                    root_len = len(self.root)
-                    for counter in range(len(outputs)):
-                        outputs[counter] = outputs[counter][root_len:]
-                from distutils import file_util
-
-                self.execute(
-                    file_util.write_file,
-                    (self.record, outputs),
-                    "writing list of installed files to '%s'" % self.record,
-                )
-            self.warn_deprecated_options()
-        finally:
-            log.set_verbosity(self.distribution.verbose)
-
-    def pseudo_tempname(self):
-        """Return a pseudo-tempname base in the install directory.
-        This code is intentionally naive; if a malicious party can write to
-        the target directory you're already in deep doodoo.
-        """
-        try:
-            pid = os.getpid()
-        except Exception:
-            pid = random.randint(0, sys.maxsize)
-        return os.path.join(self.install_dir, "test-easy-install-%s" % pid)
-
-    def warn_deprecated_options(self):
-        pass
-
-    def check_site_dir(self):  # noqa: C901  # is too complex (12)  # FIXME
-        """Verify that self.install_dir is .pth-capable dir, if needed"""
-
-        instdir = normalize_path(self.install_dir)
-        pth_file = os.path.join(instdir, 'easy-install.pth')
-
-        if not os.path.exists(instdir):
-            try:
-                os.makedirs(instdir)
-            except (OSError, IOError):
-                self.cant_write_to_target()
-
-        # Is it a configured, PYTHONPATH, implicit, or explicit site dir?
-        is_site_dir = instdir in self.all_site_dirs
-
-        if not is_site_dir and not self.multi_version:
-            # No?  Then directly test whether it does .pth file processing
-            is_site_dir = self.check_pth_processing()
-        else:
-            # make sure we can write to target dir
-            testfile = self.pseudo_tempname() + '.write-test'
-            test_exists = os.path.exists(testfile)
-            try:
-                if test_exists:
-                    os.unlink(testfile)
-                open(testfile, 'w').close()
-                os.unlink(testfile)
-            except (OSError, IOError):
-                self.cant_write_to_target()
-
-        if not is_site_dir and not self.multi_version:
-            # Can't install non-multi to non-site dir with easy_install
-            pythonpath = os.environ.get('PYTHONPATH', '')
-            log.warn(self.__no_default_msg, self.install_dir, pythonpath)
-
-        if is_site_dir:
-            if self.pth_file is None:
-                self.pth_file = PthDistributions(pth_file, self.all_site_dirs)
-        else:
-            self.pth_file = None
-
-        if self.multi_version and not os.path.exists(pth_file):
-            self.pth_file = None  # don't create a .pth file
-        self.install_dir = instdir
-
-    __cant_write_msg = textwrap.dedent(
-        """
-        can't create or remove files in install directory
-
-        The following error occurred while trying to add or remove files in the
-        installation directory:
-
-            %s
-
-        The installation directory you specified (via --install-dir, --prefix, or
-        the distutils default setting) was:
-
-            %s
-        """
-    ).lstrip()  # noqa
-
-    __not_exists_id = textwrap.dedent(
-        """
-        This directory does not currently exist.  Please create it and try again, or
-        choose a different installation directory (using the -d or --install-dir
-        option).
-        """
-    ).lstrip()  # noqa
-
-    __access_msg = textwrap.dedent(
-        """
-        Perhaps your account does not have write access to this directory?  If the
-        installation directory is a system-owned directory, you may need to sign in
-        as the administrator or "root" account.  If you do not have administrative
-        access to this machine, you may wish to choose a different installation
-        directory, preferably one that is listed in your PYTHONPATH environment
-        variable.
-
-        For information on other options, you may wish to consult the
-        documentation at:
-
-          https://setuptools.pypa.io/en/latest/deprecated/easy_install.html
-
-        Please make the appropriate changes for your system and try again.
-        """
-    ).lstrip()  # noqa
-
-    def cant_write_to_target(self):
-        msg = self.__cant_write_msg % (
-            sys.exc_info()[1],
-            self.install_dir,
-        )
-
-        if not os.path.exists(self.install_dir):
-            msg += '\n' + self.__not_exists_id
-        else:
-            msg += '\n' + self.__access_msg
-        raise DistutilsError(msg)
-
-    def check_pth_processing(self):
-        """Empirically verify whether .pth files are supported in inst. dir"""
-        instdir = self.install_dir
-        log.info("Checking .pth file support in %s", instdir)
-        pth_file = self.pseudo_tempname() + ".pth"
-        ok_file = pth_file + '.ok'
-        ok_exists = os.path.exists(ok_file)
-        tmpl = (
-            _one_liner(
-                """
-            import os
-            f = open({ok_file!r}, 'w')
-            f.write('OK')
-            f.close()
-            """
-            )
-            + '\n'
-        )
-        try:
-            if ok_exists:
-                os.unlink(ok_file)
-            dirname = os.path.dirname(ok_file)
-            os.makedirs(dirname, exist_ok=True)
-            f = open(pth_file, 'w')
-        except (OSError, IOError):
-            self.cant_write_to_target()
-        else:
-            try:
-                f.write(tmpl.format(**locals()))
-                f.close()
-                f = None
-                executable = sys.executable
-                if os.name == 'nt':
-                    dirname, basename = os.path.split(executable)
-                    alt = os.path.join(dirname, 'pythonw.exe')
-                    use_alt = basename.lower() == 'python.exe' and os.path.exists(alt)
-                    if use_alt:
-                        # use pythonw.exe to avoid opening a console window
-                        executable = alt
-
-                from distutils.spawn import spawn
-
-                spawn([executable, '-E', '-c', 'pass'], 0)
-
-                if os.path.exists(ok_file):
-                    log.info("TEST PASSED: %s appears to support .pth files", instdir)
-                    return True
-            finally:
-                if f:
-                    f.close()
-                if os.path.exists(ok_file):
-                    os.unlink(ok_file)
-                if os.path.exists(pth_file):
-                    os.unlink(pth_file)
-        if not self.multi_version:
-            log.warn("TEST FAILED: %s does NOT support .pth files", instdir)
-        return False
-
-    def install_egg_scripts(self, dist):
-        """Write all the scripts for `dist`, unless scripts are excluded"""
-        if not self.exclude_scripts and dist.metadata_isdir('scripts'):
-            for script_name in dist.metadata_listdir('scripts'):
-                if dist.metadata_isdir('scripts/' + script_name):
-                    # The "script" is a directory, likely a Python 3
-                    # __pycache__ directory, so skip it.
-                    continue
-                self.install_script(
-                    dist, script_name, dist.get_metadata('scripts/' + script_name)
-                )
-        self.install_wrapper_scripts(dist)
-
-    def add_output(self, path):
-        if os.path.isdir(path):
-            for base, dirs, files in os.walk(path):
-                for filename in files:
-                    self.outputs.append(os.path.join(base, filename))
-        else:
-            self.outputs.append(path)
-
-    def not_editable(self, spec):
-        if self.editable:
-            raise DistutilsArgError(
-                "Invalid argument %r: you can't use filenames or URLs "
-                "with --editable (except via the --find-links option)." % (spec,)
-            )
-
-    def check_editable(self, spec):
-        if not self.editable:
-            return
-
-        if os.path.exists(os.path.join(self.build_directory, spec.key)):
-            raise DistutilsArgError(
-                "%r already exists in %s; can't do a checkout there"
-                % (spec.key, self.build_directory)
-            )
-
-    @contextlib.contextmanager
-    def _tmpdir(self):
-        tmpdir = tempfile.mkdtemp(prefix=u"easy_install-")
-        try:
-            # cast to str as workaround for #709 and #710 and #712
-            yield str(tmpdir)
-        finally:
-            os.path.exists(tmpdir) and _rmtree(tmpdir)
-
-    def easy_install(self, spec, deps=False):
-        with self._tmpdir() as tmpdir:
-            if not isinstance(spec, Requirement):
-                if URL_SCHEME(spec):
-                    # It's a url, download it to tmpdir and process
-                    self.not_editable(spec)
-                    dl = self.package_index.download(spec, tmpdir)
-                    return self.install_item(None, dl, tmpdir, deps, True)
-
-                elif os.path.exists(spec):
-                    # Existing file or directory, just process it directly
-                    self.not_editable(spec)
-                    return self.install_item(None, spec, tmpdir, deps, True)
-                else:
-                    spec = parse_requirement_arg(spec)
-
-            self.check_editable(spec)
-            dist = self.package_index.fetch_distribution(
-                spec,
-                tmpdir,
-                self.upgrade,
-                self.editable,
-                not self.always_copy,
-                self.local_index,
-            )
-            if dist is None:
-                msg = "Could not find suitable distribution for %r" % spec
-                if self.always_copy:
-                    msg += " (--always-copy skips system and development eggs)"
-                raise DistutilsError(msg)
-            elif dist.precedence == DEVELOP_DIST:
-                # .egg-info dists don't need installing, just process deps
-                self.process_distribution(spec, dist, deps, "Using")
-                return dist
-            else:
-                return self.install_item(spec, dist.location, tmpdir, deps)
-
-    def install_item(self, spec, download, tmpdir, deps, install_needed=False):
-        # Installation is also needed if file in tmpdir or is not an egg
-        install_needed = install_needed or self.always_copy
-        install_needed = install_needed or os.path.dirname(download) == tmpdir
-        install_needed = install_needed or not download.endswith('.egg')
-        install_needed = install_needed or (
-            self.always_copy_from is not None
-            and os.path.dirname(normalize_path(download))
-            == normalize_path(self.always_copy_from)
-        )
-
-        if spec and not install_needed:
-            # at this point, we know it's a local .egg, we just don't know if
-            # it's already installed.
-            for dist in self.local_index[spec.project_name]:
-                if dist.location == download:
-                    break
-            else:
-                install_needed = True  # it's not in the local index
-
-        log.info("Processing %s", os.path.basename(download))
-
-        if install_needed:
-            dists = self.install_eggs(spec, download, tmpdir)
-            for dist in dists:
-                self.process_distribution(spec, dist, deps)
-        else:
-            dists = [self.egg_distribution(download)]
-            self.process_distribution(spec, dists[0], deps, "Using")
-
-        if spec is not None:
-            for dist in dists:
-                if dist in spec:
-                    return dist
-
-    def select_scheme(self, name):
-        try:
-            install._select_scheme(self, name)
-        except AttributeError:
-            # stdlib distutils
-            install.install.select_scheme(self, name.replace('posix', 'unix'))
-
-    # FIXME: 'easy_install.process_distribution' is too complex (12)
-    def process_distribution(  # noqa: C901
-        self,
-        requirement,
-        dist,
-        deps=True,
-        *info,
-    ):
-        self.update_pth(dist)
-        self.package_index.add(dist)
-        if dist in self.local_index[dist.key]:
-            self.local_index.remove(dist)
-        self.local_index.add(dist)
-        self.install_egg_scripts(dist)
-        self.installed_projects[dist.key] = dist
-        log.info(self.installation_report(requirement, dist, *info))
-        if dist.has_metadata('dependency_links.txt') and not self.no_find_links:
-            self.package_index.add_find_links(
-                dist.get_metadata_lines('dependency_links.txt')
-            )
-        if not deps and not self.always_copy:
-            return
-        elif requirement is not None and dist.key != requirement.key:
-            log.warn("Skipping dependencies for %s", dist)
-            return  # XXX this is not the distribution we were looking for
-        elif requirement is None or dist not in requirement:
-            # if we wound up with a different version, resolve what we've got
-            distreq = dist.as_requirement()
-            requirement = Requirement(str(distreq))
-        log.info("Processing dependencies for %s", requirement)
-        try:
-            distros = WorkingSet([]).resolve(
-                [requirement], self.local_index, self.easy_install
-            )
-        except DistributionNotFound as e:
-            raise DistutilsError(str(e)) from e
-        except VersionConflict as e:
-            raise DistutilsError(e.report()) from e
-        if self.always_copy or self.always_copy_from:
-            # Force all the relevant distros to be copied or activated
-            for dist in distros:
-                if dist.key not in self.installed_projects:
-                    self.easy_install(dist.as_requirement())
-        log.info("Finished processing dependencies for %s", requirement)
-
-    def should_unzip(self, dist):
-        if self.zip_ok is not None:
-            return not self.zip_ok
-        if dist.has_metadata('not-zip-safe'):
-            return True
-        if not dist.has_metadata('zip-safe'):
-            return True
-        return False
-
-    def maybe_move(self, spec, dist_filename, setup_base):
-        dst = os.path.join(self.build_directory, spec.key)
-        if os.path.exists(dst):
-            msg = "%r already exists in %s; build directory %s will not be kept"
-            log.warn(msg, spec.key, self.build_directory, setup_base)
-            return setup_base
-        if os.path.isdir(dist_filename):
-            setup_base = dist_filename
-        else:
-            if os.path.dirname(dist_filename) == setup_base:
-                os.unlink(dist_filename)  # get it out of the tmp dir
-            contents = os.listdir(setup_base)
-            if len(contents) == 1:
-                dist_filename = os.path.join(setup_base, contents[0])
-                if os.path.isdir(dist_filename):
-                    # if the only thing there is a directory, move it instead
-                    setup_base = dist_filename
-        ensure_directory(dst)
-        shutil.move(setup_base, dst)
-        return dst
-
-    def install_wrapper_scripts(self, dist):
-        if self.exclude_scripts:
-            return
-        for args in ScriptWriter.best().get_args(dist):
-            self.write_script(*args)
-
-    def install_script(self, dist, script_name, script_text, dev_path=None):
-        """Generate a legacy script wrapper and install it"""
-        spec = str(dist.as_requirement())
-        is_script = is_python_script(script_text, script_name)
-
-        if is_script:
-            body = self._load_template(dev_path) % locals()
-            script_text = ScriptWriter.get_header(script_text) + body
-        self.write_script(script_name, _to_bytes(script_text), 'b')
-
-    @staticmethod
-    def _load_template(dev_path):
-        """
-        There are a couple of template scripts in the package. This
-        function loads one of them and prepares it for use.
-        """
-        # See https://github.com/pypa/setuptools/issues/134 for info
-        # on script file naming and downstream issues with SVR4
-        name = 'script.tmpl'
-        if dev_path:
-            name = name.replace('.tmpl', ' (dev).tmpl')
-
-        raw_bytes = resource_string('setuptools', name)
-        return raw_bytes.decode('utf-8')
-
-    def write_script(self, script_name, contents, mode="t", blockers=()):
-        """Write an executable file to the scripts directory"""
-        self.delete_blockers(  # clean up old .py/.pyw w/o a script
-            [os.path.join(self.script_dir, x) for x in blockers]
-        )
-        log.info("Installing %s script to %s", script_name, self.script_dir)
-        target = os.path.join(self.script_dir, script_name)
-        self.add_output(target)
-
-        if self.dry_run:
-            return
-
-        mask = current_umask()
-        ensure_directory(target)
-        if os.path.exists(target):
-            os.unlink(target)
-        with open(target, "w" + mode) as f:
-            f.write(contents)
-        chmod(target, 0o777 - mask)
-
-    def install_eggs(self, spec, dist_filename, tmpdir):
-        # .egg dirs or files are already built, so just return them
-        installer_map = {
-            '.egg': self.install_egg,
-            '.exe': self.install_exe,
-            '.whl': self.install_wheel,
-        }
-        try:
-            install_dist = installer_map[dist_filename.lower()[-4:]]
-        except KeyError:
-            pass
-        else:
-            return [install_dist(dist_filename, tmpdir)]
-
-        # Anything else, try to extract and build
-        setup_base = tmpdir
-        if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'):
-            unpack_archive(dist_filename, tmpdir, self.unpack_progress)
-        elif os.path.isdir(dist_filename):
-            setup_base = os.path.abspath(dist_filename)
-
-        if (
-            setup_base.startswith(tmpdir)  # something we downloaded
-            and self.build_directory
-            and spec is not None
-        ):
-            setup_base = self.maybe_move(spec, dist_filename, setup_base)
-
-        # Find the setup.py file
-        setup_script = os.path.join(setup_base, 'setup.py')
-
-        if not os.path.exists(setup_script):
-            setups = glob(os.path.join(setup_base, '*', 'setup.py'))
-            if not setups:
-                raise DistutilsError(
-                    "Couldn't find a setup script in %s"
-                    % os.path.abspath(dist_filename)
-                )
-            if len(setups) > 1:
-                raise DistutilsError(
-                    "Multiple setup scripts in %s" % os.path.abspath(dist_filename)
-                )
-            setup_script = setups[0]
-
-        # Now run it, and return the result
-        if self.editable:
-            log.info(self.report_editable(spec, setup_script))
-            return []
-        else:
-            return self.build_and_install(setup_script, setup_base)
-
-    def egg_distribution(self, egg_path):
-        if os.path.isdir(egg_path):
-            metadata = PathMetadata(egg_path, os.path.join(egg_path, 'EGG-INFO'))
-        else:
-            metadata = EggMetadata(zipimport.zipimporter(egg_path))
-        return Distribution.from_filename(egg_path, metadata=metadata)
-
-    # FIXME: 'easy_install.install_egg' is too complex (11)
-    def install_egg(self, egg_path, tmpdir):  # noqa: C901
-        destination = os.path.join(
-            self.install_dir,
-            os.path.basename(egg_path),
-        )
-        destination = os.path.abspath(destination)
-        if not self.dry_run:
-            ensure_directory(destination)
-
-        dist = self.egg_distribution(egg_path)
-        if not (
-            os.path.exists(destination) and os.path.samefile(egg_path, destination)
-        ):
-            if os.path.isdir(destination) and not os.path.islink(destination):
-                dir_util.remove_tree(destination, dry_run=self.dry_run)
-            elif os.path.exists(destination):
-                self.execute(
-                    os.unlink,
-                    (destination,),
-                    "Removing " + destination,
-                )
-            try:
-                new_dist_is_zipped = False
-                if os.path.isdir(egg_path):
-                    if egg_path.startswith(tmpdir):
-                        f, m = shutil.move, "Moving"
-                    else:
-                        f, m = shutil.copytree, "Copying"
-                elif self.should_unzip(dist):
-                    self.mkpath(destination)
-                    f, m = self.unpack_and_compile, "Extracting"
-                else:
-                    new_dist_is_zipped = True
-                    if egg_path.startswith(tmpdir):
-                        f, m = shutil.move, "Moving"
-                    else:
-                        f, m = shutil.copy2, "Copying"
-                self.execute(
-                    f,
-                    (egg_path, destination),
-                    (m + " %s to %s")
-                    % (os.path.basename(egg_path), os.path.dirname(destination)),
-                )
-                update_dist_caches(
-                    destination,
-                    fix_zipimporter_caches=new_dist_is_zipped,
-                )
-            except Exception:
-                update_dist_caches(destination, fix_zipimporter_caches=False)
-                raise
-
-        self.add_output(destination)
-        return self.egg_distribution(destination)
-
-    def install_exe(self, dist_filename, tmpdir):
-        # See if it's valid, get data
-        cfg = extract_wininst_cfg(dist_filename)
-        if cfg is None:
-            raise DistutilsError(
-                "%s is not a valid distutils Windows .exe" % dist_filename
-            )
-        # Create a dummy distribution object until we build the real distro
-        dist = Distribution(
-            None,
-            project_name=cfg.get('metadata', 'name'),
-            version=cfg.get('metadata', 'version'),
-            platform=get_platform(),
-        )
-
-        # Convert the .exe to an unpacked egg
-        egg_path = os.path.join(tmpdir, dist.egg_name() + '.egg')
-        dist.location = egg_path
-        egg_tmp = egg_path + '.tmp'
-        _egg_info = os.path.join(egg_tmp, 'EGG-INFO')
-        pkg_inf = os.path.join(_egg_info, 'PKG-INFO')
-        ensure_directory(pkg_inf)  # make sure EGG-INFO dir exists
-        dist._provider = PathMetadata(egg_tmp, _egg_info)  # XXX
-        self.exe_to_egg(dist_filename, egg_tmp)
-
-        # Write EGG-INFO/PKG-INFO
-        if not os.path.exists(pkg_inf):
-            f = open(pkg_inf, 'w')
-            f.write('Metadata-Version: 1.0\n')
-            for k, v in cfg.items('metadata'):
-                if k != 'target_version':
-                    f.write('%s: %s\n' % (k.replace('_', '-').title(), v))
-            f.close()
-        script_dir = os.path.join(_egg_info, 'scripts')
-        # delete entry-point scripts to avoid duping
-        self.delete_blockers(
-            [os.path.join(script_dir, args[0]) for args in ScriptWriter.get_args(dist)]
-        )
-        # Build .egg file from tmpdir
-        bdist_egg.make_zipfile(
-            egg_path,
-            egg_tmp,
-            verbose=self.verbose,
-            dry_run=self.dry_run,
-        )
-        # install the .egg
-        return self.install_egg(egg_path, tmpdir)
-
-    # FIXME: 'easy_install.exe_to_egg' is too complex (12)
-    def exe_to_egg(self, dist_filename, egg_tmp):  # noqa: C901
-        """Extract a bdist_wininst to the directories an egg would use"""
-        # Check for .pth file and set up prefix translations
-        prefixes = get_exe_prefixes(dist_filename)
-        to_compile = []
-        native_libs = []
-        top_level = {}
-
-        def process(src, dst):
-            s = src.lower()
-            for old, new in prefixes:
-                if s.startswith(old):
-                    src = new + src[len(old) :]
-                    parts = src.split('/')
-                    dst = os.path.join(egg_tmp, *parts)
-                    dl = dst.lower()
-                    if dl.endswith('.pyd') or dl.endswith('.dll'):
-                        parts[-1] = bdist_egg.strip_module(parts[-1])
-                        top_level[os.path.splitext(parts[0])[0]] = 1
-                        native_libs.append(src)
-                    elif dl.endswith('.py') and old != 'SCRIPTS/':
-                        top_level[os.path.splitext(parts[0])[0]] = 1
-                        to_compile.append(dst)
-                    return dst
-            if not src.endswith('.pth'):
-                log.warn("WARNING: can't process %s", src)
-            return None
-
-        # extract, tracking .pyd/.dll->native_libs and .py -> to_compile
-        unpack_archive(dist_filename, egg_tmp, process)
-        stubs = []
-        for res in native_libs:
-            if res.lower().endswith('.pyd'):  # create stubs for .pyd's
-                parts = res.split('/')
-                resource = parts[-1]
-                parts[-1] = bdist_egg.strip_module(parts[-1]) + '.py'
-                pyfile = os.path.join(egg_tmp, *parts)
-                to_compile.append(pyfile)
-                stubs.append(pyfile)
-                bdist_egg.write_stub(resource, pyfile)
-        self.byte_compile(to_compile)  # compile .py's
-        bdist_egg.write_safety_flag(
-            os.path.join(egg_tmp, 'EGG-INFO'), bdist_egg.analyze_egg(egg_tmp, stubs)
-        )  # write zip-safety flag
-
-        for name in 'top_level', 'native_libs':
-            if locals()[name]:
-                txt = os.path.join(egg_tmp, 'EGG-INFO', name + '.txt')
-                if not os.path.exists(txt):
-                    f = open(txt, 'w')
-                    f.write('\n'.join(locals()[name]) + '\n')
-                    f.close()
-
-    def install_wheel(self, wheel_path, tmpdir):
-        wheel = Wheel(wheel_path)
-        assert wheel.is_compatible()
-        destination = os.path.join(self.install_dir, wheel.egg_name())
-        destination = os.path.abspath(destination)
-        if not self.dry_run:
-            ensure_directory(destination)
-        if os.path.isdir(destination) and not os.path.islink(destination):
-            dir_util.remove_tree(destination, dry_run=self.dry_run)
-        elif os.path.exists(destination):
-            self.execute(
-                os.unlink,
-                (destination,),
-                "Removing " + destination,
-            )
-        try:
-            self.execute(
-                wheel.install_as_egg,
-                (destination,),
-                ("Installing %s to %s")
-                % (os.path.basename(wheel_path), os.path.dirname(destination)),
-            )
-        finally:
-            update_dist_caches(destination, fix_zipimporter_caches=False)
-        self.add_output(destination)
-        return self.egg_distribution(destination)
-
-    __mv_warning = textwrap.dedent(
-        """
-        Because this distribution was installed --multi-version, before you can
-        import modules from this package in an application, you will need to
-        'import pkg_resources' and then use a 'require()' call similar to one of
-        these examples, in order to select the desired version:
-
-            pkg_resources.require("%(name)s")  # latest installed version
-            pkg_resources.require("%(name)s==%(version)s")  # this exact version
-            pkg_resources.require("%(name)s>=%(version)s")  # this version or higher
-        """
-    ).lstrip()  # noqa
-
-    __id_warning = textwrap.dedent(
-        """
-        Note also that the installation directory must be on sys.path at runtime for
-        this to work.  (e.g. by being the application's script directory, by being on
-        PYTHONPATH, or by being added to sys.path by your code.)
-        """
-    )  # noqa
-
-    def installation_report(self, req, dist, what="Installed"):
-        """Helpful installation message for display to package users"""
-        msg = "\n%(what)s %(eggloc)s%(extras)s"
-        if self.multi_version and not self.no_report:
-            msg += '\n' + self.__mv_warning
-            if self.install_dir not in map(normalize_path, sys.path):
-                msg += '\n' + self.__id_warning
-
-        eggloc = dist.location
-        name = dist.project_name
-        version = dist.version
-        extras = ''  # TODO: self.report_extras(req, dist)
-        return msg % locals()
-
-    __editable_msg = textwrap.dedent(
-        """
-        Extracted editable version of %(spec)s to %(dirname)s
-
-        If it uses setuptools in its setup script, you can activate it in
-        "development" mode by going to that directory and running::
-
-            %(python)s setup.py develop
-
-        See the setuptools documentation for the "develop" command for more info.
-        """
-    ).lstrip()  # noqa
-
-    def report_editable(self, spec, setup_script):
-        dirname = os.path.dirname(setup_script)
-        python = sys.executable
-        return '\n' + self.__editable_msg % locals()
-
-    def run_setup(self, setup_script, setup_base, args):
-        sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg)
-        sys.modules.setdefault('distutils.command.egg_info', egg_info)
-
-        args = list(args)
-        if self.verbose > 2:
-            v = 'v' * (self.verbose - 1)
-            args.insert(0, '-' + v)
-        elif self.verbose < 2:
-            args.insert(0, '-q')
-        if self.dry_run:
-            args.insert(0, '-n')
-        log.info("Running %s %s", setup_script[len(setup_base) + 1 :], ' '.join(args))
-        try:
-            run_setup(setup_script, args)
-        except SystemExit as v:
-            raise DistutilsError("Setup script exited with %s" % (v.args[0],)) from v
-
-    def build_and_install(self, setup_script, setup_base):
-        args = ['bdist_egg', '--dist-dir']
-
-        dist_dir = tempfile.mkdtemp(
-            prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script)
-        )
-        try:
-            self._set_fetcher_options(os.path.dirname(setup_script))
-            args.append(dist_dir)
-
-            self.run_setup(setup_script, setup_base, args)
-            all_eggs = Environment([dist_dir])
-            eggs = []
-            for key in all_eggs:
-                for dist in all_eggs[key]:
-                    eggs.append(self.install_egg(dist.location, setup_base))
-            if not eggs and not self.dry_run:
-                log.warn("No eggs found in %s (setup script problem?)", dist_dir)
-            return eggs
-        finally:
-            _rmtree(dist_dir)
-            log.set_verbosity(self.verbose)  # restore our log verbosity
-
-    def _set_fetcher_options(self, base):
-        """
-        When easy_install is about to run bdist_egg on a source dist, that
-        source dist might have 'setup_requires' directives, requiring
-        additional fetching. Ensure the fetcher options given to easy_install
-        are available to that command as well.
-        """
-        # find the fetch options from easy_install and write them out
-        # to the setup.cfg file.
-        ei_opts = self.distribution.get_option_dict('easy_install').copy()
-        fetch_directives = (
-            'find_links',
-            'site_dirs',
-            'index_url',
-            'optimize',
-            'allow_hosts',
-        )
-        fetch_options = {}
-        for key, val in ei_opts.items():
-            if key not in fetch_directives:
-                continue
-            fetch_options[key] = val[1]
-        # create a settings dictionary suitable for `edit_config`
-        settings = dict(easy_install=fetch_options)
-        cfg_filename = os.path.join(base, 'setup.cfg')
-        setopt.edit_config(cfg_filename, settings)
-
-    def update_pth(self, dist):  # noqa: C901  # is too complex (11)  # FIXME
-        if self.pth_file is None:
-            return
-
-        for d in self.pth_file[dist.key]:  # drop old entries
-            if not self.multi_version and d.location == dist.location:
-                continue
-
-            log.info("Removing %s from easy-install.pth file", d)
-            self.pth_file.remove(d)
-            if d.location in self.shadow_path:
-                self.shadow_path.remove(d.location)
-
-        if not self.multi_version:
-            if dist.location in self.pth_file.paths:
-                log.info(
-                    "%s is already the active version in easy-install.pth",
-                    dist,
-                )
-            else:
-                log.info("Adding %s to easy-install.pth file", dist)
-                self.pth_file.add(dist)  # add new entry
-                if dist.location not in self.shadow_path:
-                    self.shadow_path.append(dist.location)
-
-        if self.dry_run:
-            return
-
-        self.pth_file.save()
-
-        if dist.key != 'setuptools':
-            return
-
-        # Ensure that setuptools itself never becomes unavailable!
-        # XXX should this check for latest version?
-        filename = os.path.join(self.install_dir, 'setuptools.pth')
-        if os.path.islink(filename):
-            os.unlink(filename)
-        with open(filename, 'wt') as f:
-            f.write(self.pth_file.make_relative(dist.location) + '\n')
-
-    def unpack_progress(self, src, dst):
-        # Progress filter for unpacking
-        log.debug("Unpacking %s to %s", src, dst)
-        return dst  # only unpack-and-compile skips files for dry run
-
-    def unpack_and_compile(self, egg_path, destination):
-        to_compile = []
-        to_chmod = []
-
-        def pf(src, dst):
-            if dst.endswith('.py') and not src.startswith('EGG-INFO/'):
-                to_compile.append(dst)
-            elif dst.endswith('.dll') or dst.endswith('.so'):
-                to_chmod.append(dst)
-            self.unpack_progress(src, dst)
-            return not self.dry_run and dst or None
-
-        unpack_archive(egg_path, destination, pf)
-        self.byte_compile(to_compile)
-        if not self.dry_run:
-            for f in to_chmod:
-                mode = ((os.stat(f)[stat.ST_MODE]) | 0o555) & 0o7755
-                chmod(f, mode)
-
-    def byte_compile(self, to_compile):
-        if sys.dont_write_bytecode:
-            return
-
-        from distutils.util import byte_compile
-
-        try:
-            # try to make the byte compile messages quieter
-            log.set_verbosity(self.verbose - 1)
-
-            byte_compile(to_compile, optimize=0, force=1, dry_run=self.dry_run)
-            if self.optimize:
-                byte_compile(
-                    to_compile,
-                    optimize=self.optimize,
-                    force=1,
-                    dry_run=self.dry_run,
-                )
-        finally:
-            log.set_verbosity(self.verbose)  # restore original verbosity
-
-    __no_default_msg = textwrap.dedent(
-        """
-        bad install directory or PYTHONPATH
-
-        You are attempting to install a package to a directory that is not
-        on PYTHONPATH and which Python does not read ".pth" files from.  The
-        installation directory you specified (via --install-dir, --prefix, or
-        the distutils default setting) was:
-
-            %s
-
-        and your PYTHONPATH environment variable currently contains:
-
-            %r
-
-        Here are some of your options for correcting the problem:
-
-        * You can choose a different installation directory, i.e., one that is
-          on PYTHONPATH or supports .pth files
-
-        * You can add the installation directory to the PYTHONPATH environment
-          variable.  (It must then also be on PYTHONPATH whenever you run
-          Python and want to use the package(s) you are installing.)
-
-        * You can set up the installation directory to support ".pth" files by
-          using one of the approaches described here:
+    """Stubbed command for temporary pbr compatibility."""
 
-          https://setuptools.pypa.io/en/latest/deprecated/easy_install.html#custom-installation-locations
 
-
-        Please make the appropriate changes for your system and try again.
-        """
-    ).strip()
-
-    def create_home_path(self):
-        """Create directories under ~."""
-        if not self.user:
-            return
-        home = convert_path(os.path.expanduser("~"))
-        for path in only_strs(self.config_vars.values()):
-            if path.startswith(home) and not os.path.isdir(path):
-                self.debug_print("os.makedirs('%s', 0o700)" % path)
-                os.makedirs(path, 0o700)
-
-    INSTALL_SCHEMES = dict(
-        posix=dict(
-            install_dir='$base/lib/python$py_version_short/site-packages',
-            script_dir='$base/bin',
+def __getattr__(name):
+    attr = getattr(
+        types.SimpleNamespace(
+            ScriptWriter=_scripts.ScriptWriter,
+            sys_executable=os.environ.get(
+                "__PYVENV_LAUNCHER__", os.path.normpath(sys.executable)
+            ),
         ),
+        name,
     )
-
-    DEFAULT_SCHEME = dict(
-        install_dir='$base/Lib/site-packages',
-        script_dir='$base/Scripts',
+    warnings.SetuptoolsDeprecationWarning.emit(
+        summary="easy_install module is deprecated",
+        details="Avoid accessing attributes of setuptools.command.easy_install.",
+        due_date=(2025, 10, 31),
+        see_url="https://github.com/pypa/setuptools/issues/4976",
     )
-
-    def _expand(self, *attrs):
-        config_vars = self.get_finalized_command('install').config_vars
-
-        if self.prefix:
-            # Set default install_dir/scripts from --prefix
-            config_vars = dict(config_vars)
-            config_vars['base'] = self.prefix
-            scheme = self.INSTALL_SCHEMES.get(os.name, self.DEFAULT_SCHEME)
-            for attr, val in scheme.items():
-                if getattr(self, attr, None) is None:
-                    setattr(self, attr, val)
-
-        from distutils.util import subst_vars
-
-        for attr in attrs:
-            val = getattr(self, attr)
-            if val is not None:
-                val = subst_vars(val, config_vars)
-                if os.name == 'posix':
-                    val = os.path.expanduser(val)
-                setattr(self, attr, val)
-
-
-def _pythonpath():
-    items = os.environ.get('PYTHONPATH', '').split(os.pathsep)
-    return filter(None, items)
-
-
-def get_site_dirs():
-    """
-    Return a list of 'site' dirs
-    """
-
-    sitedirs = []
-
-    # start with PYTHONPATH
-    sitedirs.extend(_pythonpath())
-
-    prefixes = [sys.prefix]
-    if sys.exec_prefix != sys.prefix:
-        prefixes.append(sys.exec_prefix)
-    for prefix in prefixes:
-        if not prefix:
-            continue
-
-        if sys.platform in ('os2emx', 'riscos'):
-            sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
-        elif os.sep == '/':
-            sitedirs.extend(
-                [
-                    os.path.join(
-                        prefix,
-                        "lib",
-                        "python{}.{}".format(*sys.version_info),
-                        "site-packages",
-                    ),
-                    os.path.join(prefix, "lib", "site-python"),
-                ]
-            )
-        else:
-            sitedirs.extend(
-                [
-                    prefix,
-                    os.path.join(prefix, "lib", "site-packages"),
-                ]
-            )
-        if sys.platform != 'darwin':
-            continue
-
-        # for framework builds *only* we add the standard Apple
-        # locations. Currently only per-user, but /Library and
-        # /Network/Library could be added too
-        if 'Python.framework' not in prefix:
-            continue
-
-        home = os.environ.get('HOME')
-        if not home:
-            continue
-
-        home_sp = os.path.join(
-            home,
-            'Library',
-            'Python',
-            '{}.{}'.format(*sys.version_info),
-            'site-packages',
-        )
-        sitedirs.append(home_sp)
-    lib_paths = get_path('purelib'), get_path('platlib')
-
-    sitedirs.extend(s for s in lib_paths if s not in sitedirs)
-
-    if site.ENABLE_USER_SITE:
-        sitedirs.append(site.USER_SITE)
-
-    with contextlib.suppress(AttributeError):
-        sitedirs.extend(site.getsitepackages())
-
-    sitedirs = list(map(normalize_path, sitedirs))
-
-    return sitedirs
-
-
-def expand_paths(inputs):  # noqa: C901  # is too complex (11)  # FIXME
-    """Yield sys.path directories that might contain "old-style" packages"""
-
-    seen = {}
-
-    for dirname in inputs:
-        dirname = normalize_path(dirname)
-        if dirname in seen:
-            continue
-
-        seen[dirname] = 1
-        if not os.path.isdir(dirname):
-            continue
-
-        files = os.listdir(dirname)
-        yield dirname, files
-
-        for name in files:
-            if not name.endswith('.pth'):
-                # We only care about the .pth files
-                continue
-            if name in ('easy-install.pth', 'setuptools.pth'):
-                # Ignore .pth files that we control
-                continue
-
-            # Read the .pth file
-            f = open(os.path.join(dirname, name))
-            lines = list(yield_lines(f))
-            f.close()
-
-            # Yield existing non-dupe, non-import directory lines from it
-            for line in lines:
-                if line.startswith("import"):
-                    continue
-
-                line = normalize_path(line.rstrip())
-                if line in seen:
-                    continue
-
-                seen[line] = 1
-                if not os.path.isdir(line):
-                    continue
-
-                yield line, os.listdir(line)
-
-
-def extract_wininst_cfg(dist_filename):
-    """Extract configuration data from a bdist_wininst .exe
-
-    Returns a configparser.RawConfigParser, or None
-    """
-    f = open(dist_filename, 'rb')
-    try:
-        endrec = zipfile._EndRecData(f)
-        if endrec is None:
-            return None
-
-        prepended = (endrec[9] - endrec[5]) - endrec[6]
-        if prepended < 12:  # no wininst data here
-            return None
-        f.seek(prepended - 12)
-
-        tag, cfglen, bmlen = struct.unpack("egg path translations for a given .exe file"""
-
-    prefixes = [
-        ('PURELIB/', ''),
-        ('PLATLIB/pywin32_system32', ''),
-        ('PLATLIB/', ''),
-        ('SCRIPTS/', 'EGG-INFO/scripts/'),
-        ('DATA/lib/site-packages', ''),
-    ]
-    z = zipfile.ZipFile(exe_filename)
-    try:
-        for info in z.infolist():
-            name = info.filename
-            parts = name.split('/')
-            if len(parts) == 3 and parts[2] == 'PKG-INFO':
-                if parts[1].endswith('.egg-info'):
-                    prefixes.insert(0, ('/'.join(parts[:2]), 'EGG-INFO/'))
-                    break
-            if len(parts) != 2 or not name.endswith('.pth'):
-                continue
-            if name.endswith('-nspkg.pth'):
-                continue
-            if parts[0].upper() in ('PURELIB', 'PLATLIB'):
-                contents = z.read(name).decode()
-                for pth in yield_lines(contents):
-                    pth = pth.strip().replace('\\', '/')
-                    if not pth.startswith('import'):
-                        prefixes.append((('%s/%s/' % (parts[0], pth)), ''))
-    finally:
-        z.close()
-    prefixes = [(x.lower(), y) for x, y in prefixes]
-    prefixes.sort()
-    prefixes.reverse()
-    return prefixes
-
-
-class PthDistributions(Environment):
-    """A .pth file with Distribution paths in it"""
-
-    def __init__(self, filename, sitedirs=()):
-        self.filename = filename
-        self.sitedirs = list(map(normalize_path, sitedirs))
-        self.basedir = normalize_path(os.path.dirname(self.filename))
-        self.paths, self.dirty = self._load()
-        # keep a copy if someone manually updates the paths attribute on the instance
-        self._init_paths = self.paths[:]
-        super().__init__([], None, None)
-        for path in yield_lines(self.paths):
-            list(map(self.add, find_distributions(path, True)))
-
-    def _load_raw(self):
-        paths = []
-        dirty = saw_import = False
-        seen = dict.fromkeys(self.sitedirs)
-        f = open(self.filename, 'rt')
-        for line in f:
-            path = line.rstrip()
-            # still keep imports and empty/commented lines for formatting
-            paths.append(path)
-            if line.startswith(('import ', 'from ')):
-                saw_import = True
-                continue
-            stripped_path = path.strip()
-            if not stripped_path or stripped_path.startswith('#'):
-                continue
-            # skip non-existent paths, in case somebody deleted a package
-            # manually, and duplicate paths as well
-            normalized_path = normalize_path(os.path.join(self.basedir, path))
-            if normalized_path in seen or not os.path.exists(normalized_path):
-                log.debug("cleaned up dirty or duplicated %r", path)
-                dirty = True
-                paths.pop()
-                continue
-            seen[normalized_path] = 1
-        f.close()
-        # remove any trailing empty/blank line
-        while paths and not paths[-1].strip():
-            paths.pop()
-            dirty = True
-        return paths, dirty or (paths and saw_import)
-
-    def _load(self):
-        if os.path.isfile(self.filename):
-            return self._load_raw()
-        return [], False
-
-    def save(self):
-        """Write changed .pth file back to disk"""
-        # first reload the file
-        last_paths, last_dirty = self._load()
-        # and check that there are no difference with what we have.
-        # there can be difference if someone else has written to the file
-        # since we first loaded it.
-        # we don't want to lose the eventual new paths added since then.
-        for path in last_paths[:]:
-            if path not in self.paths:
-                self.paths.append(path)
-                log.info("detected new path %r", path)
-                last_dirty = True
-            else:
-                last_paths.remove(path)
-        # also, re-check that all paths are still valid before saving them
-        for path in self.paths[:]:
-            if path not in last_paths and not path.startswith(
-                ('import ', 'from ', '#')
-            ):
-                absolute_path = os.path.join(self.basedir, path)
-                if not os.path.exists(absolute_path):
-                    self.paths.remove(path)
-                    log.info("removing now non-existent path %r", path)
-                    last_dirty = True
-
-        self.dirty |= last_dirty or self.paths != self._init_paths
-        if not self.dirty:
-            return
-
-        rel_paths = list(map(self.make_relative, self.paths))
-        if rel_paths:
-            log.debug("Saving %s", self.filename)
-            lines = self._wrap_lines(rel_paths)
-            data = '\n'.join(lines) + '\n'
-            if os.path.islink(self.filename):
-                os.unlink(self.filename)
-            with open(self.filename, 'wt') as f:
-                f.write(data)
-        elif os.path.exists(self.filename):
-            log.debug("Deleting empty %s", self.filename)
-            os.unlink(self.filename)
-
-        self.dirty = False
-        self._init_paths[:] = self.paths[:]
-
-    @staticmethod
-    def _wrap_lines(lines):
-        return lines
-
-    def add(self, dist):
-        """Add `dist` to the distribution map"""
-        new_path = dist.location not in self.paths and (
-            dist.location not in self.sitedirs
-            or
-            # account for '.' being in PYTHONPATH
-            dist.location == os.getcwd()
-        )
-        if new_path:
-            self.paths.append(dist.location)
-            self.dirty = True
-        super().add(dist)
-
-    def remove(self, dist):
-        """Remove `dist` from the distribution map"""
-        while dist.location in self.paths:
-            self.paths.remove(dist.location)
-            self.dirty = True
-        super().remove(dist)
-
-    def make_relative(self, path):
-        npath, last = os.path.split(normalize_path(path))
-        baselen = len(self.basedir)
-        parts = [last]
-        sep = os.altsep == '/' and '/' or os.sep
-        while len(npath) >= baselen:
-            if npath == self.basedir:
-                parts.append(os.curdir)
-                parts.reverse()
-                return sep.join(parts)
-            npath, last = os.path.split(npath)
-            parts.append(last)
-        else:
-            return path
-
-
-class RewritePthDistributions(PthDistributions):
-    @classmethod
-    def _wrap_lines(cls, lines):
-        yield cls.prelude
-        for line in lines:
-            yield line
-        yield cls.postlude
-
-    prelude = _one_liner(
-        """
-        import sys
-        sys.__plen = len(sys.path)
-        """
-    )
-    postlude = _one_liner(
-        """
-        import sys
-        new = sys.path[sys.__plen:]
-        del sys.path[sys.__plen:]
-        p = getattr(sys, '__egginsert', 0)
-        sys.path[p:p] = new
-        sys.__egginsert = p + len(new)
-        """
-    )
-
-
-if os.environ.get('SETUPTOOLS_SYS_PATH_TECHNIQUE', 'raw') == 'rewrite':
-    PthDistributions = RewritePthDistributions
-
-
-def _first_line_re():
-    """
-    Return a regular expression based on first_line_re suitable for matching
-    strings.
-    """
-    if isinstance(first_line_re.pattern, str):
-        return first_line_re
-
-    # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
-    return re.compile(first_line_re.pattern.decode())
-
-
-def auto_chmod(func, arg, exc):
-    if func in [os.unlink, os.remove] and os.name == 'nt':
-        chmod(arg, stat.S_IWRITE)
-        return func(arg)
-    et, ev, _ = sys.exc_info()
-    # TODO: This code doesn't make sense. What is it trying to do?
-    raise (ev[0], ev[1] + (" %s %s" % (func, arg)))
-
-
-def update_dist_caches(dist_path, fix_zipimporter_caches):
-    """
-    Fix any globally cached `dist_path` related data
-
-    `dist_path` should be a path of a newly installed egg distribution (zipped
-    or unzipped).
-
-    sys.path_importer_cache contains finder objects that have been cached when
-    importing data from the original distribution. Any such finders need to be
-    cleared since the replacement distribution might be packaged differently,
-    e.g. a zipped egg distribution might get replaced with an unzipped egg
-    folder or vice versa. Having the old finders cached may then cause Python
-    to attempt loading modules from the replacement distribution using an
-    incorrect loader.
-
-    zipimport.zipimporter objects are Python loaders charged with importing
-    data packaged inside zip archives. If stale loaders referencing the
-    original distribution, are left behind, they can fail to load modules from
-    the replacement distribution. E.g. if an old zipimport.zipimporter instance
-    is used to load data from a new zipped egg archive, it may cause the
-    operation to attempt to locate the requested data in the wrong location -
-    one indicated by the original distribution's zip archive directory
-    information. Such an operation may then fail outright, e.g. report having
-    read a 'bad local file header', or even worse, it may fail silently &
-    return invalid data.
-
-    zipimport._zip_directory_cache contains cached zip archive directory
-    information for all existing zipimport.zipimporter instances and all such
-    instances connected to the same archive share the same cached directory
-    information.
-
-    If asked, and the underlying Python implementation allows it, we can fix
-    all existing zipimport.zipimporter instances instead of having to track
-    them down and remove them one by one, by updating their shared cached zip
-    archive directory information. This, of course, assumes that the
-    replacement distribution is packaged as a zipped egg.
-
-    If not asked to fix existing zipimport.zipimporter instances, we still do
-    our best to clear any remaining zipimport.zipimporter related cached data
-    that might somehow later get used when attempting to load data from the new
-    distribution and thus cause such load operations to fail. Note that when
-    tracking down such remaining stale data, we can not catch every conceivable
-    usage from here, and we clear only those that we know of and have found to
-    cause problems if left alive. Any remaining caches should be updated by
-    whomever is in charge of maintaining them, i.e. they should be ready to
-    handle us replacing their zip archives with new distributions at runtime.
-
-    """
-    # There are several other known sources of stale zipimport.zipimporter
-    # instances that we do not clear here, but might if ever given a reason to
-    # do so:
-    # * Global setuptools pkg_resources.working_set (a.k.a. 'master working
-    # set') may contain distributions which may in turn contain their
-    #   zipimport.zipimporter loaders.
-    # * Several zipimport.zipimporter loaders held by local variables further
-    #   up the function call stack when running the setuptools installation.
-    # * Already loaded modules may have their __loader__ attribute set to the
-    #   exact loader instance used when importing them. Python 3.4 docs state
-    #   that this information is intended mostly for introspection and so is
-    #   not expected to cause us problems.
-    normalized_path = normalize_path(dist_path)
-    _uncache(normalized_path, sys.path_importer_cache)
-    if fix_zipimporter_caches:
-        _replace_zip_directory_cache_data(normalized_path)
-    else:
-        # Here, even though we do not want to fix existing and now stale
-        # zipimporter cache information, we still want to remove it. Related to
-        # Python's zip archive directory information cache, we clear each of
-        # its stale entries in two phases:
-        #   1. Clear the entry so attempting to access zip archive information
-        #      via any existing stale zipimport.zipimporter instances fails.
-        #   2. Remove the entry from the cache so any newly constructed
-        #      zipimport.zipimporter instances do not end up using old stale
-        #      zip archive directory information.
-        # This whole stale data removal step does not seem strictly necessary,
-        # but has been left in because it was done before we started replacing
-        # the zip archive directory information cache content if possible, and
-        # there are no relevant unit tests that we can depend on to tell us if
-        # this is really needed.
-        _remove_and_clear_zip_directory_cache_data(normalized_path)
-
-
-def _collect_zipimporter_cache_entries(normalized_path, cache):
-    """
-    Return zipimporter cache entry keys related to a given normalized path.
-
-    Alternative path spellings (e.g. those using different character case or
-    those using alternative path separators) related to the same path are
-    included. Any sub-path entries are included as well, i.e. those
-    corresponding to zip archives embedded in other zip archives.
-
-    """
-    result = []
-    prefix_len = len(normalized_path)
-    for p in cache:
-        np = normalize_path(p)
-        if np.startswith(normalized_path) and np[prefix_len : prefix_len + 1] in (
-            os.sep,
-            '',
-        ):
-            result.append(p)
-    return result
-
-
-def _update_zipimporter_cache(normalized_path, cache, updater=None):
-    """
-    Update zipimporter cache data for a given normalized path.
-
-    Any sub-path entries are processed as well, i.e. those corresponding to zip
-    archives embedded in other zip archives.
-
-    Given updater is a callable taking a cache entry key and the original entry
-    (after already removing the entry from the cache), and expected to update
-    the entry and possibly return a new one to be inserted in its place.
-    Returning None indicates that the entry should not be replaced with a new
-    one. If no updater is given, the cache entries are simply removed without
-    any additional processing, the same as if the updater simply returned None.
-
-    """
-    for p in _collect_zipimporter_cache_entries(normalized_path, cache):
-        # N.B. pypy's custom zipimport._zip_directory_cache implementation does
-        # not support the complete dict interface:
-        # * Does not support item assignment, thus not allowing this function
-        #    to be used only for removing existing cache entries.
-        #  * Does not support the dict.pop() method, forcing us to use the
-        #    get/del patterns instead. For more detailed information see the
-        #    following links:
-        #      https://github.com/pypa/setuptools/issues/202#issuecomment-202913420
-        #      https://foss.heptapod.net/pypy/pypy/-/blob/144c4e65cb6accb8e592f3a7584ea38265d1873c/pypy/module/zipimport/interp_zipimport.py
-        old_entry = cache[p]
-        del cache[p]
-        new_entry = updater and updater(p, old_entry)
-        if new_entry is not None:
-            cache[p] = new_entry
-
-
-def _uncache(normalized_path, cache):
-    _update_zipimporter_cache(normalized_path, cache)
-
-
-def _remove_and_clear_zip_directory_cache_data(normalized_path):
-    def clear_and_remove_cached_zip_archive_directory_data(path, old_entry):
-        old_entry.clear()
-
-    _update_zipimporter_cache(
-        normalized_path,
-        zipimport._zip_directory_cache,
-        updater=clear_and_remove_cached_zip_archive_directory_data,
-    )
-
-
-# PyPy Python implementation does not allow directly writing to the
-# zipimport._zip_directory_cache and so prevents us from attempting to correct
-# its content. The best we can do there is clear the problematic cache content
-# and have PyPy repopulate it as needed. The downside is that if there are any
-# stale zipimport.zipimporter instances laying around, attempting to use them
-# will fail due to not having its zip archive directory information available
-# instead of being automatically corrected to use the new correct zip archive
-# directory information.
-if '__pypy__' in sys.builtin_module_names:
-    _replace_zip_directory_cache_data = _remove_and_clear_zip_directory_cache_data
-else:
-
-    def _replace_zip_directory_cache_data(normalized_path):
-        def replace_cached_zip_archive_directory_data(path, old_entry):
-            # N.B. In theory, we could load the zip directory information just
-            # once for all updated path spellings, and then copy it locally and
-            # update its contained path strings to contain the correct
-            # spelling, but that seems like a way too invasive move (this cache
-            # structure is not officially documented anywhere and could in
-            # theory change with new Python releases) for no significant
-            # benefit.
-            old_entry.clear()
-            zipimport.zipimporter(path)
-            old_entry.update(zipimport._zip_directory_cache[path])
-            return old_entry
-
-        _update_zipimporter_cache(
-            normalized_path,
-            zipimport._zip_directory_cache,
-            updater=replace_cached_zip_archive_directory_data,
-        )
-
-
-def is_python(text, filename=''):
-    "Is this string a valid Python script?"
-    try:
-        compile(text, filename, 'exec')
-    except (SyntaxError, TypeError):
-        return False
-    else:
-        return True
-
-
-def is_sh(executable):
-    """Determine if the specified executable is a .sh (contains a #! line)"""
-    try:
-        with io.open(executable, encoding='latin-1') as fp:
-            magic = fp.read(2)
-    except (OSError, IOError):
-        return executable
-    return magic == '#!'
-
-
-def nt_quote_arg(arg):
-    """Quote a command line argument according to Windows parsing rules"""
-    return subprocess.list2cmdline([arg])
-
-
-def is_python_script(script_text, filename):
-    """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc."""
-    if filename.endswith('.py') or filename.endswith('.pyw'):
-        return True  # extension says it's Python
-    if is_python(script_text, filename):
-        return True  # it's syntactically valid Python
-    if script_text.startswith('#!'):
-        # It begins with a '#!' line, so check if 'python' is in it somewhere
-        return 'python' in script_text.splitlines()[0].lower()
-
-    return False  # Not any Python I can recognize
-
-
-try:
-    from os import chmod as _chmod
-except ImportError:
-    # Jython compatibility
-    def _chmod(*args):
-        pass
-
-
-def chmod(path, mode):
-    log.debug("changing mode of %s to %o", path, mode)
-    try:
-        _chmod(path, mode)
-    except os.error as e:
-        log.debug("chmod failed: %s", e)
-
-
-class CommandSpec(list):
-    """
-    A command spec for a #! header, specified as a list of arguments akin to
-    those passed to Popen.
-    """
-
-    options = []
-    split_args = dict()
-
-    @classmethod
-    def best(cls):
-        """
-        Choose the best CommandSpec class based on environmental conditions.
-        """
-        return cls
-
-    @classmethod
-    def _sys_executable(cls):
-        _default = os.path.normpath(sys.executable)
-        return os.environ.get('__PYVENV_LAUNCHER__', _default)
-
-    @classmethod
-    def from_param(cls, param):
-        """
-        Construct a CommandSpec from a parameter to build_scripts, which may
-        be None.
-        """
-        if isinstance(param, cls):
-            return param
-        if isinstance(param, list):
-            return cls(param)
-        if param is None:
-            return cls.from_environment()
-        # otherwise, assume it's a string.
-        return cls.from_string(param)
-
-    @classmethod
-    def from_environment(cls):
-        return cls([cls._sys_executable()])
-
-    @classmethod
-    def from_string(cls, string):
-        """
-        Construct a command spec from a simple string representing a command
-        line parseable by shlex.split.
-        """
-        items = shlex.split(string, **cls.split_args)
-        return cls(items)
-
-    def install_options(self, script_text):
-        self.options = shlex.split(self._extract_options(script_text))
-        cmdline = subprocess.list2cmdline(self)
-        if not isascii(cmdline):
-            self.options[:0] = ['-x']
-
-    @staticmethod
-    def _extract_options(orig_script):
-        """
-        Extract any options from the first line of the script.
-        """
-        first = (orig_script + '\n').splitlines()[0]
-        match = _first_line_re().match(first)
-        options = match.group(1) or '' if match else ''
-        return options.strip()
-
-    def as_header(self):
-        return self._render(self + list(self.options))
-
-    @staticmethod
-    def _strip_quotes(item):
-        _QUOTES = '"\''
-        for q in _QUOTES:
-            if item.startswith(q) and item.endswith(q):
-                return item[1:-1]
-        return item
-
-    @staticmethod
-    def _render(items):
-        cmdline = subprocess.list2cmdline(
-            CommandSpec._strip_quotes(item.strip()) for item in items
-        )
-        return '#!' + cmdline + '\n'
-
-
-# For pbr compat; will be removed in a future version.
-sys_executable = CommandSpec._sys_executable()
-
-
-class WindowsCommandSpec(CommandSpec):
-    split_args = dict(posix=False)
-
-
-class ScriptWriter:
-    """
-    Encapsulates behavior around writing entry point scripts for console and
-    gui apps.
-    """
-
-    template = textwrap.dedent(
-        r"""
-        # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r
-        import re
-        import sys
-
-        # for compatibility with easy_install; see #2198
-        __requires__ = %(spec)r
-
-        try:
-            from importlib.metadata import distribution
-        except ImportError:
-            try:
-                from importlib_metadata import distribution
-            except ImportError:
-                from pkg_resources import load_entry_point
-
-
-        def importlib_load_entry_point(spec, group, name):
-            dist_name, _, _ = spec.partition('==')
-            matches = (
-                entry_point
-                for entry_point in distribution(dist_name).entry_points
-                if entry_point.group == group and entry_point.name == name
-            )
-            return next(matches).load()
-
-
-        globals().setdefault('load_entry_point', importlib_load_entry_point)
-
-
-        if __name__ == '__main__':
-            sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
-            sys.exit(load_entry_point(%(spec)r, %(group)r, %(name)r)())
-        """
-    ).lstrip()
-
-    command_spec_class = CommandSpec
-
-    @classmethod
-    def get_args(cls, dist, header=None):
-        """
-        Yield write_script() argument tuples for a distribution's
-        console_scripts and gui_scripts entry points.
-        """
-        if header is None:
-            header = cls.get_header()
-        spec = str(dist.as_requirement())
-        for type_ in 'console', 'gui':
-            group = type_ + '_scripts'
-            for name, ep in dist.get_entry_map(group).items():
-                cls._ensure_safe_name(name)
-                script_text = cls.template % locals()
-                args = cls._get_script_args(type_, name, header, script_text)
-                for res in args:
-                    yield res
-
-    @staticmethod
-    def _ensure_safe_name(name):
-        """
-        Prevent paths in *_scripts entry point names.
-        """
-        has_path_sep = re.search(r'[\\/]', name)
-        if has_path_sep:
-            raise ValueError("Path separators not allowed in script names")
-
-    @classmethod
-    def best(cls):
-        """
-        Select the best ScriptWriter for this environment.
-        """
-        if sys.platform == 'win32' or (os.name == 'java' and os._name == 'nt'):
-            return WindowsScriptWriter.best()
-        else:
-            return cls
-
-    @classmethod
-    def _get_script_args(cls, type_, name, header, script_text):
-        # Simply write the stub with no extension.
-        yield (name, header + script_text)
-
-    @classmethod
-    def get_header(cls, script_text="", executable=None):
-        """Create a #! line, getting options (if any) from script_text"""
-        cmd = cls.command_spec_class.best().from_param(executable)
-        cmd.install_options(script_text)
-        return cmd.as_header()
-
-
-class WindowsScriptWriter(ScriptWriter):
-    command_spec_class = WindowsCommandSpec
-
-    @classmethod
-    def best(cls):
-        """
-        Select the best ScriptWriter suitable for Windows
-        """
-        writer_lookup = dict(
-            executable=WindowsExecutableLauncherWriter,
-            natural=cls,
-        )
-        # for compatibility, use the executable launcher by default
-        launcher = os.environ.get('SETUPTOOLS_LAUNCHER', 'executable')
-        return writer_lookup[launcher]
-
-    @classmethod
-    def _get_script_args(cls, type_, name, header, script_text):
-        "For Windows, add a .py extension"
-        ext = dict(console='.pya', gui='.pyw')[type_]
-        if ext not in os.environ['PATHEXT'].lower().split(';'):
-            msg = (
-                "{ext} not listed in PATHEXT; scripts will not be "
-                "recognized as executables."
-            ).format(**locals())
-            SetuptoolsWarning.emit(msg)
-        old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe']
-        old.remove(ext)
-        header = cls._adjust_header(type_, header)
-        blockers = [name + x for x in old]
-        yield name + ext, header + script_text, 't', blockers
-
-    @classmethod
-    def _adjust_header(cls, type_, orig_header):
-        """
-        Make sure 'pythonw' is used for gui and 'python' is used for
-        console (regardless of what sys.executable is).
-        """
-        pattern = 'pythonw.exe'
-        repl = 'python.exe'
-        if type_ == 'gui':
-            pattern, repl = repl, pattern
-        pattern_ob = re.compile(re.escape(pattern), re.IGNORECASE)
-        new_header = pattern_ob.sub(string=orig_header, repl=repl)
-        return new_header if cls._use_header(new_header) else orig_header
-
-    @staticmethod
-    def _use_header(new_header):
-        """
-        Should _adjust_header use the replaced header?
-
-        On non-windows systems, always use. On
-        Windows systems, only use the replaced header if it resolves
-        to an executable on the system.
-        """
-        clean_header = new_header[2:-1].strip('"')
-        return sys.platform != 'win32' or find_executable(clean_header)
-
-
-class WindowsExecutableLauncherWriter(WindowsScriptWriter):
-    @classmethod
-    def _get_script_args(cls, type_, name, header, script_text):
-        """
-        For Windows, add a .py extension and an .exe launcher
-        """
-        if type_ == 'gui':
-            launcher_type = 'gui'
-            ext = '-script.pyw'
-            old = ['.pyw']
-        else:
-            launcher_type = 'cli'
-            ext = '-script.py'
-            old = ['.py', '.pyc', '.pyo']
-        hdr = cls._adjust_header(type_, header)
-        blockers = [name + x for x in old]
-        yield (name + ext, hdr + script_text, 't', blockers)
-        yield (
-            name + '.exe',
-            get_win_launcher(launcher_type),
-            'b',  # write in binary mode
-        )
-        if not is_64bit():
-            # install a manifest for the launcher to prevent Windows
-            # from detecting it as an installer (which it will for
-            #  launchers like easy_install.exe). Consider only
-            #  adding a manifest for launchers detected as installers.
-            #  See Distribute #143 for details.
-            m_name = name + '.exe.manifest'
-            yield (m_name, load_launcher_manifest(name), 't')
-
-
-def get_win_launcher(type):
-    """
-    Load the Windows launcher (executable) suitable for launching a script.
-
-    `type` should be either 'cli' or 'gui'
-
-    Returns the executable as a byte string.
-    """
-    launcher_fn = '%s.exe' % type
-    if is_64bit():
-        if get_platform() == "win-arm64":
-            launcher_fn = launcher_fn.replace(".", "-arm64.")
-        else:
-            launcher_fn = launcher_fn.replace(".", "-64.")
-    else:
-        launcher_fn = launcher_fn.replace(".", "-32.")
-    return resource_string('setuptools', launcher_fn)
-
-
-def load_launcher_manifest(name):
-    manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml')
-    return manifest.decode('utf-8') % vars()
-
-
-def _rmtree(path, ignore_errors=False, onexc=auto_chmod):
-    return py312compat.shutil_rmtree(path, ignore_errors, onexc)
-
-
-def current_umask():
-    tmp = os.umask(0o022)
-    os.umask(tmp)
-    return tmp
-
-
-def only_strs(values):
-    """
-    Exclude non-str values. Ref #3063.
-    """
-    return filter(lambda val: isinstance(val, str), values)
-
-
-class EasyInstallDeprecationWarning(SetuptoolsDeprecationWarning):
-    _SUMMARY = "easy_install command is deprecated."
-    _DETAILS = """
-    Please avoid running ``setup.py`` and ``easy_install``.
-    Instead, use pypa/build, pypa/installer or other
-    standards-based tools.
-    """
-    _SEE_URL = "https://github.com/pypa/setuptools/issues/917"
-    # _DUE_DATE not defined yet
+    return attr
diff --git a/setuptools/command/editable_wheel.py b/setuptools/command/editable_wheel.py
index 7f66f7e3e9..6f44f13643 100644
--- a/setuptools/command/editable_wheel.py
+++ b/setuptools/command/editable_wheel.py
@@ -10,59 +10,43 @@
    *auxiliary build directory* or ``auxiliary_dir``.
 """
 
-import logging
+from __future__ import annotations
+
 import io
+import logging
+import operator
 import os
 import shutil
-import sys
 import traceback
+from collections.abc import Iterable, Iterator, Mapping
 from contextlib import suppress
 from enum import Enum
 from inspect import cleandoc
-from itertools import chain
+from itertools import chain, starmap
 from pathlib import Path
 from tempfile import TemporaryDirectory
-from typing import (
-    TYPE_CHECKING,
-    Dict,
-    Iterable,
-    Iterator,
-    List,
-    Mapping,
-    Optional,
-    Tuple,
-    TypeVar,
-    Union,
-)
-
-from .. import (
-    Command,
-    _normalization,
-    _path,
-    errors,
-    namespaces,
-)
+from types import TracebackType
+from typing import TYPE_CHECKING, Protocol, TypeVar, cast
+
+from .. import Command, _normalization, _path, _shutil, errors, namespaces
+from .._path import StrPath
+from ..compat import py310, py312
 from ..discovery import find_package_path
 from ..dist import Distribution
-from ..warnings import (
-    InformationOnly,
-    SetuptoolsDeprecationWarning,
-    SetuptoolsWarning,
-)
+from ..warnings import InformationOnly, SetuptoolsDeprecationWarning
+from .build import build as build_cls
 from .build_py import build_py as build_py_cls
+from .dist_info import dist_info as dist_info_cls
+from .egg_info import egg_info as egg_info_cls
+from .install import install as install_cls
+from .install_scripts import install_scripts as install_scripts_cls
 
 if TYPE_CHECKING:
-    from wheel.wheelfile import WheelFile  # noqa
+    from typing_extensions import Self
 
-if sys.version_info >= (3, 8):
-    from typing import Protocol
-elif TYPE_CHECKING:
-    from typing_extensions import Protocol
-else:
-    from abc import ABC as Protocol
+    from .._vendor.wheel.wheelfile import WheelFile
 
-_Path = Union[str, Path]
-_P = TypeVar("_P", bound=_Path)
+_P = TypeVar("_P", bound=StrPath)
 _logger = logging.getLogger(__name__)
 
 
@@ -79,7 +63,7 @@ class _EditableMode(Enum):
     COMPAT = "compat"  # TODO: Remove `compat` after Dec/2022.
 
     @classmethod
-    def convert(cls, mode: Optional[str]) -> "_EditableMode":
+    def convert(cls, mode: str | None) -> _EditableMode:
         if not mode:
             return _EditableMode.LENIENT  # default
 
@@ -137,13 +121,13 @@ def initialize_options(self):
         self.project_dir = None
         self.mode = None
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         dist = self.distribution
         self.project_dir = dist.src_root or os.curdir
         self.package_dir = dist.package_dir or {}
         self.dist_dir = Path(self.dist_dir or os.path.join(self.project_dir, "dist"))
 
-    def run(self):
+    def run(self) -> None:
         try:
             self.dist_dir.mkdir(exist_ok=True)
             self._ensure_dist_info()
@@ -154,15 +138,19 @@ def run(self):
             bdist_wheel.write_wheelfile(self.dist_info_dir)
 
             self._create_wheel_file(bdist_wheel)
-        except Exception:
-            traceback.print_exc()
+        except Exception as ex:
             project = self.distribution.name or self.distribution.get_name()
-            _DebuggingTips.emit(project=project)
+            py310.add_note(
+                ex,
+                f"An error occurred when building editable wheel for {project}.\n"
+                "See debugging tips in: "
+                "https://setuptools.pypa.io/en/latest/userguide/development_mode.html#debugging-tips",
+            )
             raise
 
     def _ensure_dist_info(self):
         if self.dist_info_dir is None:
-            dist_info = self.reinitialize_command("dist_info")
+            dist_info = cast(dist_info_cls, self.reinitialize_command("dist_info"))
             dist_info.output_dir = self.dist_dir
             dist_info.ensure_finalized()
             dist_info.run()
@@ -181,13 +169,13 @@ def _install_namespaces(self, installation_dir, pth_prefix):
         installer = _NamespaceInstaller(dist, installation_dir, pth_prefix, src_root)
         installer.install_namespaces()
 
-    def _find_egg_info_dir(self) -> Optional[str]:
+    def _find_egg_info_dir(self) -> str | None:
         parent_dir = Path(self.dist_info_dir).parent if self.dist_info_dir else Path()
         candidates = map(str, parent_dir.glob("*.egg-info"))
         return next(candidates, None)
 
     def _configure_build(
-        self, name: str, unpacked_wheel: _Path, build_lib: _Path, tmp_dir: _Path
+        self, name: str, unpacked_wheel: StrPath, build_lib: StrPath, tmp_dir: StrPath
     ):
         """Configure commands to behave in the following ways:
 
@@ -209,12 +197,18 @@ def _configure_build(
         scripts = str(Path(unpacked_wheel, f"{name}.data", "scripts"))
 
         # egg-info may be generated again to create a manifest (used for package data)
-        egg_info = dist.reinitialize_command("egg_info", reinit_subcommands=True)
+        egg_info = cast(
+            egg_info_cls, dist.reinitialize_command("egg_info", reinit_subcommands=True)
+        )
         egg_info.egg_base = str(tmp_dir)
         egg_info.ignore_egg_info_in_manifest = True
 
-        build = dist.reinitialize_command("build", reinit_subcommands=True)
-        install = dist.reinitialize_command("install", reinit_subcommands=True)
+        build = cast(
+            build_cls, dist.reinitialize_command("build", reinit_subcommands=True)
+        )
+        install = cast(
+            install_cls, dist.reinitialize_command("install", reinit_subcommands=True)
+        )
 
         build.build_platlib = build.build_purelib = build.build_lib = build_lib
         install.install_purelib = install.install_platlib = install.install_lib = wheel
@@ -222,12 +216,19 @@ def _configure_build(
         install.install_headers = headers
         install.install_data = data
 
-        install_scripts = dist.get_command_obj("install_scripts")
+        # For portability, ensure scripts are built with #!python shebang
+        # pypa/setuptools#4863
+        build_scripts = dist.get_command_obj("build_scripts")
+        build_scripts.executable = 'python'
+
+        install_scripts = cast(
+            install_scripts_cls, dist.get_command_obj("install_scripts")
+        )
         install_scripts.no_ep = True
 
         build.build_temp = str(tmp_dir)
 
-        build_py = dist.get_command_obj("build_py")
+        build_py = cast(build_py_cls, dist.get_command_obj("build_py"))
         build_py.compile = False
         build_py.existing_egg_info_dir = self._find_egg_info_dir()
 
@@ -247,9 +248,9 @@ def _set_editable_mode(self):
             elif hasattr(cmd, "inplace"):
                 cmd.inplace = True  # backward compatibility with distutils
 
-    def _collect_build_outputs(self) -> Tuple[List[str], Dict[str, str]]:
-        files: List[str] = []
-        mapping: Dict[str, str] = {}
+    def _collect_build_outputs(self) -> tuple[list[str], dict[str, str]]:
+        files: list[str] = []
+        mapping: dict[str, str] = {}
         build = self.get_finalized_command("build")
 
         for cmd_name in build.get_sub_commands():
@@ -262,8 +263,12 @@ def _collect_build_outputs(self) -> Tuple[List[str], Dict[str, str]]:
         return files, mapping
 
     def _run_build_commands(
-        self, dist_name: str, unpacked_wheel: _Path, build_lib: _Path, tmp_dir: _Path
-    ) -> Tuple[List[str], Dict[str, str]]:
+        self,
+        dist_name: str,
+        unpacked_wheel: StrPath,
+        build_lib: StrPath,
+        tmp_dir: StrPath,
+    ) -> tuple[list[str], dict[str, str]]:
         self._configure_build(dist_name, unpacked_wheel, build_lib, tmp_dir)
         self._run_build_subcommands()
         files, mapping = self._collect_build_outputs()
@@ -272,7 +277,7 @@ def _run_build_commands(
         self._run_install("data")
         return files, mapping
 
-    def _run_build_subcommands(self):
+    def _run_build_subcommands(self) -> None:
         """
         Issue #3501 indicates that some plugins/customizations might rely on:
 
@@ -283,13 +288,13 @@ def _run_build_subcommands(self):
         This method implements a temporary workaround to support the ecosystem
         while the implementations catch up.
         """
-        # TODO: Once plugins/customisations had the chance to catch up, replace
+        # TODO: Once plugins/customizations had the chance to catch up, replace
         #       `self._run_build_subcommands()` with `self.run_command("build")`.
         #       Also remove _safely_run, TestCustomBuildPy. Suggested date: Aug/2023.
-        build: Command = self.get_finalized_command("build")
+        build = self.get_finalized_command("build")
         for name in build.get_sub_commands():
             cmd = self.get_finalized_command(name)
-            if name == "build_py" and type(cmd) != build_py_cls:
+            if name == "build_py" and type(cmd) is not build_py_cls:
                 self._safely_run(name)
             else:
                 self.run_command(name)
@@ -314,7 +319,7 @@ def _safely_run(self, cmd_name: str):
                 https://setuptools.pypa.io/en/latest/userguide/extension.html.
 
                 For the time being `setuptools` will silence this error and ignore
-                the faulty command, but this behaviour will change in future versions.
+                the faulty command, but this behavior will change in future versions.
                 """,
                 # TODO: define due_date
                 # There is a series of shortcomings with the available editable install
@@ -341,7 +346,7 @@ def _create_wheel_file(self, bdist_wheel):
         with unpacked_wheel as unpacked, build_lib as lib, build_tmp as tmp:
             unpacked_dist_info = Path(unpacked, Path(self.dist_info_dir).name)
             shutil.copytree(self.dist_info_dir, unpacked_dist_info)
-            self._install_namespaces(unpacked, dist_info.name)
+            self._install_namespaces(unpacked, dist_name)
             files, mapping = self._run_build_commands(dist_name, unpacked, lib, tmp)
             strategy = self._select_strategy(dist_name, tag, lib)
             with strategy, WheelFile(wheel_path, "w") as wheel_obj:
@@ -360,8 +365,8 @@ def _select_strategy(
         self,
         name: str,
         tag: str,
-        build_lib: _Path,
-    ) -> "EditableStrategy":
+        build_lib: StrPath,
+    ) -> EditableStrategy:
         """Decides which strategy to use to implement an editable installation."""
         build_name = f"__editable__.{name}-{tag}"
         project_dir = Path(self.project_dir)
@@ -384,28 +389,32 @@ def _select_strategy(
 
 
 class EditableStrategy(Protocol):
-    def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
-        ...
-
-    def __enter__(self):
-        ...
-
-    def __exit__(self, _exc_type, _exc_value, _traceback):
-        ...
+    def __call__(
+        self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]
+    ) -> object: ...
+    def __enter__(self) -> Self: ...
+    def __exit__(
+        self,
+        _exc_type: type[BaseException] | None,
+        _exc_value: BaseException | None,
+        _traceback: TracebackType | None,
+    ) -> object: ...
 
 
 class _StaticPth:
-    def __init__(self, dist: Distribution, name: str, path_entries: List[Path]):
+    def __init__(self, dist: Distribution, name: str, path_entries: list[Path]) -> None:
         self.dist = dist
         self.name = name
         self.path_entries = path_entries
 
-    def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
-        entries = "\n".join((str(p.resolve()) for p in self.path_entries))
+    def __call__(
+        self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]
+    ) -> None:
+        entries = "\n".join(str(p.resolve()) for p in self.path_entries)
         contents = _encode_pth(f"{entries}\n")
         wheel.writestr(f"__editable__.{self.name}.pth", contents)
 
-    def __enter__(self):
+    def __enter__(self) -> Self:
         msg = f"""
         Editable install will be performed using .pth file to extend `sys.path` with:
         {list(map(os.fspath, self.path_entries))!r}
@@ -413,8 +422,13 @@ def __enter__(self):
         _logger.warning(msg + _LENIENT_WARNING)
         return self
 
-    def __exit__(self, _exc_type, _exc_value, _traceback):
-        ...
+    def __exit__(
+        self,
+        _exc_type: object,
+        _exc_value: object,
+        _traceback: object,
+    ) -> None:
+        pass
 
 
 class _LinkTree(_StaticPth):
@@ -432,19 +446,21 @@ def __init__(
         self,
         dist: Distribution,
         name: str,
-        auxiliary_dir: _Path,
-        build_lib: _Path,
-    ):
+        auxiliary_dir: StrPath,
+        build_lib: StrPath,
+    ) -> None:
         self.auxiliary_dir = Path(auxiliary_dir)
         self.build_lib = Path(build_lib).resolve()
         self._file = dist.get_command_obj("build_py").copy_file
         super().__init__(dist, name, [self.auxiliary_dir])
 
-    def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
+    def __call__(
+        self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]
+    ) -> None:
         self._create_links(files, mapping)
         super().__call__(wheel, files, mapping)
 
-    def _normalize_output(self, file: str) -> Optional[str]:
+    def _normalize_output(self, file: str) -> str | None:
         # Files relative to build_lib will be normalized to None
         with suppress(ValueError):
             path = Path(file).resolve().relative_to(self.build_lib)
@@ -457,11 +473,12 @@ def _create_file(self, relative_output: str, src_file: str, link=None):
             dest.parent.mkdir(parents=True)
         self._file(src_file, dest, link=link)
 
-    def _create_links(self, outputs, output_mapping):
+    def _create_links(self, outputs, output_mapping: Mapping[str, str]):
         self.auxiliary_dir.mkdir(parents=True, exist_ok=True)
         link_type = "sym" if _can_symlink_files(self.auxiliary_dir) else "hard"
-        mappings = {self._normalize_output(k): v for k, v in output_mapping.items()}
-        mappings.pop(None, None)  # remove files that are not relative to build_lib
+        normalised = ((self._normalize_output(k), v) for k, v in output_mapping.items())
+        # remove files that are not relative to build_lib
+        mappings = {k: v for k, v in normalised if k is not None}
 
         for output in outputs:
             relative = self._normalize_output(output)
@@ -471,12 +488,17 @@ def _create_links(self, outputs, output_mapping):
         for relative, src in mappings.items():
             self._create_file(relative, src, link=link_type)
 
-    def __enter__(self):
+    def __enter__(self) -> Self:
         msg = "Strict editable install will be performed using a link tree.\n"
         _logger.warning(msg + _STRICT_WARNING)
         return self
 
-    def __exit__(self, _exc_type, _exc_value, _traceback):
+    def __exit__(
+        self,
+        _exc_type: object,
+        _exc_value: object,
+        _traceback: object,
+    ) -> None:
         msg = f"""\n
         Strict editable installation performed using the auxiliary directory:
             {self.auxiliary_dir}
@@ -488,37 +510,63 @@ def __exit__(self, _exc_type, _exc_value, _traceback):
 
 
 class _TopLevelFinder:
-    def __init__(self, dist: Distribution, name: str):
+    def __init__(self, dist: Distribution, name: str) -> None:
         self.dist = dist
         self.name = name
 
-    def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
+    def template_vars(self) -> tuple[str, str, dict[str, str], dict[str, list[str]]]:
         src_root = self.dist.src_root or os.curdir
         top_level = chain(_find_packages(self.dist), _find_top_level_modules(self.dist))
         package_dir = self.dist.package_dir or {}
         roots = _find_package_roots(top_level, package_dir, src_root)
 
-        namespaces_: Dict[str, List[str]] = dict(
+        namespaces_ = dict(
             chain(
                 _find_namespaces(self.dist.packages or [], roots),
                 ((ns, []) for ns in _find_virtual_namespaces(roots)),
             )
         )
 
+        legacy_namespaces = {
+            pkg: find_package_path(pkg, roots, self.dist.src_root or "")
+            for pkg in self.dist.namespace_packages or []
+        }
+
+        mapping = {**roots, **legacy_namespaces}
+        # ^-- We need to explicitly add the legacy_namespaces to the mapping to be
+        #     able to import their modules even if another package sharing the same
+        #     namespace is installed in a conventional (non-editable) way.
+
         name = f"__editable__.{self.name}.finder"
         finder = _normalization.safe_identifier(name)
-        content = bytes(_finder_template(name, roots, namespaces_), "utf-8")
-        wheel.writestr(f"{finder}.py", content)
+        return finder, name, mapping, namespaces_
+
+    def get_implementation(self) -> Iterator[tuple[str, bytes]]:
+        finder, name, mapping, namespaces_ = self.template_vars()
+
+        content = bytes(_finder_template(name, mapping, namespaces_), "utf-8")
+        yield (f"{finder}.py", content)
 
         content = _encode_pth(f"import {finder}; {finder}.install()")
-        wheel.writestr(f"__editable__.{self.name}.pth", content)
+        yield (f"__editable__.{self.name}.pth", content)
 
-    def __enter__(self):
+    def __call__(
+        self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]
+    ) -> None:
+        for file, content in self.get_implementation():
+            wheel.writestr(file, content)
+
+    def __enter__(self) -> Self:
         msg = "Editable install will be performed using a meta path finder.\n"
         _logger.warning(msg + _LENIENT_WARNING)
         return self
 
-    def __exit__(self, _exc_type, _exc_value, _traceback):
+    def __exit__(
+        self,
+        _exc_type: object,
+        _exc_value: object,
+        _traceback: object,
+    ) -> None:
         msg = """\n
         Please be careful with folders in your working directory with the same
         name as your package as they may take precedence during imports.
@@ -527,17 +575,20 @@ def __exit__(self, _exc_type, _exc_value, _traceback):
 
 
 def _encode_pth(content: str) -> bytes:
-    """.pth files are always read with 'locale' encoding, the recommendation
+    """
+    Prior to Python 3.13 (see https://github.com/python/cpython/issues/77102),
+    .pth files are always read with 'locale' encoding, the recommendation
     from the cpython core developers is to write them as ``open(path, "w")``
     and ignore warnings (see python/cpython#77102, pypa/setuptools#3937).
-    This function tries to simulate this behaviour without having to create an
+    This function tries to simulate this behavior without having to create an
     actual file, in a way that supports a range of active Python versions.
     (There seems to be some variety in the way different version of Python handle
-    ``encoding=None``, not all of them use ``locale.getpreferredencoding(False)``).
+    ``encoding=None``, not all of them use ``locale.getpreferredencoding(False)``
+    or ``locale.getencoding()``).
     """
-    encoding = "locale" if sys.version_info >= (3, 10) else None
     with io.BytesIO() as buffer:
-        wrapper = io.TextIOWrapper(buffer, encoding)
+        wrapper = io.TextIOWrapper(buffer, encoding=py312.PTH_ENCODING)
+        # TODO: Python 3.13 replace the whole function with `bytes(content, "utf-8")`
         wrapper.write(content)
         wrapper.flush()
         buffer.seek(0)
@@ -565,7 +616,7 @@ def _can_symlink_files(base_dir: Path) -> bool:
 
 
 def _simple_layout(
-    packages: Iterable[str], package_dir: Dict[str, str], project_dir: Path
+    packages: Iterable[str], package_dir: dict[str, str], project_dir: StrPath
 ) -> bool:
     """Return ``True`` if:
     - all packages are contained by the same parent directory, **and**
@@ -598,7 +649,7 @@ def _simple_layout(
     layout = {pkg: find_package_path(pkg, package_dir, project_dir) for pkg in packages}
     if not layout:
         return set(package_dir) in ({}, {""})
-    parent = os.path.commonpath([_parent_path(k, v) for k, v in layout.items()])
+    parent = os.path.commonpath(starmap(_parent_path, layout.items()))
     return all(
         _path.same_path(Path(parent, *key.split('.')), value)
         for key, value in layout.items()
@@ -615,7 +666,7 @@ def _parent_path(pkg, pkg_path):
     >>> _parent_path("b", "src/c")
     'src/c'
     """
-    parent = pkg_path[: -len(pkg)] if pkg_path.endswith(pkg) else pkg_path
+    parent = pkg_path.removesuffix(pkg)
     return parent.rstrip("/" + os.sep)
 
 
@@ -647,9 +698,9 @@ def _find_top_level_modules(dist: Distribution) -> Iterator[str]:
 def _find_package_roots(
     packages: Iterable[str],
     package_dir: Mapping[str, str],
-    src_root: _Path,
-) -> Dict[str, str]:
-    pkg_roots: Dict[str, str] = {
+    src_root: StrPath,
+) -> dict[str, str]:
+    pkg_roots: dict[str, str] = {
         pkg: _absolute_root(find_package_path(pkg, package_dir, src_root))
         for pkg in sorted(packages)
     }
@@ -657,7 +708,7 @@ def _find_package_roots(
     return _remove_nested(pkg_roots)
 
 
-def _absolute_root(path: _Path) -> str:
+def _absolute_root(path: StrPath) -> str:
     """Works for packages and top-level modules"""
     path_ = Path(path)
     parent = path_.parent
@@ -668,7 +719,7 @@ def _absolute_root(path: _Path) -> str:
         return str(parent.resolve() / path_.name)
 
 
-def _find_virtual_namespaces(pkg_roots: Dict[str, str]) -> Iterator[str]:
+def _find_virtual_namespaces(pkg_roots: dict[str, str]) -> Iterator[str]:
     """By carefully designing ``package_dir``, it is possible to implement the logical
     structure of PEP 420 in a package without the corresponding directories.
 
@@ -693,15 +744,15 @@ def _find_virtual_namespaces(pkg_roots: Dict[str, str]) -> Iterator[str]:
 
 
 def _find_namespaces(
-    packages: List[str], pkg_roots: Dict[str, str]
-) -> Iterator[Tuple[str, List[str]]]:
+    packages: list[str], pkg_roots: dict[str, str]
+) -> Iterator[tuple[str, list[str]]]:
     for pkg in packages:
         path = find_package_path(pkg, pkg_roots, "")
         if Path(path).exists() and not Path(path, "__init__.py").exists():
             yield (pkg, [path])
 
 
-def _remove_nested(pkg_roots: Dict[str, str]) -> Dict[str, str]:
+def _remove_nested(pkg_roots: dict[str, str]) -> dict[str, str]:
     output = dict(pkg_roots.copy())
 
     for pkg, path in reversed(list(pkg_roots.items())):
@@ -738,23 +789,22 @@ def _is_nested(pkg: str, pkg_path: str, parent: str, parent_path: str) -> bool:
 
 def _empty_dir(dir_: _P) -> _P:
     """Create a directory ensured to be empty. Existing files may be removed."""
-    shutil.rmtree(dir_, ignore_errors=True)
+    _shutil.rmtree(dir_, ignore_errors=True)
     os.makedirs(dir_)
     return dir_
 
 
 class _NamespaceInstaller(namespaces.Installer):
-    def __init__(self, distribution, installation_dir, editable_name, src_root):
+    def __init__(self, distribution, installation_dir, editable_name, src_root) -> None:
         self.distribution = distribution
         self.src_root = src_root
         self.installation_dir = installation_dir
         self.editable_name = editable_name
-        self.outputs = []
-        self.dry_run = False
+        self.outputs: list[str] = []
 
-    def _get_target(self):
+    def _get_nspkg_file(self):
         """Installation target."""
-        return os.path.join(self.installation_dir, self.editable_name)
+        return os.path.join(self.installation_dir, self.editable_name + self.nspkg_ext)
 
     def _get_root(self):
         """Where the modules/packages should be loaded from."""
@@ -762,6 +812,7 @@ def _get_root(self):
 
 
 _FINDER_TEMPLATE = """\
+from __future__ import annotations
 import sys
 from importlib.machinery import ModuleSpec, PathFinder
 from importlib.machinery import all_suffixes as module_suffixes
@@ -769,14 +820,14 @@ def _get_root(self):
 from itertools import chain
 from pathlib import Path
 
-MAPPING = {mapping!r}
-NAMESPACES = {namespaces!r}
+MAPPING: dict[str, str] = {mapping!r}
+NAMESPACES: dict[str, list[str]] = {namespaces!r}
 PATH_PLACEHOLDER = {name!r} + ".__path_hook__"
 
 
 class _EditableFinder:  # MetaPathFinder
     @classmethod
-    def find_spec(cls, fullname, path=None, target=None):
+    def find_spec(cls, fullname: str, path=None, target=None) -> ModuleSpec | None:  # type: ignore
         # Top-level packages and modules (we know these exist in the FS)
         if fullname in MAPPING:
             pkg_path = MAPPING[fullname]
@@ -794,28 +845,35 @@ def find_spec(cls, fullname, path=None, target=None):
         return None
 
     @classmethod
-    def _find_spec(cls, fullname, candidate_path):
+    def _find_spec(cls, fullname: str, candidate_path: Path) -> ModuleSpec | None:
         init = candidate_path / "__init__.py"
         candidates = (candidate_path.with_suffix(x) for x in module_suffixes())
         for candidate in chain([init], candidates):
             if candidate.exists():
                 return spec_from_file_location(fullname, candidate)
+        return None
 
 
 class _EditableNamespaceFinder:  # PathEntryFinder
     @classmethod
-    def _path_hook(cls, path):
+    def _path_hook(cls, path) -> type[_EditableNamespaceFinder]:
         if path == PATH_PLACEHOLDER:
             return cls
         raise ImportError
 
     @classmethod
-    def _paths(cls, fullname):
-        # Ensure __path__ is not empty for the spec to be considered a namespace.
-        return NAMESPACES[fullname] or MAPPING.get(fullname) or [PATH_PLACEHOLDER]
+    def _paths(cls, fullname: str) -> list[str]:
+        paths = NAMESPACES[fullname]
+        if not paths and fullname in MAPPING:
+            paths = [MAPPING[fullname]]
+        # Always add placeholder, for 2 reasons:
+        # 1. __path__ cannot be empty for the spec to be considered namespace.
+        # 2. In the case of nested namespaces, we need to force
+        #    import machinery to query _EditableNamespaceFinder again.
+        return [*paths, PATH_PLACEHOLDER]
 
     @classmethod
-    def find_spec(cls, fullname, target=None):
+    def find_spec(cls, fullname: str, target=None) -> ModuleSpec | None:  # type: ignore
         if fullname in NAMESPACES:
             spec = ModuleSpec(fullname, None, is_package=True)
             spec.submodule_search_locations = cls._paths(fullname)
@@ -823,7 +881,7 @@ def find_spec(cls, fullname, target=None):
         return None
 
     @classmethod
-    def find_module(cls, fullname):
+    def find_module(cls, _fullname) -> None:
         return None
 
 
@@ -843,40 +901,14 @@ def install():
 
 
 def _finder_template(
-    name: str, mapping: Mapping[str, str], namespaces: Dict[str, List[str]]
+    name: str, mapping: Mapping[str, str], namespaces: dict[str, list[str]]
 ) -> str:
     """Create a string containing the code for the``MetaPathFinder`` and
     ``PathEntryFinder``.
     """
-    mapping = dict(sorted(mapping.items(), key=lambda p: p[0]))
+    mapping = dict(sorted(mapping.items(), key=operator.itemgetter(0)))
     return _FINDER_TEMPLATE.format(name=name, mapping=mapping, namespaces=namespaces)
 
 
 class LinksNotSupported(errors.FileError):
     """File system does not seem to support either symlinks or hard links."""
-
-
-class _DebuggingTips(SetuptoolsWarning):
-    _SUMMARY = "Problem in editable installation."
-    _DETAILS = """
-    An error happened while installing `{project}` in editable mode.
-
-    The following steps are recommended to help debug this problem:
-
-    - Try to install the project normally, without using the editable mode.
-      Does the error still persist?
-      (If it does, try fixing the problem before attempting the editable mode).
-    - If you are using binary extensions, make sure you have all OS-level
-      dependencies installed (e.g. compilers, toolchains, binary libraries, ...).
-    - Try the latest version of setuptools (maybe the error was already fixed).
-    - If you (or your project dependencies) are using any setuptools extension
-      or customization, make sure they support the editable mode.
-
-    After following the steps above, if the problem still persists and
-    you think this is related to how setuptools handles editable installations,
-    please submit a reproducible example
-    (see https://stackoverflow.com/help/minimal-reproducible-example) to:
-
-        https://github.com/pypa/setuptools/issues
-    """
-    _SEE_DOCS = "userguide/development_mode.html"
diff --git a/setuptools/command/egg_info.py b/setuptools/command/egg_info.py
index a5199deb33..a5b5932702 100644
--- a/setuptools/command/egg_info.py
+++ b/setuptools/command/egg_info.py
@@ -2,36 +2,39 @@
 
 Create a distribution's .egg-info directory and contents"""
 
-from distutils.filelist import FileList as _FileList
-from distutils.errors import DistutilsInternalError
-from distutils.util import convert_path
-from distutils import log
-import distutils.errors
-import distutils.filelist
+from __future__ import annotations
+
 import functools
 import os
 import re
 import sys
 import time
-import collections
+from collections.abc import Callable
 
-from .._importlib import metadata
-from .. import _entry_points, _normalization
-from . import _requirestxt
+import packaging
+import packaging.requirements
+import packaging.version
 
+import setuptools.unicode_utils as unicode_utils
 from setuptools import Command
-from setuptools.command.sdist import sdist
-from setuptools.command.sdist import walk_revctrl
-from setuptools.command.setopt import edit_config
 from setuptools.command import bdist_egg
-import setuptools.unicode_utils as unicode_utils
+from setuptools.command.sdist import sdist, walk_revctrl
+from setuptools.command.setopt import edit_config
 from setuptools.glob import glob
 
-from setuptools.extern import packaging
+from .. import _entry_points, _normalization
+from .._importlib import metadata
 from ..warnings import SetuptoolsDeprecationWarning
+from . import _requirestxt
 
+import distutils.errors
+import distutils.filelist
+from distutils import log
+from distutils.errors import DistutilsInternalError
+from distutils.filelist import FileList as _FileList
+from distutils.util import convert_path
 
-PY_MAJOR = '{}.{}'.format(*sys.version_info)
+PY_MAJOR = f'{sys.version_info.major}.{sys.version_info.minor}'
 
 
 def translate_pattern(glob):  # noqa: C901  # is too complex (14)  # FIXME
@@ -47,7 +50,7 @@ def translate_pattern(glob):  # noqa: C901  # is too complex (14)  # FIXME
     chunks = glob.split(os.path.sep)
 
     sep = re.escape(os.sep)
-    valid_char = '[^%s]' % (sep,)
+    valid_char = f'[^{sep}]'
 
     for c, chunk in enumerate(chunks):
         last_chunk = c == len(chunks) - 1
@@ -59,7 +62,7 @@ def translate_pattern(glob):  # noqa: C901  # is too complex (14)  # FIXME
                 pat += '.*'
             else:
                 # Match '(name/)*'
-                pat += '(?:%s+%s)*' % (valid_char, sep)
+                pat += f'(?:{valid_char}+{sep})*'
             continue  # Break here as the whole path component has been handled
 
         # Find any special characters in the remainder
@@ -101,7 +104,7 @@ def translate_pattern(glob):  # noqa: C901  # is too complex (14)  # FIXME
                         inner = inner[1:]
 
                     char_class += re.escape(inner)
-                    pat += '[%s]' % (char_class,)
+                    pat += f'[{char_class}]'
 
                     # Skip to the end ]
                     i = inner_i
@@ -127,7 +130,7 @@ def name(self):
 
     def tagged_version(self):
         tagged = self._maybe_tag(self.distribution.get_version())
-        return _normalization.best_effort_version(tagged)
+        return _normalization.safe_version(tagged)
 
     def _maybe_tag(self, version):
         """
@@ -143,12 +146,15 @@ def _maybe_tag(self, version):
     def _already_tagged(self, version: str) -> bool:
         # Depending on their format, tags may change with version normalization.
         # So in addition the regular tags, we have to search for the normalized ones.
-        return version.endswith(self.vtags) or version.endswith(self._safe_tags())
+        return version.endswith((self.vtags, self._safe_tags()))
 
     def _safe_tags(self) -> str:
         # To implement this we can rely on `safe_version` pretending to be version 0
         # followed by tags. Then we simply discard the starting 0 (fake version number)
-        return _normalization.best_effort_version(f"0{self.vtags}")[1:]
+        try:
+            return _normalization.safe_version(f"0{self.vtags}")[1:]
+        except packaging.version.InvalidVersion:
+            return _normalization.safe_name(self.vtags.replace(' ', '.'))
 
     def tags(self) -> str:
         version = ''
@@ -169,7 +175,7 @@ class egg_info(InfoCommon, Command):
             'egg-base=',
             'e',
             "directory containing .egg-info directories"
-            " (default: top of the source tree)",
+            " [default: top of the source tree]",
         ),
         ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"),
         ('tag-build=', 'b', "Specify explicit tag to add to version number"),
@@ -192,29 +198,27 @@ def initialize_options(self):
     # allow the 'tag_svn_revision' to be detected and
     # set, supporting sdists built on older Setuptools.
     @property
-    def tag_svn_revision(self):
+    def tag_svn_revision(self) -> int | None:
         pass
 
     @tag_svn_revision.setter
-    def tag_svn_revision(self, value):
+    def tag_svn_revision(self, value) -> None:
         pass
 
     ####################################
 
-    def save_version_info(self, filename):
+    def save_version_info(self, filename) -> None:
         """
         Materialize the value of date into the
         build tag. Install build keys in a deterministic order
         to avoid arbitrary reordering on subsequent builds.
         """
-        egg_info = collections.OrderedDict()
         # follow the order these keys would have been added
         # when PYTHONHASHSEED=0
-        egg_info['tag_build'] = self.tags()
-        egg_info['tag_date'] = 0
+        egg_info = dict(tag_build=self.tags(), tag_date=0)
         edit_config(filename, dict(egg_info=egg_info))
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         # Note: we need to capture the current value returned
         # by `self.tagged_version()`, so we can later update
         # `self.distribution.metadata.version` without
@@ -229,8 +233,7 @@ def finalize_options(self):
             packaging.requirements.Requirement(spec % (self.egg_name, self.egg_version))
         except ValueError as e:
             raise distutils.errors.DistutilsOptionError(
-                "Invalid distribution name or version syntax: %s-%s"
-                % (self.egg_name, self.egg_version)
+                f"Invalid distribution name or version syntax: {self.egg_name}-{self.egg_version}"
             ) from e
 
         if self.egg_base is None:
@@ -247,22 +250,11 @@ def finalize_options(self):
         #
         self.distribution.metadata.version = self.egg_version
 
-        # If we bootstrapped around the lack of a PKG-INFO, as might be the
-        # case in a fresh checkout, make sure that any special tags get added
-        # to the version info
-        #
-        pd = self.distribution._patched_dist
-        key = getattr(pd, "key", None) or getattr(pd, "name", None)
-        if pd is not None and key == self.egg_name.lower():
-            pd._version = self.egg_version
-            pd._parsed_version = packaging.version.Version(self.egg_version)
-            self.distribution._patched_dist = None
-
     def _get_egg_basename(self, py_version=PY_MAJOR, platform=None):
         """Compute filename of the output egg. Private API."""
         return _egg_basename(self.egg_name, self.egg_version, py_version, platform)
 
-    def write_or_delete_file(self, what, filename, data, force=False):
+    def write_or_delete_file(self, what, filename, data, force: bool = False) -> None:
         """Write `data` to `filename` or delete if empty
 
         If `data` is non-empty, this routine is the same as ``write_file()``.
@@ -280,7 +272,7 @@ def write_or_delete_file(self, what, filename, data, force=False):
             else:
                 self.delete_file(filename)
 
-    def write_file(self, what, filename, data):
+    def write_file(self, what, filename, data) -> None:
         """Write `data` to `filename` (if not a dry run) after announcing it
 
         `what` is used in a log message to identify what is being written
@@ -288,25 +280,27 @@ def write_file(self, what, filename, data):
         """
         log.info("writing %s to %s", what, filename)
         data = data.encode("utf-8")
-        if not self.dry_run:
-            f = open(filename, 'wb')
-            f.write(data)
-            f.close()
+        f = open(filename, 'wb')
+        f.write(data)
+        f.close()
 
-    def delete_file(self, filename):
+    def delete_file(self, filename) -> None:
         """Delete `filename` (if not a dry run) after announcing it"""
         log.info("deleting %s", filename)
-        if not self.dry_run:
-            os.unlink(filename)
+        os.unlink(filename)
+
+    def run(self) -> None:
+        # Pre-load to avoid iterating over entry-points while an empty .egg-info
+        # exists in sys.path. See pypa/pyproject-hooks#206
+        writers = list(metadata.entry_points(group='egg_info.writers'))
 
-    def run(self):
         self.mkpath(self.egg_info)
         try:
             os.utime(self.egg_info, None)
         except OSError as e:
             msg = f"Cannot update time stamp of directory '{self.egg_info}'"
             raise distutils.errors.DistutilsFileError(msg) from e
-        for ep in metadata.entry_points(group='egg_info.writers'):
+        for ep in writers:
             writer = ep.load()
             writer(self, ep.name, os.path.join(self.egg_info, ep.name))
 
@@ -317,7 +311,7 @@ def run(self):
 
         self.find_sources()
 
-    def find_sources(self):
+    def find_sources(self) -> None:
         """Generate SOURCES.txt manifest file"""
         manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
         mm = manifest_maker(self.distribution)
@@ -330,11 +324,13 @@ def find_sources(self):
 class FileList(_FileList):
     # Implementations of the various MANIFEST.in commands
 
-    def __init__(self, warn=None, debug_print=None, ignore_egg_info_dir=False):
+    def __init__(
+        self, warn=None, debug_print=None, ignore_egg_info_dir: bool = False
+    ) -> None:
         super().__init__(warn, debug_print)
         self.ignore_egg_info_dir = ignore_egg_info_dir
 
-    def process_template_line(self, line):
+    def process_template_line(self, line) -> None:
         # Parse the line: split it up, make sure the right number of words
         # is there, and return the relevant words.  'action' is always
         # defined: it's the first word of the line.  Which of the other
@@ -342,7 +338,7 @@ def process_template_line(self, line):
         # patterns, (dir and patterns), or (dir_pattern).
         (action, patterns, dir, dir_pattern) = self._parse_template_line(line)
 
-        action_map = {
+        action_map: dict[str, Callable] = {
             'include': self.include,
             'exclude': self.exclude,
             'global-include': self.global_include,
@@ -360,16 +356,16 @@ def process_template_line(self, line):
         }
         log_map = {
             'include': "warning: no files found matching '%s'",
-            'exclude': ("warning: no previously-included files found " "matching '%s'"),
+            'exclude': ("warning: no previously-included files found matching '%s'"),
             'global-include': (
-                "warning: no files found matching '%s' " "anywhere in distribution"
+                "warning: no files found matching '%s' anywhere in distribution"
             ),
             'global-exclude': (
                 "warning: no previously-included files matching "
                 "'%s' found anywhere in distribution"
             ),
             'recursive-include': (
-                "warning: no files found matching '%s' " "under directory '%s'"
+                "warning: no files found matching '%s' under directory '%s'"
             ),
             'recursive-exclude': (
                 "warning: no previously-included files matching "
@@ -382,9 +378,8 @@ def process_template_line(self, line):
         try:
             process_action = action_map[action]
         except KeyError:
-            raise DistutilsInternalError(
-                "this cannot happen: invalid action '{action!s}'".format(action=action),
-            )
+            msg = f"Invalid MANIFEST.in: unknown action {action!r} in {line!r}"
+            raise DistutilsInternalError(msg) from None
 
         # OK, now we know that the action is valid and we have the
         # right number of words on the line for that action -- so we
@@ -479,15 +474,14 @@ def global_exclude(self, pattern):
         match = translate_pattern(os.path.join('**', pattern))
         return self._remove_files(match.match)
 
-    def append(self, item):
-        if item.endswith('\r'):  # Fix older sdists built on Windows
-            item = item[:-1]
+    def append(self, item) -> None:
+        item = item.removesuffix('\r')  # Fix older sdists built on Windows
         path = convert_path(item)
 
         if self._safe_path(path):
             self.files.append(path)
 
-    def extend(self, paths):
+    def extend(self, paths) -> None:
         self.files.extend(filter(self._safe_path, paths))
 
     def _repair(self):
@@ -506,7 +500,7 @@ def _safe_path(self, path):
         # To avoid accidental trans-codings errors, first to unicode
         u_path = unicode_utils.filesys_decode(path)
         if u_path is None:
-            log.warn("'%s' in unexpected encoding -- skipping" % path)
+            log.warn(f"'{path}' in unexpected encoding -- skipping")
             return False
 
         # Must ensure utf-8 encodability
@@ -531,17 +525,17 @@ def _safe_path(self, path):
 class manifest_maker(sdist):
     template = "MANIFEST.in"
 
-    def initialize_options(self):
-        self.use_defaults = 1
-        self.prune = 1
-        self.manifest_only = 1
-        self.force_manifest = 1
+    def initialize_options(self) -> None:
+        self.use_defaults = True
+        self.prune = True
+        self.manifest_only = True
+        self.force_manifest = True
         self.ignore_egg_info_dir = False
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         pass
 
-    def run(self):
+    def run(self) -> None:
         self.filelist = FileList(ignore_egg_info_dir=self.ignore_egg_info_dir)
         if not os.path.exists(self.manifest):
             self.write_manifest()  # it must exist so it'll get in the list
@@ -559,7 +553,7 @@ def _manifest_normalize(self, path):
         path = unicode_utils.filesys_decode(path)
         return path.replace(os.sep, '/')
 
-    def write_manifest(self):
+    def write_manifest(self) -> None:
         """
         Write the file list in 'self.filelist' to the manifest file
         named by 'self.manifest'.
@@ -568,10 +562,10 @@ def write_manifest(self):
 
         # Now _repairs should encodability, but not unicode
         files = [self._manifest_normalize(f) for f in self.filelist.files]
-        msg = "writing manifest file '%s'" % self.manifest
+        msg = f"writing manifest file '{self.manifest}'"
         self.execute(write_file, (self.manifest, files), msg)
 
-    def warn(self, msg):
+    def warn(self, msg) -> None:
         if not self._should_suppress_warning(msg):
             sdist.warn(self, msg)
 
@@ -582,7 +576,7 @@ def _should_suppress_warning(msg):
         """
         return re.match(r"standard file .*not found", msg)
 
-    def add_defaults(self):
+    def add_defaults(self) -> None:
         sdist.add_defaults(self)
         self.filelist.append(self.template)
         self.filelist.append(self.manifest)
@@ -600,7 +594,7 @@ def add_defaults(self):
         ei_cmd = self.get_finalized_command('egg_info')
         self.filelist.graft(ei_cmd.egg_info)
 
-    def add_license_files(self):
+    def add_license_files(self) -> None:
         license_files = self.distribution.metadata.license_files or []
         for lf in license_files:
             log.info("adding license file '%s'", lf)
@@ -614,16 +608,6 @@ def _add_referenced_files(self):
             log.debug("adding file referenced by config '%s'", rf)
         self.filelist.extend(referenced)
 
-    def prune_file_list(self):
-        build = self.get_finalized_command('build')
-        base_dir = self.distribution.get_fullname()
-        self.filelist.prune(build.build_base)
-        self.filelist.prune(base_dir)
-        sep = re.escape(os.sep)
-        self.filelist.exclude_pattern(
-            r'(^|' + sep + r')(RCS|CVS|\.svn)' + sep, is_regex=1
-        )
-
     def _safe_data_files(self, build_py):
         """
         The parent class implementation of this method
@@ -649,7 +633,7 @@ def _safe_data_files(self, build_py):
         return build_py.get_data_files()
 
 
-def write_file(filename, contents):
+def write_file(filename, contents) -> None:
     """Create a file with the specified name and write 'contents' (a
     sequence of strings without line terminators) to it.
     """
@@ -662,26 +646,23 @@ def write_file(filename, contents):
         f.write(contents)
 
 
-def write_pkg_info(cmd, basename, filename):
+def write_pkg_info(cmd, basename, filename) -> None:
     log.info("writing %s", filename)
-    if not cmd.dry_run:
-        metadata = cmd.distribution.metadata
-        metadata.version, oldver = cmd.egg_version, metadata.version
-        metadata.name, oldname = cmd.egg_name, metadata.name
+    metadata = cmd.distribution.metadata
+    metadata.version, oldver = cmd.egg_version, metadata.version
+    metadata.name, oldname = cmd.egg_name, metadata.name
 
-        try:
-            # write unescaped data to PKG-INFO, so older pkg_resources
-            # can still parse it
-            metadata.write_pkg_info(cmd.egg_info)
-        finally:
-            metadata.name, metadata.version = oldname, oldver
+    try:
+        metadata.write_pkg_info(cmd.egg_info)
+    finally:
+        metadata.name, metadata.version = oldname, oldver
 
-        safe = getattr(cmd.distribution, 'zip_safe', None)
+    safe = getattr(cmd.distribution, 'zip_safe', None)
 
-        bdist_egg.write_safety_flag(cmd.egg_info, safe)
+    bdist_egg.write_safety_flag(cmd.egg_info, safe)
 
 
-def warn_depends_obsolete(cmd, basename, filename):
+def warn_depends_obsolete(cmd, basename, filename) -> None:
     """
     Unused: left to avoid errors when updating (from source) from <= 67.8.
     Old installations have a .dist-info directory with the entry-point
@@ -696,18 +677,18 @@ def warn_depends_obsolete(cmd, basename, filename):
 write_setup_requirements = _requirestxt.write_setup_requirements
 
 
-def write_toplevel_names(cmd, basename, filename):
-    pkgs = dict.fromkeys(
-        [k.split('.', 1)[0] for k in cmd.distribution.iter_distribution_names()]
-    )
+def write_toplevel_names(cmd, basename, filename) -> None:
+    pkgs = dict.fromkeys([
+        k.split('.', 1)[0] for k in cmd.distribution.iter_distribution_names()
+    ])
     cmd.write_file("top-level names", filename, '\n'.join(sorted(pkgs)) + '\n')
 
 
-def overwrite_arg(cmd, basename, filename):
+def overwrite_arg(cmd, basename, filename) -> None:
     write_arg(cmd, basename, filename, True)
 
 
-def write_arg(cmd, basename, filename, force=False):
+def write_arg(cmd, basename, filename, force: bool = False) -> None:
     argname = os.path.splitext(basename)[0]
     value = getattr(cmd.distribution, argname, None)
     if value is not None:
@@ -715,7 +696,7 @@ def write_arg(cmd, basename, filename, force=False):
     cmd.write_or_delete_file(argname, filename, value, force)
 
 
-def write_entries(cmd, basename, filename):
+def write_entries(cmd, basename, filename) -> None:
     eps = _entry_points.load(cmd.distribution.entry_points)
     defn = _entry_points.render(eps)
     cmd.write_or_delete_file('entry points', filename, defn, True)
diff --git a/setuptools/command/install.py b/setuptools/command/install.py
index 606cce9d89..19ca601458 100644
--- a/setuptools/command/install.py
+++ b/setuptools/command/install.py
@@ -1,20 +1,39 @@
-from distutils.errors import DistutilsArgError
+from __future__ import annotations
+
 import inspect
-import glob
 import platform
-import distutils.command.install as orig
+from collections.abc import Callable
+from typing import TYPE_CHECKING, Any, ClassVar
 
-import setuptools
+from ..dist import Distribution
 from ..warnings import SetuptoolsDeprecationWarning, SetuptoolsWarning
 
-# Prior to numpy 1.9, NumPy relies on the '_install' name, so provide it for
-# now. See https://github.com/pypa/setuptools/issues/199/
-_install = orig.install
+import distutils.command.install as orig
+from distutils.errors import DistutilsArgError
+
+if TYPE_CHECKING:
+    # This is only used for a type-cast, don't import at runtime or it'll cause deprecation warnings
+    from .easy_install import easy_install as easy_install_cls
+else:
+    easy_install_cls = None
+
+
+def __getattr__(name: str):  # pragma: no cover
+    if name == "_install":
+        SetuptoolsDeprecationWarning.emit(
+            "`setuptools.command._install` was an internal implementation detail "
+            "that was left in for numpy<1.9 support.",
+            due_date=(2025, 5, 2),  # Originally added on 2024-11-01
+        )
+        return orig.install
+    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
 
 
 class install(orig.install):
     """Use easy_install to install the package, w/dependencies"""
 
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+
     user_options = orig.install.user_options + [
         ('old-and-unmanageable', None, "Try not to use this!"),
         (
@@ -27,7 +46,9 @@ class install(orig.install):
         'old-and-unmanageable',
         'single-version-externally-managed',
     ]
-    new_commands = [
+    # Type the same as distutils.command.install.install.sub_commands
+    # Must keep the second tuple item potentially None due to invariance
+    new_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] = [
         ('install_egg_info', lambda self: True),
         ('install_scripts', lambda self: True),
     ]
@@ -42,24 +63,21 @@ def initialize_options(self):
             standards-based tools.
             """,
             see_url="https://blog.ganssle.io/articles/2021/10/setup-py-deprecated.html",
-            # TODO: Document how to bootstrap setuptools without install
-            #       (e.g. by unziping the wheel file)
-            #       and then add a due_date to this warning.
+            due_date=(2025, 10, 31),
         )
 
-        orig.install.initialize_options(self)
+        super().initialize_options()
         self.old_and_unmanageable = None
         self.single_version_externally_managed = None
 
-    def finalize_options(self):
-        orig.install.finalize_options(self)
+    def finalize_options(self) -> None:
+        super().finalize_options()
         if self.root:
             self.single_version_externally_managed = True
         elif self.single_version_externally_managed:
             if not self.root and not self.record:
                 raise DistutilsArgError(
-                    "You must specify --record or --root when building system"
-                    " packages"
+                    "You must specify --record or --root when building system packages"
                 )
 
     def handle_extra_path(self):
@@ -71,17 +89,7 @@ def handle_extra_path(self):
         # command without --root or --single-version-externally-managed
         self.path_file = None
         self.extra_dirs = ''
-
-    def run(self):
-        # Explicit request for old-style install?  Just do it
-        if self.old_and_unmanageable or self.single_version_externally_managed:
-            return orig.install.run(self)
-
-        if not self._called_from_setup(inspect.currentframe()):
-            # Run in backward-compatibility mode to support bdist_* commands.
-            orig.install.run(self)
-        else:
-            self.do_egg_install()
+        return None
 
     @staticmethod
     def _called_from_setup(run_frame):
@@ -114,31 +122,7 @@ def _called_from_setup(run_frame):
 
             return caller_module == 'distutils.dist' and info.function == 'run_commands'
 
-    def do_egg_install(self):
-        easy_install = self.distribution.get_command_class('easy_install')
-
-        cmd = easy_install(
-            self.distribution,
-            args="x",
-            root=self.root,
-            record=self.record,
-        )
-        cmd.ensure_finalized()  # finalize before bdist_egg munges install cmd
-        cmd.always_copy_from = '.'  # make sure local-dir eggs get installed
-
-        # pick up setup-dir .egg files only: no .egg-info
-        cmd.package_index.scan(glob.glob('*.egg'))
-
-        self.run_command('bdist_egg')
-        args = [self.distribution.get_command_obj('bdist_egg').egg_output]
-
-        if setuptools.bootstrap_install_from:
-            # Bootstrap self-installation of setuptools
-            args.insert(0, setuptools.bootstrap_install_from)
-
-        cmd.args = args
-        cmd.run(show_deprecation=False)
-        setuptools.bootstrap_install_from = None
+        return False
 
 
 # XXX Python 3.1 doesn't see _nc if this is inside the class
diff --git a/setuptools/command/install_egg_info.py b/setuptools/command/install_egg_info.py
index a1d2e8184f..46138d2fd7 100644
--- a/setuptools/command/install_egg_info.py
+++ b/setuptools/command/install_egg_info.py
@@ -1,11 +1,12 @@
-from distutils import log, dir_util
 import os
 
-from setuptools import Command
-from setuptools import namespaces
+from setuptools import Command, namespaces
 from setuptools.archive_util import unpack_archive
+
 from .._path import ensure_directory
 
+from distutils import dir_util, log
+
 
 class install_egg_info(namespaces.Installer, Command):
     """Install an .egg-info directory for the package"""
@@ -19,29 +20,28 @@ class install_egg_info(namespaces.Installer, Command):
     def initialize_options(self):
         self.install_dir = None
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         self.set_undefined_options('install_lib', ('install_dir', 'install_dir'))
         ei_cmd = self.get_finalized_command("egg_info")
         basename = f"{ei_cmd._get_egg_basename()}.egg-info"
         self.source = ei_cmd.egg_info
         self.target = os.path.join(self.install_dir, basename)
-        self.outputs = []
+        self.outputs: list[str] = []
 
-    def run(self):
+    def run(self) -> None:
         self.run_command('egg_info')
         if os.path.isdir(self.target) and not os.path.islink(self.target):
-            dir_util.remove_tree(self.target, dry_run=self.dry_run)
+            dir_util.remove_tree(self.target)
         elif os.path.exists(self.target):
             self.execute(os.unlink, (self.target,), "Removing " + self.target)
-        if not self.dry_run:
-            ensure_directory(self.target)
-        self.execute(self.copytree, (), "Copying %s to %s" % (self.source, self.target))
+        ensure_directory(self.target)
+        self.execute(self.copytree, (), f"Copying {self.source} to {self.target}")
         self.install_namespaces()
 
     def get_outputs(self):
         return self.outputs
 
-    def copytree(self):
+    def copytree(self) -> None:
         # Copy the .egg-info tree to site-packages
         def skimmer(src, dst):
             # filter out source-control directories; note that 'src' is always
diff --git a/setuptools/command/install_lib.py b/setuptools/command/install_lib.py
index 32ff65e783..8e1e072710 100644
--- a/setuptools/command/install_lib.py
+++ b/setuptools/command/install_lib.py
@@ -1,13 +1,21 @@
+from __future__ import annotations
+
 import os
 import sys
 from itertools import product, starmap
+
+from .._path import StrPath
+from ..dist import Distribution
+
 import distutils.command.install_lib as orig
 
 
 class install_lib(orig.install_lib):
     """Don't add compiled flags to filenames of non-Python files"""
 
-    def run(self):
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+
+    def run(self) -> None:
         self.build()
         outfiles = self.install()
         if outfiles is not None:
@@ -44,7 +52,7 @@ def _all_packages(pkg_name):
         """
         while pkg_name:
             yield pkg_name
-            pkg_name, sep, child = pkg_name.rpartition('.')
+            pkg_name, _sep, _child = pkg_name.rpartition('.')
 
     def _get_SVEM_NSPs(self):
         """
@@ -85,14 +93,17 @@ def _gen_exclusion_paths():
 
     def copy_tree(
         self,
-        infile,
-        outfile,
-        preserve_mode=1,
-        preserve_times=1,
-        preserve_symlinks=0,
-        level=1,
-    ):
-        assert preserve_mode and preserve_times and not preserve_symlinks
+        infile: StrPath,
+        outfile: str,
+        # override: Using actual booleans
+        preserve_mode: bool = True,  # type: ignore[override]
+        preserve_times: bool = True,  # type: ignore[override]
+        preserve_symlinks: bool = False,  # type: ignore[override]
+        level: object = 1,
+    ) -> list[str]:
+        assert preserve_mode
+        assert preserve_times
+        assert not preserve_symlinks
         exclude = self.get_exclusions()
 
         if not exclude:
@@ -101,11 +112,12 @@ def copy_tree(
         # Exclude namespace package __init__.py* files from the output
 
         from setuptools.archive_util import unpack_directory
+
         from distutils import log
 
-        outfiles = []
+        outfiles: list[str] = []
 
-        def pf(src, dst):
+        def pf(src: str, dst: str):
             if dst in exclude:
                 log.warn("Skipping installation of %s (namespace package)", dst)
                 return False
diff --git a/setuptools/command/install_scripts.py b/setuptools/command/install_scripts.py
index 72b2e45cbc..5d7d3869ec 100644
--- a/setuptools/command/install_scripts.py
+++ b/setuptools/command/install_scripts.py
@@ -1,24 +1,30 @@
-from distutils import log
-import distutils.command.install_scripts as orig
+from __future__ import annotations
+
 import os
 import sys
 
 from .._path import ensure_directory
+from ..dist import Distribution
+
+import distutils.command.install_scripts as orig
+from distutils import log
 
 
 class install_scripts(orig.install_scripts):
     """Do normal script install, plus any egg_info wrapper scripts"""
 
-    def initialize_options(self):
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+
+    def initialize_options(self) -> None:
         orig.install_scripts.initialize_options(self)
         self.no_ep = False
 
-    def run(self):
+    def run(self) -> None:
         self.run_command("egg_info")
         if self.distribution.scripts:
             orig.install_scripts.run(self)  # run first to set up self.outfiles
         else:
-            self.outfiles = []
+            self.outfiles: list[str] = []
         if self.no_ep:
             # don't install entry point scripts into .egg file!
             return
@@ -26,19 +32,14 @@ def run(self):
 
     def _install_ep_scripts(self):
         # Delay import side-effects
-        from pkg_resources import Distribution, PathMetadata
-        from . import easy_install as ei
+        from .. import _scripts
+        from .._importlib import metadata
 
         ei_cmd = self.get_finalized_command("egg_info")
-        dist = Distribution(
-            ei_cmd.egg_base,
-            PathMetadata(ei_cmd.egg_base, ei_cmd.egg_info),
-            ei_cmd.egg_name,
-            ei_cmd.egg_version,
-        )
+        dist = metadata.Distribution.at(path=ei_cmd.egg_info)
         bs_cmd = self.get_finalized_command('build_scripts')
         exec_param = getattr(bs_cmd, 'executable', None)
-        writer = ei.ScriptWriter
+        writer = _scripts.ScriptWriter
         if exec_param == sys.executable:
             # In case the path to the Python executable contains a space, wrap
             # it so it's not split up.
@@ -49,18 +50,17 @@ def _install_ep_scripts(self):
         for args in writer.get_args(dist, cmd.as_header()):
             self.write_script(*args)
 
-    def write_script(self, script_name, contents, mode="t", *ignored):
+    def write_script(self, script_name, contents, mode: str = "t", *ignored) -> None:
         """Write an executable file to the scripts directory"""
-        from setuptools.command.easy_install import chmod, current_umask
+        from .._shutil import attempt_chmod_verbose as chmod, current_umask
 
         log.info("Installing %s script to %s", script_name, self.install_dir)
         target = os.path.join(self.install_dir, script_name)
         self.outfiles.append(target)
 
+        encoding = None if "b" in mode else "utf-8"
         mask = current_umask()
-        if not self.dry_run:
-            ensure_directory(target)
-            f = open(target, "w" + mode)
+        ensure_directory(target)
+        with open(target, "w" + mode, encoding=encoding) as f:
             f.write(contents)
-            f.close()
-            chmod(target, 0o777 - mask)
+        chmod(target, 0o777 - mask)
diff --git a/setuptools/command/register.py b/setuptools/command/register.py
deleted file mode 100644
index b8266b9a60..0000000000
--- a/setuptools/command/register.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from distutils import log
-import distutils.command.register as orig
-
-from setuptools.errors import RemovedCommandError
-
-
-class register(orig.register):
-    """Formerly used to register packages on PyPI."""
-
-    def run(self):
-        msg = (
-            "The register command has been removed, use twine to upload "
-            + "instead (https://pypi.org/p/twine)"
-        )
-
-        self.announce("ERROR: " + msg, log.ERROR)
-
-        raise RemovedCommandError(msg)
diff --git a/setuptools/command/rotate.py b/setuptools/command/rotate.py
index cfb78ce52d..9ff72f5600 100644
--- a/setuptools/command/rotate.py
+++ b/setuptools/command/rotate.py
@@ -1,10 +1,13 @@
-from distutils.util import convert_path
-from distutils import log
-from distutils.errors import DistutilsOptionError
+from __future__ import annotations
+
 import os
-import shutil
+from typing import ClassVar
 
-from setuptools import Command
+from .. import Command, _shutil
+
+from distutils import log
+from distutils.errors import DistutilsOptionError
+from distutils.util import convert_path
 
 
 class rotate(Command):
@@ -17,14 +20,14 @@ class rotate(Command):
         ('keep=', 'k', "number of matching distributions to keep"),
     ]
 
-    boolean_options = []
+    boolean_options: ClassVar[list[str]] = []
 
     def initialize_options(self):
         self.match = None
         self.dist_dir = None
         self.keep = None
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         if self.match is None:
             raise DistutilsOptionError(
                 "Must specify one or more (comma-separated) match patterns "
@@ -40,7 +43,7 @@ def finalize_options(self):
             self.match = [convert_path(p.strip()) for p in self.match.split(',')]
         self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
 
-    def run(self):
+    def run(self) -> None:
         self.run_command("egg_info")
         from glob import glob
 
@@ -55,8 +58,7 @@ def run(self):
             files = files[self.keep :]
             for t, f in files:
                 log.info("Deleting %s", f)
-                if not self.dry_run:
-                    if os.path.isdir(f):
-                        shutil.rmtree(f)
-                    else:
-                        os.unlink(f)
+                if os.path.isdir(f):
+                    _shutil.rmtree(f)
+                else:
+                    os.unlink(f)
diff --git a/setuptools/command/saveopts.py b/setuptools/command/saveopts.py
index f175de1015..76c3cdbf37 100644
--- a/setuptools/command/saveopts.py
+++ b/setuptools/command/saveopts.py
@@ -6,9 +6,9 @@ class saveopts(option_base):
 
     description = "save supplied options to setup.cfg or other config file"
 
-    def run(self):
+    def run(self) -> None:
         dist = self.distribution
-        settings = {}
+        settings: dict[str, dict[str, str]] = {}
 
         for cmd in dist.command_options:
             if cmd == 'saveopts':
@@ -18,4 +18,4 @@ def run(self):
                 if src == "command line":
                     settings.setdefault(cmd, {})[opt] = val
 
-        edit_config(self.filename, settings, self.dry_run)
+        edit_config(self.filename, settings)
diff --git a/setuptools/command/sdist.py b/setuptools/command/sdist.py
index c04823c159..17279ac421 100644
--- a/setuptools/command/sdist.py
+++ b/setuptools/command/sdist.py
@@ -1,22 +1,26 @@
-from distutils import log
-import distutils.command.sdist as orig
-import os
-import sys
-import io
+from __future__ import annotations
+
 import contextlib
+import os
+import re
+from collections.abc import Iterator
 from itertools import chain
+from typing import ClassVar
 
 from .._importlib import metadata
+from ..dist import Distribution
 from .build import _ORIGINAL_SUBCOMMANDS
 
+import distutils.command.sdist as orig
+from distutils import log
+
 _default_revctrl = list
 
 
-def walk_revctrl(dirname=''):
+def walk_revctrl(dirname='') -> Iterator:
     """Find all files under revision control"""
     for ep in metadata.entry_points(group='setuptools.file_finders'):
-        for item in ep.load()(dirname):
-            yield item
+        yield from ep.load()(dirname)
 
 
 class sdist(orig.sdist):
@@ -27,12 +31,12 @@ class sdist(orig.sdist):
         (
             'keep-temp',
             'k',
-            "keep the distribution tree around after creating " + "archive file(s)",
+            "keep the distribution tree around after creating archive file(s)",
         ),
         (
             'dist-dir=',
             'd',
-            "directory to put the source distribution archive(s) in " "[default: dist]",
+            "directory to put the source distribution archive(s) in [default: dist]",
         ),
         (
             'owner=',
@@ -46,12 +50,13 @@ class sdist(orig.sdist):
         ),
     ]
 
-    negative_opt = {}
+    distribution: Distribution  # override distutils.dist.Distribution with setuptools.dist.Distribution
+    negative_opt: ClassVar[dict[str, str]] = {}
 
     README_EXTENSIONS = ['', '.rst', '.txt', '.md']
-    READMES = tuple('README{0}'.format(ext) for ext in README_EXTENSIONS)
+    READMES = tuple(f'README{ext}' for ext in README_EXTENSIONS)
 
-    def run(self):
+    def run(self) -> None:
         self.run_command('egg_info')
         ei_cmd = self.get_finalized_command('egg_info')
         self.filelist = ei_cmd.filelist
@@ -70,18 +75,10 @@ def run(self):
             if data not in dist_files:
                 dist_files.append(data)
 
-    def initialize_options(self):
+    def initialize_options(self) -> None:
         orig.sdist.initialize_options(self)
 
-        self._default_to_gztar()
-
-    def _default_to_gztar(self):
-        # only needed on Python prior to 3.6.
-        if sys.version_info >= (3, 6, 0, 'beta', 1):
-            return
-        self.formats = ['gztar']
-
-    def make_distribution(self):
+    def make_distribution(self) -> None:
         """
         Workaround for #516
         """
@@ -107,9 +104,9 @@ class NoValue:
             yield
         finally:
             if orig_val is not NoValue:
-                setattr(os, 'link', orig_val)
+                os.link = orig_val
 
-    def add_defaults(self):
+    def add_defaults(self) -> None:
         super().add_defaults()
         self._add_defaults_build_sub_commands()
 
@@ -162,7 +159,13 @@ def _add_defaults_data_files(self):
         except TypeError:
             log.warn("data_files contains unexpected objects")
 
-    def check_readme(self):
+    def prune_file_list(self) -> None:
+        super().prune_file_list()
+        # Prevent accidental inclusion of test-related cache dirs at the project root
+        sep = re.escape(os.sep)
+        self.filelist.exclude_pattern(r"^(\.tox|\.nox|\.venv)" + sep, is_regex=True)
+
+    def check_readme(self) -> None:
         for f in self.READMES:
             if os.path.exists(f):
                 return
@@ -171,7 +174,7 @@ def check_readme(self):
                 "standard file not found: should have one of " + ', '.join(self.READMES)
             )
 
-    def make_release_tree(self, base_dir, files):
+    def make_release_tree(self, base_dir, files) -> None:
         orig.sdist.make_release_tree(self, base_dir, files)
 
         # Save any egg_info command line options used to create this sdist
@@ -189,23 +192,23 @@ def _manifest_is_not_generated(self):
         if not os.path.isfile(self.manifest):
             return False
 
-        with io.open(self.manifest, 'rb') as fp:
+        with open(self.manifest, 'rb') as fp:
             first_line = fp.readline()
-        return first_line != '# file GENERATED by distutils, do NOT edit\n'.encode()
+        return first_line != b'# file GENERATED by distutils, do NOT edit\n'
 
-    def read_manifest(self):
+    def read_manifest(self) -> None:
         """Read the manifest file (named by 'self.manifest') and use it to
         fill in 'self.filelist', the list of files to include in the source
         distribution.
         """
         log.info("reading manifest file '%s'", self.manifest)
         manifest = open(self.manifest, 'rb')
-        for line in manifest:
+        for bytes_line in manifest:
             # The manifest must contain UTF-8. See #303.
             try:
-                line = line.decode('UTF-8')
+                line = bytes_line.decode('UTF-8')
             except UnicodeDecodeError:
-                log.warn("%r not UTF-8 decodable -- skipping" % line)
+                log.warn(f"{line!r} not UTF-8 decodable -- skipping")
                 continue
             # ignore comments and blank lines
             line = line.strip()
diff --git a/setuptools/command/setopt.py b/setuptools/command/setopt.py
index f9a6075128..349041ecb6 100644
--- a/setuptools/command/setopt.py
+++ b/setuptools/command/setopt.py
@@ -1,11 +1,13 @@
-from distutils.util import convert_path
-from distutils import log
-from distutils.errors import DistutilsOptionError
-import distutils
-import os
 import configparser
+import os
 
-from setuptools import Command
+from .. import Command
+from ..unicode_utils import _cfg_read_utf8_with_fallback
+
+import distutils
+from distutils import log
+from distutils.errors import DistutilsOptionError
+from distutils.util import convert_path
 
 __all__ = ['config_file', 'edit_config', 'option_base', 'setopt']
 
@@ -21,11 +23,11 @@ def config_file(kind="local"):
         return os.path.join(os.path.dirname(distutils.__file__), 'distutils.cfg')
     if kind == 'user':
         dot = os.name == 'posix' and '.' or ''
-        return os.path.expanduser(convert_path("~/%spydistutils.cfg" % dot))
+        return os.path.expanduser(convert_path(f"~/{dot}pydistutils.cfg"))
     raise ValueError("config_file() type must be 'local', 'global', or 'user'", kind)
 
 
-def edit_config(filename, settings, dry_run=False):
+def edit_config(filename, settings) -> None:
     """Edit a configuration file to include `settings`
 
     `settings` is a dictionary of dictionaries or ``None`` values, keyed by
@@ -35,8 +37,9 @@ def edit_config(filename, settings, dry_run=False):
     """
     log.debug("Reading configuration from %s", filename)
     opts = configparser.RawConfigParser()
-    opts.optionxform = lambda x: x
-    opts.read([filename])
+    opts.optionxform = lambda optionstr: optionstr  # type: ignore[method-assign] # overriding method
+    _cfg_read_utf8_with_fallback(opts, filename)
+
     for section, options in settings.items():
         if options is None:
             log.info("Deleting section [%s] from %s", section, filename)
@@ -61,9 +64,8 @@ def edit_config(filename, settings, dry_run=False):
                     opts.set(section, option, value)
 
     log.info("Writing %s", filename)
-    if not dry_run:
-        with open(filename, 'w') as f:
-            opts.write(f)
+    with open(filename, 'w', encoding="utf-8") as f:
+        opts.write(f)
 
 
 class option_base(Command):
@@ -85,7 +87,7 @@ def initialize_options(self):
         self.user_config = None
         self.filename = None
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         filenames = []
         if self.global_config:
             filenames.append(config_file('global'))
@@ -123,16 +125,15 @@ def initialize_options(self):
         self.set_value = None
         self.remove = None
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         option_base.finalize_options(self)
         if self.command is None or self.option is None:
             raise DistutilsOptionError("Must specify --command *and* --option")
         if self.set_value is None and not self.remove:
             raise DistutilsOptionError("Must specify --set-value or --remove")
 
-    def run(self):
+    def run(self) -> None:
         edit_config(
             self.filename,
             {self.command: {self.option.replace('-', '_'): self.set_value}},
-            self.dry_run,
         )
diff --git a/setuptools/command/test.py b/setuptools/command/test.py
index 5fce6660c0..5d03c91102 100644
--- a/setuptools/command/test.py
+++ b/setuptools/command/test.py
@@ -1,82 +1,31 @@
-import os
-import operator
-import sys
-import contextlib
-import itertools
-import unittest
-from distutils.errors import DistutilsError, DistutilsOptionError
-from distutils import log
-from unittest import TestLoader
+from __future__ import annotations
 
-from pkg_resources import (
-    resource_listdir,
-    resource_exists,
-    normalize_path,
-    working_set,
-    evaluate_marker,
-    add_activation_listener,
-    require,
-)
-from .._importlib import metadata
-from setuptools import Command
-from setuptools.extern.more_itertools import unique_everseen
-from setuptools.extern.jaraco.functools import pass_none
-
-
-class ScanningLoader(TestLoader):
-    def __init__(self):
-        TestLoader.__init__(self)
-        self._visited = set()
-
-    def loadTestsFromModule(self, module, pattern=None):
-        """Return a suite of all tests cases contained in the given module
-
-        If the module is a package, load tests from all the modules in it.
-        If the module has an ``additional_tests`` function, call it and add
-        the return value to the tests.
-        """
-        if module in self._visited:
-            return None
-        self._visited.add(module)
-
-        tests = []
-        tests.append(TestLoader.loadTestsFromModule(self, module))
-
-        if hasattr(module, "additional_tests"):
-            tests.append(module.additional_tests())
-
-        if hasattr(module, '__path__'):
-            for file in resource_listdir(module.__name__, ''):
-                if file.endswith('.py') and file != '__init__.py':
-                    submodule = module.__name__ + '.' + file[:-3]
-                else:
-                    if resource_exists(module.__name__, file + '/__init__.py'):
-                        submodule = module.__name__ + '.' + file
-                    else:
-                        continue
-                tests.append(self.loadTestsFromName(submodule))
-
-        if len(tests) != 1:
-            return self.suiteClass(tests)
-        else:
-            return tests[0]  # don't create a nested suite for only one return
+from typing import NoReturn
 
-
-# adapted from jaraco.classes.properties:NonDataProperty
-class NonDataProperty:
-    def __init__(self, fget):
-        self.fget = fget
-
-    def __get__(self, obj, objtype=None):
-        if obj is None:
-            return self
-        return self.fget(obj)
+from setuptools import Command
+from setuptools.warnings import SetuptoolsDeprecationWarning
+
+
+# Would restrict to Literal["test"], but mypy doesn't support it: https://github.com/python/mypy/issues/8203
+def __getattr__(name: str) -> type[_test]:
+    if name == 'test':
+        SetuptoolsDeprecationWarning.emit(
+            "The test command is disabled and references to it are deprecated.",
+            "Please remove any references to `setuptools.command.test` in all "
+            "supported versions of the affected package.",
+            due_date=(2024, 11, 15),
+            stacklevel=2,
+        )
+        return _test
+    raise AttributeError(name)
 
 
-class test(Command):
-    """Command to run unit tests after in-place build"""
+class _test(Command):
+    """
+    Stub to warn when test command is referenced or used.
+    """
 
-    description = "run unit tests after in-place build (deprecated)"
+    description = "stub for old test command (do not use)"
 
     user_options = [
         ('test-module=', 'm', "Run 'test_suite' in specified module"),
@@ -88,163 +37,11 @@ class test(Command):
         ('test-runner=', 'r', "Test runner to use"),
     ]
 
-    def initialize_options(self):
-        self.test_suite = None
-        self.test_module = None
-        self.test_loader = None
-        self.test_runner = None
-
-    def finalize_options(self):
-        if self.test_suite and self.test_module:
-            msg = "You may specify a module or a suite, but not both"
-            raise DistutilsOptionError(msg)
-
-        if self.test_suite is None:
-            if self.test_module is None:
-                self.test_suite = self.distribution.test_suite
-            else:
-                self.test_suite = self.test_module + ".test_suite"
-
-        if self.test_loader is None:
-            self.test_loader = getattr(self.distribution, 'test_loader', None)
-        if self.test_loader is None:
-            self.test_loader = "setuptools.command.test:ScanningLoader"
-        if self.test_runner is None:
-            self.test_runner = getattr(self.distribution, 'test_runner', None)
-
-    @NonDataProperty
-    def test_args(self):
-        return list(self._test_args())
-
-    def _test_args(self):
-        if not self.test_suite:
-            yield 'discover'
-        if self.verbose:
-            yield '--verbose'
-        if self.test_suite:
-            yield self.test_suite
-
-    def with_project_on_sys_path(self, func):
-        """
-        Backward compatibility for project_on_sys_path context.
-        """
-        with self.project_on_sys_path():
-            func()
-
-    @contextlib.contextmanager
-    def project_on_sys_path(self, include_dists=[]):
-        self.run_command('egg_info')
-
-        # Build extensions in-place
-        self.reinitialize_command('build_ext', inplace=1)
-        self.run_command('build_ext')
-
-        ei_cmd = self.get_finalized_command("egg_info")
-
-        old_path = sys.path[:]
-        old_modules = sys.modules.copy()
-
-        try:
-            project_path = normalize_path(ei_cmd.egg_base)
-            sys.path.insert(0, project_path)
-            working_set.__init__()
-            add_activation_listener(lambda dist: dist.activate())
-            require('%s==%s' % (ei_cmd.egg_name, ei_cmd.egg_version))
-            with self.paths_on_pythonpath([project_path]):
-                yield
-        finally:
-            sys.path[:] = old_path
-            sys.modules.clear()
-            sys.modules.update(old_modules)
-            working_set.__init__()
-
-    @staticmethod
-    @contextlib.contextmanager
-    def paths_on_pythonpath(paths):
-        """
-        Add the indicated paths to the head of the PYTHONPATH environment
-        variable so that subprocesses will also see the packages at
-        these paths.
-
-        Do this in a context that restores the value on exit.
-        """
-        nothing = object()
-        orig_pythonpath = os.environ.get('PYTHONPATH', nothing)
-        current_pythonpath = os.environ.get('PYTHONPATH', '')
-        try:
-            prefix = os.pathsep.join(unique_everseen(paths))
-            to_join = filter(None, [prefix, current_pythonpath])
-            new_path = os.pathsep.join(to_join)
-            if new_path:
-                os.environ['PYTHONPATH'] = new_path
-            yield
-        finally:
-            if orig_pythonpath is nothing:
-                os.environ.pop('PYTHONPATH', None)
-            else:
-                os.environ['PYTHONPATH'] = orig_pythonpath
-
-    @staticmethod
-    def install_dists(dist):
-        """
-        Install the requirements indicated by self.distribution and
-        return an iterable of the dists that were built.
-        """
-        ir_d = dist.fetch_build_eggs(dist.install_requires)
-        tr_d = dist.fetch_build_eggs(dist.tests_require or [])
-        er_d = dist.fetch_build_eggs(
-            v
-            for k, v in dist.extras_require.items()
-            if k.startswith(':') and evaluate_marker(k[1:])
-        )
-        return itertools.chain(ir_d, tr_d, er_d)
-
-    def run(self):
-        self.announce(
-            "WARNING: Testing via this command is deprecated and will be "
-            "removed in a future version. Users looking for a generic test "
-            "entry point independent of test runner are encouraged to use "
-            "tox.",
-            log.WARN,
-        )
-
-        installed_dists = self.install_dists(self.distribution)
-
-        cmd = ' '.join(self._argv)
-        if self.dry_run:
-            self.announce('skipping "%s" (dry run)' % cmd)
-            return
-
-        self.announce('running "%s"' % cmd)
-
-        paths = map(operator.attrgetter('location'), installed_dists)
-        with self.paths_on_pythonpath(paths):
-            with self.project_on_sys_path():
-                self.run_tests()
-
-    def run_tests(self):
-        test = unittest.main(
-            None,
-            None,
-            self._argv,
-            testLoader=self._resolve_as_ep(self.test_loader),
-            testRunner=self._resolve_as_ep(self.test_runner),
-            exit=False,
-        )
-        if not test.result.wasSuccessful():
-            msg = 'Test failed: %s' % test.result
-            self.announce(msg, log.ERROR)
-            raise DistutilsError(msg)
+    def initialize_options(self) -> None:
+        pass
 
-    @property
-    def _argv(self):
-        return ['unittest'] + self.test_args
+    def finalize_options(self) -> None:
+        pass
 
-    @staticmethod
-    @pass_none
-    def _resolve_as_ep(val):
-        """
-        Load the indicated attribute value, called, as a as if it were
-        specified as an entry point.
-        """
-        return metadata.EntryPoint(value=val, name=None, group=None).load()()
+    def run(self) -> NoReturn:
+        raise RuntimeError("Support for the test command was removed in Setuptools 72")
diff --git a/setuptools/command/upload.py b/setuptools/command/upload.py
deleted file mode 100644
index ec7f81e227..0000000000
--- a/setuptools/command/upload.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from distutils import log
-from distutils.command import upload as orig
-
-from setuptools.errors import RemovedCommandError
-
-
-class upload(orig.upload):
-    """Formerly used to upload packages to PyPI."""
-
-    def run(self):
-        msg = (
-            "The upload command has been removed, use twine to upload "
-            + "instead (https://pypi.org/p/twine)"
-        )
-
-        self.announce("ERROR: " + msg, log.ERROR)
-        raise RemovedCommandError(msg)
diff --git a/setuptools/command/upload_docs.py b/setuptools/command/upload_docs.py
deleted file mode 100644
index 27c98b7c30..0000000000
--- a/setuptools/command/upload_docs.py
+++ /dev/null
@@ -1,222 +0,0 @@
-"""upload_docs
-
-Implements a Distutils 'upload_docs' subcommand (upload documentation to
-sites other than PyPi such as devpi).
-"""
-
-from base64 import standard_b64encode
-from distutils import log
-from distutils.errors import DistutilsOptionError
-import os
-import socket
-import zipfile
-import tempfile
-import shutil
-import itertools
-import functools
-import http.client
-import urllib.parse
-
-from .._importlib import metadata
-from ..warnings import SetuptoolsDeprecationWarning
-
-from .upload import upload
-
-
-def _encode(s):
-    return s.encode('utf-8', 'surrogateescape')
-
-
-class upload_docs(upload):
-    # override the default repository as upload_docs isn't
-    # supported by Warehouse (and won't be).
-    DEFAULT_REPOSITORY = 'https://pypi.python.org/pypi/'
-
-    description = 'Upload documentation to sites other than PyPi such as devpi'
-
-    user_options = [
-        (
-            'repository=',
-            'r',
-            "url of repository [default: %s]" % upload.DEFAULT_REPOSITORY,
-        ),
-        ('show-response', None, 'display full response text from server'),
-        ('upload-dir=', None, 'directory to upload'),
-    ]
-    boolean_options = upload.boolean_options
-
-    def has_sphinx(self):
-        return bool(
-            self.upload_dir is None
-            and metadata.entry_points(group='distutils.commands', name='build_sphinx')
-        )
-
-    sub_commands = [('build_sphinx', has_sphinx)]
-
-    def initialize_options(self):
-        upload.initialize_options(self)
-        self.upload_dir = None
-        self.target_dir = None
-
-    def finalize_options(self):
-        log.warn(
-            "Upload_docs command is deprecated. Use Read the Docs "
-            "(https://readthedocs.org) instead."
-        )
-        upload.finalize_options(self)
-        if self.upload_dir is None:
-            if self.has_sphinx():
-                build_sphinx = self.get_finalized_command('build_sphinx')
-                self.target_dir = dict(build_sphinx.builder_target_dirs)['html']
-            else:
-                build = self.get_finalized_command('build')
-                self.target_dir = os.path.join(build.build_base, 'docs')
-        else:
-            self.ensure_dirname('upload_dir')
-            self.target_dir = self.upload_dir
-        self.announce('Using upload directory %s' % self.target_dir)
-
-    def create_zipfile(self, filename):
-        zip_file = zipfile.ZipFile(filename, "w")
-        try:
-            self.mkpath(self.target_dir)  # just in case
-            for root, dirs, files in os.walk(self.target_dir):
-                if root == self.target_dir and not files:
-                    tmpl = "no files found in upload directory '%s'"
-                    raise DistutilsOptionError(tmpl % self.target_dir)
-                for name in files:
-                    full = os.path.join(root, name)
-                    relative = root[len(self.target_dir) :].lstrip(os.path.sep)
-                    dest = os.path.join(relative, name)
-                    zip_file.write(full, dest)
-        finally:
-            zip_file.close()
-
-    def run(self):
-        SetuptoolsDeprecationWarning.emit(
-            "Deprecated command",
-            """
-            upload_docs is deprecated and will be removed in a future version.
-            Instead, use tools like devpi and Read the Docs; or lower level tools like
-            httpie and curl to interact directly with your hosting service API.
-            """,
-            due_date=(2023, 9, 26),  # warning introduced in 27 Jul 2022
-        )
-
-        # Run sub commands
-        for cmd_name in self.get_sub_commands():
-            self.run_command(cmd_name)
-
-        tmp_dir = tempfile.mkdtemp()
-        name = self.distribution.metadata.get_name()
-        zip_file = os.path.join(tmp_dir, "%s.zip" % name)
-        try:
-            self.create_zipfile(zip_file)
-            self.upload_file(zip_file)
-        finally:
-            shutil.rmtree(tmp_dir)
-
-    @staticmethod
-    def _build_part(item, sep_boundary):
-        key, values = item
-        title = '\nContent-Disposition: form-data; name="%s"' % key
-        # handle multiple entries for the same name
-        if not isinstance(values, list):
-            values = [values]
-        for value in values:
-            if isinstance(value, tuple):
-                title += '; filename="%s"' % value[0]
-                value = value[1]
-            else:
-                value = _encode(value)
-            yield sep_boundary
-            yield _encode(title)
-            yield b"\n\n"
-            yield value
-            if value and value[-1:] == b'\r':
-                yield b'\n'  # write an extra newline (lurve Macs)
-
-    @classmethod
-    def _build_multipart(cls, data):
-        """
-        Build up the MIME payload for the POST data
-        """
-        boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
-        sep_boundary = b'\n--' + boundary.encode('ascii')
-        end_boundary = sep_boundary + b'--'
-        end_items = (
-            end_boundary,
-            b"\n",
-        )
-        builder = functools.partial(
-            cls._build_part,
-            sep_boundary=sep_boundary,
-        )
-        part_groups = map(builder, data.items())
-        parts = itertools.chain.from_iterable(part_groups)
-        body_items = itertools.chain(parts, end_items)
-        content_type = 'multipart/form-data; boundary=%s' % boundary
-        return b''.join(body_items), content_type
-
-    def upload_file(self, filename):
-        with open(filename, 'rb') as f:
-            content = f.read()
-        meta = self.distribution.metadata
-        data = {
-            ':action': 'doc_upload',
-            'name': meta.get_name(),
-            'content': (os.path.basename(filename), content),
-        }
-        # set up the authentication
-        credentials = _encode(self.username + ':' + self.password)
-        credentials = standard_b64encode(credentials).decode('ascii')
-        auth = "Basic " + credentials
-
-        body, ct = self._build_multipart(data)
-
-        msg = "Submitting documentation to %s" % (self.repository)
-        self.announce(msg, log.INFO)
-
-        # build the Request
-        # We can't use urllib2 since we need to send the Basic
-        # auth right with the first request
-        schema, netloc, url, params, query, fragments = urllib.parse.urlparse(
-            self.repository
-        )
-        assert not params and not query and not fragments
-        if schema == 'http':
-            conn = http.client.HTTPConnection(netloc)
-        elif schema == 'https':
-            conn = http.client.HTTPSConnection(netloc)
-        else:
-            raise AssertionError("unsupported schema " + schema)
-
-        data = ''
-        try:
-            conn.connect()
-            conn.putrequest("POST", url)
-            content_type = ct
-            conn.putheader('Content-type', content_type)
-            conn.putheader('Content-length', str(len(body)))
-            conn.putheader('Authorization', auth)
-            conn.endheaders()
-            conn.send(body)
-        except socket.error as e:
-            self.announce(str(e), log.ERROR)
-            return
-
-        r = conn.getresponse()
-        if r.status == 200:
-            msg = 'Server response (%s): %s' % (r.status, r.reason)
-            self.announce(msg, log.INFO)
-        elif r.status == 301:
-            location = r.getheader('Location')
-            if location is None:
-                location = 'https://pythonhosted.org/%s/' % meta.get_name()
-            msg = 'Upload successful. Visit %s' % location
-            self.announce(msg, log.INFO)
-        else:
-            msg = 'Upload failed (%s): %s' % (r.status, r.reason)
-            self.announce(msg, log.ERROR)
-        if self.show_response:
-            print('-' * 75, r.read(), '-' * 75)
diff --git a/pkg_resources/_vendor/importlib_resources/tests/data02/__init__.py b/setuptools/compat/__init__.py
similarity index 100%
rename from pkg_resources/_vendor/importlib_resources/tests/data02/__init__.py
rename to setuptools/compat/__init__.py
diff --git a/setuptools/compat/py310.py b/setuptools/compat/py310.py
new file mode 100644
index 0000000000..58a4d9f366
--- /dev/null
+++ b/setuptools/compat/py310.py
@@ -0,0 +1,20 @@
+import sys
+
+__all__ = ['tomllib']
+
+
+if sys.version_info >= (3, 11):
+    import tomllib
+else:  # pragma: no cover
+    import tomli as tomllib
+
+
+if sys.version_info >= (3, 11):
+
+    def add_note(ex, note):
+        ex.add_note(note)
+
+else:  # pragma: no cover
+
+    def add_note(ex, note):
+        vars(ex).setdefault('__notes__', []).append(note)
diff --git a/setuptools/compat/py311.py b/setuptools/compat/py311.py
new file mode 100644
index 0000000000..2aec70b8cc
--- /dev/null
+++ b/setuptools/compat/py311.py
@@ -0,0 +1,29 @@
+from __future__ import annotations
+
+import shutil
+import sys
+from collections.abc import Callable
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+    from typing import TypeAlias
+
+    from _typeshed import ExcInfo, StrOrBytesPath
+
+# Same as shutil._OnExcCallback from typeshed
+_OnExcCallback: TypeAlias = Callable[[Callable[..., Any], str, BaseException], object]
+
+
+def shutil_rmtree(
+    path: StrOrBytesPath,
+    ignore_errors: bool = False,
+    onexc: _OnExcCallback | None = None,
+) -> None:
+    if sys.version_info >= (3, 12):
+        return shutil.rmtree(path, ignore_errors, onexc=onexc)
+
+    def _handler(fn: Callable[..., Any], path: str, excinfo: ExcInfo) -> None:
+        if onexc:
+            onexc(fn, path, excinfo[1])
+
+    return shutil.rmtree(path, ignore_errors, onerror=_handler)
diff --git a/setuptools/compat/py312.py b/setuptools/compat/py312.py
new file mode 100644
index 0000000000..b20c5f697a
--- /dev/null
+++ b/setuptools/compat/py312.py
@@ -0,0 +1,13 @@
+from __future__ import annotations
+
+import sys
+
+if sys.version_info >= (3, 12, 4):
+    # Python 3.13 should support `.pth` files encoded in UTF-8
+    # See discussion in https://github.com/python/cpython/issues/77102
+    PTH_ENCODING: str | None = "utf-8"
+else:
+    from .py39 import LOCALE_ENCODING
+
+    # PTH_ENCODING = "locale"
+    PTH_ENCODING = LOCALE_ENCODING
diff --git a/setuptools/compat/py39.py b/setuptools/compat/py39.py
new file mode 100644
index 0000000000..04a4abe5a9
--- /dev/null
+++ b/setuptools/compat/py39.py
@@ -0,0 +1,9 @@
+import sys
+
+# Explicitly use the ``"locale"`` encoding in versions that support it,
+# otherwise just rely on the implicit handling of ``encoding=None``.
+# Since all platforms that support ``EncodingWarning`` also support
+# ``encoding="locale"``, this can be used to suppress the warning.
+# However, please try to use UTF-8 when possible
+# (.pth files are the notorious exception: python/cpython#77102, pypa/setuptools#3937).
+LOCALE_ENCODING = "locale" if sys.version_info >= (3, 10) else None
diff --git a/setuptools/config/NOTICE b/setuptools/config/NOTICE
new file mode 100644
index 0000000000..01864511b0
--- /dev/null
+++ b/setuptools/config/NOTICE
@@ -0,0 +1,10 @@
+The following files include code from opensource projects
+(either as direct copies or modified versions):
+
+- `setuptools.schema.json`, `distutils.schema.json`:
+    - project: `validate-pyproject` - licensed under MPL-2.0
+      (https://github.com/abravalheri/validate-pyproject):
+
+      This Source Code Form is subject to the terms of the Mozilla Public
+      License, v. 2.0. If a copy of the MPL was not distributed with this file,
+      You can obtain one at https://mozilla.org/MPL/2.0/.
diff --git a/setuptools/config/__init__.py b/setuptools/config/__init__.py
index ffea394436..76754b0ced 100644
--- a/setuptools/config/__init__.py
+++ b/setuptools/config/__init__.py
@@ -1,8 +1,10 @@
 """For backward compatibility, expose main functions from
 ``setuptools.config.setupcfg``
 """
+
+from collections.abc import Callable
 from functools import wraps
-from typing import Callable, TypeVar, cast
+from typing import TypeVar, cast
 
 from ..warnings import SetuptoolsDeprecationWarning
 from . import setupcfg
diff --git a/setuptools/config/_apply_pyprojecttoml.py b/setuptools/config/_apply_pyprojecttoml.py
index 4b8f803c1b..140969feee 100644
--- a/setuptools/config/_apply_pyprojecttoml.py
+++ b/setuptools/config/_apply_pyprojecttoml.py
@@ -7,43 +7,43 @@
 
 **PRIVATE MODULE**: API reserved for setuptools internal usage only.
 """
+
+from __future__ import annotations
+
 import logging
 import os
-from collections.abc import Mapping
+from collections.abc import Callable, Mapping
 from email.headerregistry import Address
 from functools import partial, reduce
+from inspect import cleandoc
 from itertools import chain
 from types import MappingProxyType
-from typing import (
-    TYPE_CHECKING,
-    Any,
-    Callable,
-    Dict,
-    List,
-    Optional,
-    Set,
-    Tuple,
-    Type,
-    Union,
-    cast,
-)
-
-from ..warnings import SetuptoolsWarning, SetuptoolsDeprecationWarning
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from .. import _static
+from .._path import StrPath
+from ..errors import InvalidConfigError, RemovedConfigError
+from ..extension import Extension
+from ..warnings import SetuptoolsDeprecationWarning, SetuptoolsWarning
 
 if TYPE_CHECKING:
-    from setuptools._importlib import metadata  # noqa
-    from setuptools.dist import Distribution  # noqa
+    from typing import TypeAlias
+
+    from setuptools._importlib import metadata
+    from setuptools.dist import Distribution
+
+    from distutils.dist import _OptionsList  # Comes from typeshed
+
 
 EMPTY: Mapping = MappingProxyType({})  # Immutable dict-like
-_Path = Union[os.PathLike, str]
-_DictOrStr = Union[dict, str]
-_CorrespFn = Callable[["Distribution", Any, _Path], None]
-_Correspondence = Union[str, _CorrespFn]
+_ProjectReadmeValue: TypeAlias = str | dict[str, str]
+_Correspondence: TypeAlias = Callable[["Distribution", Any, StrPath | None], None]
+_T = TypeVar("_T")
 
 _logger = logging.getLogger(__name__)
 
 
-def apply(dist: "Distribution", config: dict, filename: _Path) -> "Distribution":
+def apply(dist: Distribution, config: dict, filename: StrPath) -> Distribution:
     """Apply configuration dict read with :func:`read_configuration`"""
 
     if not config:
@@ -58,6 +58,7 @@ def apply(dist: "Distribution", config: dict, filename: _Path) -> "Distribution"
     os.chdir(root_dir)
     try:
         dist._finalize_requires()
+        dist._finalize_license_expression()
         dist._finalize_license_files()
     finally:
         os.chdir(current_directory)
@@ -65,11 +66,12 @@ def apply(dist: "Distribution", config: dict, filename: _Path) -> "Distribution"
     return dist
 
 
-def _apply_project_table(dist: "Distribution", config: dict, root_dir: _Path):
-    project_table = config.get("project", {}).copy()
-    if not project_table:
+def _apply_project_table(dist: Distribution, config: dict, root_dir: StrPath):
+    orig_config = config.get("project", {})
+    if not orig_config:
         return  # short-circuit
 
+    project_table = {k: _static.attempt_conversion(v) for k, v in orig_config.items()}
     _handle_missing_dynamic(dist, project_table)
     _unify_entry_points(project_table)
 
@@ -82,36 +84,57 @@ def _apply_project_table(dist: "Distribution", config: dict, root_dir: _Path):
             _set_config(dist, corresp, value)
 
 
-def _apply_tool_table(dist: "Distribution", config: dict, filename: _Path):
+def _apply_tool_table(dist: Distribution, config: dict, filename: StrPath):
     tool_table = config.get("tool", {}).get("setuptools", {})
     if not tool_table:
         return  # short-circuit
 
+    if "license-files" in tool_table:
+        if "license-files" in config.get("project", {}):
+            # https://github.com/pypa/setuptools/pull/4837#discussion_r2004983349
+            raise InvalidConfigError(
+                "'project.license-files' is defined already. "
+                "Remove 'tool.setuptools.license-files'."
+            )
+
+        pypa_guides = "guides/writing-pyproject-toml/#license-files"
+        SetuptoolsDeprecationWarning.emit(
+            "'tool.setuptools.license-files' is deprecated in favor of "
+            "'project.license-files' (available on setuptools>=77.0.0).",
+            see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
+            due_date=(2027, 2, 18),  # Warning introduced on 2025-02-18
+        )
+
     for field, value in tool_table.items():
         norm_key = json_compatible_key(field)
 
-        if norm_key in TOOL_TABLE_DEPRECATIONS:
-            suggestion, kwargs = TOOL_TABLE_DEPRECATIONS[norm_key]
-            msg = f"The parameter `{norm_key}` is deprecated, {suggestion}"
-            SetuptoolsDeprecationWarning.emit(
-                "Deprecated config", msg, **kwargs  # type: ignore
-            )
+        if norm_key in TOOL_TABLE_REMOVALS:
+            suggestion = cleandoc(TOOL_TABLE_REMOVALS[norm_key])
+            msg = f"""
+            The parameter `tool.setuptools.{field}` was long deprecated
+            and has been removed from `pyproject.toml`.
+            """
+            raise RemovedConfigError("\n".join([cleandoc(msg), suggestion]))
 
         norm_key = TOOL_TABLE_RENAMES.get(norm_key, norm_key)
-        _set_config(dist, norm_key, value)
+        corresp = TOOL_TABLE_CORRESPONDENCE.get(norm_key, norm_key)
+        if callable(corresp):
+            corresp(dist, value)
+        else:
+            _set_config(dist, corresp, value)
 
     _copy_command_options(config, dist, filename)
 
 
-def _handle_missing_dynamic(dist: "Distribution", project_table: dict):
+def _handle_missing_dynamic(dist: Distribution, project_table: dict):
     """Be temporarily forgiving with ``dynamic`` fields not listed in ``dynamic``"""
-    # TODO: Set fields back to `None` once the feature stabilizes
     dynamic = set(project_table.get("dynamic", []))
     for field, getter in _PREVIOUSLY_DEFINED.items():
         if not (field in project_table or field in dynamic):
             value = getter(dist)
             if value:
-                _WouldIgnoreField.emit(field=field, value=value)
+                _MissingDynamic.emit(field=field, value=value)
+                project_table[field] = _RESET_PREVIOUSLY_DEFINED.get(field)
 
 
 def json_compatible_key(key: str) -> str:
@@ -119,14 +142,15 @@ def json_compatible_key(key: str) -> str:
     return key.lower().replace("-", "_")
 
 
-def _set_config(dist: "Distribution", field: str, value: Any):
+def _set_config(dist: Distribution, field: str, value: Any):
+    val = _PREPROCESS.get(field, _noop)(dist, value)
     setter = getattr(dist.metadata, f"set_{field}", None)
     if setter:
-        setter(value)
+        setter(val)
     elif hasattr(dist.metadata, field) or field in SETUPTOOLS_PATCHES:
-        setattr(dist.metadata, field, value)
+        setattr(dist.metadata, field, val)
     else:
-        setattr(dist, field, value)
+        setattr(dist, field, val)
 
 
 _CONTENT_TYPES = {
@@ -136,51 +160,72 @@ def _set_config(dist: "Distribution", field: str, value: Any):
 }
 
 
-def _guess_content_type(file: str) -> Optional[str]:
+def _guess_content_type(file: str) -> str | None:
     _, ext = os.path.splitext(file.lower())
     if not ext:
         return None
 
     if ext in _CONTENT_TYPES:
-        return _CONTENT_TYPES[ext]
+        return _static.Str(_CONTENT_TYPES[ext])
 
     valid = ", ".join(f"{k} ({v})" for k, v in _CONTENT_TYPES.items())
     msg = f"only the following file extensions are recognized: {valid}."
     raise ValueError(f"Undefined content type for {file}, {msg}")
 
 
-def _long_description(dist: "Distribution", val: _DictOrStr, root_dir: _Path):
+def _long_description(
+    dist: Distribution, val: _ProjectReadmeValue, root_dir: StrPath | None
+):
     from setuptools.config import expand
 
+    file: str | tuple[()]
     if isinstance(val, str):
-        file: Union[str, list] = val
+        file = val
         text = expand.read_files(file, root_dir)
-        ctype = _guess_content_type(val)
+        ctype = _guess_content_type(file)
     else:
-        file = val.get("file") or []
+        file = val.get("file") or ()
         text = val.get("text") or expand.read_files(file, root_dir)
         ctype = val["content-type"]
 
-    _set_config(dist, "long_description", text)
+    # XXX: Is it completely safe to assume static?
+    _set_config(dist, "long_description", _static.Str(text))
 
     if ctype:
-        _set_config(dist, "long_description_content_type", ctype)
+        _set_config(dist, "long_description_content_type", _static.Str(ctype))
 
     if file:
-        dist._referenced_files.add(cast(str, file))
+        dist._referenced_files.add(file)
 
 
-def _license(dist: "Distribution", val: dict, root_dir: _Path):
+def _license(dist: Distribution, val: str | dict, root_dir: StrPath | None):
     from setuptools.config import expand
 
-    if "file" in val:
-        _set_config(dist, "license", expand.read_files([val["file"]], root_dir))
-        dist._referenced_files.add(val["file"])
+    if isinstance(val, str):
+        if getattr(dist.metadata, "license", None):
+            SetuptoolsWarning.emit("`license` overwritten by `pyproject.toml`")
+            dist.metadata.license = None
+        _set_config(dist, "license_expression", _static.Str(val))
     else:
-        _set_config(dist, "license", val["text"])
+        pypa_guides = "guides/writing-pyproject-toml/#license"
+        SetuptoolsDeprecationWarning.emit(
+            "`project.license` as a TOML table is deprecated",
+            "Please use a simple string containing a SPDX expression for "
+            "`project.license`. You can also use `project.license-files`. "
+            "(Both options available on setuptools>=77.0.0).",
+            see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
+            due_date=(2027, 2, 18),  # Introduced on 2025-02-18
+        )
+        if "file" in val:
+            # XXX: Is it completely safe to assume static?
+            value = expand.read_files([val["file"]], root_dir)
+            _set_config(dist, "license", _static.Str(value))
+            dist._referenced_files.add(val["file"])
+        else:
+            _set_config(dist, "license", _static.Str(val["text"]))
 
 
-def _people(dist: "Distribution", val: List[dict], _root_dir: _Path, kind: str):
+def _people(dist: Distribution, val: list[dict], _root_dir: StrPath | None, kind: str):
     field = []
     email_field = []
     for person in val:
@@ -193,50 +238,78 @@ def _people(dist: "Distribution", val: List[dict], _root_dir: _Path, kind: str):
             email_field.append(str(addr))
 
     if field:
-        _set_config(dist, kind, ", ".join(field))
+        _set_config(dist, kind, _static.Str(", ".join(field)))
     if email_field:
-        _set_config(dist, f"{kind}_email", ", ".join(email_field))
+        _set_config(dist, f"{kind}_email", _static.Str(", ".join(email_field)))
 
 
-def _project_urls(dist: "Distribution", val: dict, _root_dir):
+def _project_urls(dist: Distribution, val: dict, _root_dir: StrPath | None):
     _set_config(dist, "project_urls", val)
 
 
-def _python_requires(dist: "Distribution", val: dict, _root_dir):
-    from setuptools.extern.packaging.specifiers import SpecifierSet
+def _python_requires(dist: Distribution, val: str, _root_dir: StrPath | None):
+    _set_config(dist, "python_requires", _static.SpecifierSet(val))
 
-    _set_config(dist, "python_requires", SpecifierSet(val))
 
-
-def _dependencies(dist: "Distribution", val: list, _root_dir):
+def _dependencies(dist: Distribution, val: list, _root_dir: StrPath | None):
     if getattr(dist, "install_requires", []):
         msg = "`install_requires` overwritten in `pyproject.toml` (dependencies)"
         SetuptoolsWarning.emit(msg)
-    _set_config(dist, "install_requires", val)
+    dist.install_requires = val
+
+
+def _optional_dependencies(dist: Distribution, val: dict, _root_dir: StrPath | None):
+    if getattr(dist, "extras_require", None):
+        msg = "`extras_require` overwritten in `pyproject.toml` (optional-dependencies)"
+        SetuptoolsWarning.emit(msg)
+    dist.extras_require = val
+
 
+def _ext_modules(dist: Distribution, val: list[dict]) -> list[Extension]:
+    existing = dist.ext_modules or []
+    args = ({k.replace("-", "_"): v for k, v in x.items()} for x in val)
+    new = (Extension(**_adjust_ext_attrs(kw)) for kw in args)
+    return [*existing, *new]
 
-def _optional_dependencies(dist: "Distribution", val: dict, _root_dir):
-    existing = getattr(dist, "extras_require", None) or {}
-    _set_config(dist, "extras_require", {**existing, **val})
+
+def _adjust_ext_attrs(attrs: dict) -> dict:
+    # https://github.com/pypa/setuptools/issues/4810
+    # In TOML there is no differentiation between tuples and lists,
+    # and distutils requires tuples...
+    attrs["define_macros"] = list(map(tuple, attrs.get("define_macros") or []))
+    return attrs
+
+
+def _noop(_dist: Distribution, val: _T) -> _T:
+    return val
+
+
+def _identity(val: _T) -> _T:
+    return val
 
 
 def _unify_entry_points(project_table: dict):
     project = project_table
-    entry_points = project.pop("entry-points", project.pop("entry_points", {}))
+    given = project.pop("entry-points", project.pop("entry_points", {}))
+    entry_points = dict(given)  # Avoid problems with static
     renaming = {"scripts": "console_scripts", "gui_scripts": "gui_scripts"}
     for key, value in list(project.items()):  # eager to allow modifications
         norm_key = json_compatible_key(key)
-        if norm_key in renaming and value:
+        if norm_key in renaming:
+            # Don't skip even if value is empty (reason: reset missing `dynamic`)
             entry_points[renaming[norm_key]] = project.pop(key)
 
     if entry_points:
         project["entry-points"] = {
             name: [f"{k} = {v}" for k, v in group.items()]
             for name, group in entry_points.items()
+            if group  # now we can skip empty groups
         }
+        # Sometimes this will set `project["entry-points"] = {}`, and that is
+        # intentional (for resetting configurations that are missing `dynamic`).
 
 
-def _copy_command_options(pyproject: dict, dist: "Distribution", filename: _Path):
+def _copy_command_options(pyproject: dict, dist: Distribution, filename: StrPath):
     tool_table = pyproject.get("tool", {})
     cmdclass = tool_table.get("setuptools", {}).get("cmdclass", {})
     valid_options = _valid_command_options(cmdclass)
@@ -255,10 +328,11 @@ def _copy_command_options(pyproject: dict, dist: "Distribution", filename: _Path
                 _logger.warning(f"Command option {cmd}.{key} is not defined")
 
 
-def _valid_command_options(cmdclass: Mapping = EMPTY) -> Dict[str, Set[str]]:
-    from .._importlib import metadata
+def _valid_command_options(cmdclass: Mapping = EMPTY) -> dict[str, set[str]]:
     from setuptools.dist import Distribution
 
+    from .._importlib import metadata
+
     valid_options = {"global": _normalise_cmd_options(Distribution.global_options)}
 
     unloaded_entry_points = metadata.entry_points(group='distutils.commands')
@@ -272,7 +346,12 @@ def _valid_command_options(cmdclass: Mapping = EMPTY) -> Dict[str, Set[str]]:
     return valid_options
 
 
-def _load_ep(ep: "metadata.EntryPoint") -> Optional[Tuple[str, Type]]:
+def _load_ep(ep: metadata.EntryPoint) -> tuple[str, type] | None:
+    if ep.value.startswith("wheel.bdist_wheel"):
+        # Ignore deprecated entrypoint from wheel and avoid warning pypa/wheel#631
+        # TODO: remove check when `bdist_wheel` has been fully removed from pypa/wheel
+        return None
+
     # Ignore all the errors
     try:
         return (ep.name, ep.load())
@@ -286,26 +365,34 @@ def _normalise_cmd_option_key(name: str) -> str:
     return json_compatible_key(name).strip("_=")
 
 
-def _normalise_cmd_options(desc: List[Tuple[str, Optional[str], str]]) -> Set[str]:
+def _normalise_cmd_options(desc: _OptionsList) -> set[str]:
     return {_normalise_cmd_option_key(fancy_option[0]) for fancy_option in desc}
 
 
-def _get_previous_entrypoints(dist: "Distribution") -> Dict[str, list]:
+def _get_previous_entrypoints(dist: Distribution) -> dict[str, list]:
     ignore = ("console_scripts", "gui_scripts")
     value = getattr(dist, "entry_points", None) or {}
     return {k: v for k, v in value.items() if k not in ignore}
 
 
-def _get_previous_scripts(dist: "Distribution") -> Optional[list]:
+def _get_previous_scripts(dist: Distribution) -> list | None:
     value = getattr(dist, "entry_points", None) or {}
     return value.get("console_scripts")
 
 
-def _get_previous_gui_scripts(dist: "Distribution") -> Optional[list]:
+def _get_previous_gui_scripts(dist: Distribution) -> list | None:
     value = getattr(dist, "entry_points", None) or {}
     return value.get("gui_scripts")
 
 
+def _set_static_list_metadata(attr: str, dist: Distribution, val: list) -> None:
+    """Apply distutils metadata validation but preserve "static" behaviour"""
+    meta = dist.metadata
+    setter, getter = getattr(meta, f"set_{attr}"), getattr(meta, f"get_{attr}")
+    setter(val)
+    setattr(meta, attr, _static.List(getter()))
+
+
 def _attrgetter(attr):
     """
     Similar to ``operator.attrgetter`` but returns None if ``attr`` is not found
@@ -341,7 +428,7 @@ def _acessor(obj):
     return _acessor
 
 
-PYPROJECT_CORRESPONDENCE: Dict[str, _Correspondence] = {
+PYPROJECT_CORRESPONDENCE: dict[str, _Correspondence] = {
     "readme": _long_description,
     "license": _license,
     "authors": partial(_people, kind="author"),
@@ -353,11 +440,17 @@ def _acessor(obj):
 }
 
 TOOL_TABLE_RENAMES = {"script_files": "scripts"}
-TOOL_TABLE_DEPRECATIONS = {
-    "namespace_packages": (
-        "consider using implicit namespaces instead (PEP 420).",
-        {"due_date": (2023, 10, 30)},  # warning introduced in May 2022
-    )
+TOOL_TABLE_REMOVALS = {
+    "namespace_packages": """
+        Please migrate to implicit native namespaces instead.
+        See https://packaging.python.org/en/latest/guides/packaging-namespace-packages/.
+        """,
+}
+TOOL_TABLE_CORRESPONDENCE = {
+    # Fields with corresponding core metadata need to be marked as static:
+    "obsoletes": partial(_set_static_list_metadata, "obsoletes"),
+    "provides": partial(_set_static_list_metadata, "provides"),
+    "platforms": partial(_set_static_list_metadata, "platforms"),
 }
 
 SETUPTOOLS_PATCHES = {
@@ -366,6 +459,11 @@ def _acessor(obj):
     "provides_extras",
     "license_file",
     "license_files",
+    "license_expression",
+}
+
+_PREPROCESS = {
+    "ext_modules": _ext_modules,
 }
 
 _PREVIOUSLY_DEFINED = {
@@ -374,7 +472,9 @@ def _acessor(obj):
     "description": _attrgetter("metadata.description"),
     "readme": _attrgetter("metadata.long_description"),
     "requires-python": _some_attrgetter("python_requires", "metadata.python_requires"),
-    "license": _attrgetter("metadata.license"),
+    "license": _some_attrgetter("metadata.license_expression", "metadata.license"),
+    # XXX: `license-file` is currently not considered in the context of `dynamic`.
+    #      See TestPresetField.test_license_files_exempt_from_dynamic
     "authors": _some_attrgetter("metadata.author", "metadata.author_email"),
     "maintainers": _some_attrgetter("metadata.maintainer", "metadata.maintainer_email"),
     "keywords": _attrgetter("metadata.keywords"),
@@ -388,14 +488,30 @@ def _acessor(obj):
 }
 
 
-class _WouldIgnoreField(SetuptoolsDeprecationWarning):
-    _SUMMARY = "`{field}` defined outside of `pyproject.toml` would be ignored."
+_RESET_PREVIOUSLY_DEFINED: dict = {
+    # Fix improper setting: given in `setup.py`, but not listed in `dynamic`
+    # Use "immutable" data structures to avoid in-place modification.
+    # dict: pyproject name => value to which reset
+    "license": "",
+    # XXX: `license-file` is currently not considered in the context of `dynamic`.
+    #      See TestPresetField.test_license_files_exempt_from_dynamic
+    "authors": _static.EMPTY_LIST,
+    "maintainers": _static.EMPTY_LIST,
+    "keywords": _static.EMPTY_LIST,
+    "classifiers": _static.EMPTY_LIST,
+    "urls": _static.EMPTY_DICT,
+    "entry-points": _static.EMPTY_DICT,
+    "scripts": _static.EMPTY_DICT,
+    "gui-scripts": _static.EMPTY_DICT,
+    "dependencies": _static.EMPTY_LIST,
+    "optional-dependencies": _static.EMPTY_DICT,
+}
+
+
+class _MissingDynamic(SetuptoolsWarning):
+    _SUMMARY = "`{field}` defined outside of `pyproject.toml` is ignored."
 
     _DETAILS = """
-    ##########################################################################
-    # configuration would be ignored/result in error due to `pyproject.toml` #
-    ##########################################################################
-
     The following seems to be defined outside of `pyproject.toml`:
 
     `{field} = {value!r}`
@@ -403,14 +519,16 @@ class _WouldIgnoreField(SetuptoolsDeprecationWarning):
     According to the spec (see the link below), however, setuptools CANNOT
     consider this value unless `{field}` is listed as `dynamic`.
 
-    https://packaging.python.org/en/latest/specifications/declaring-project-metadata/
+    https://packaging.python.org/en/latest/specifications/pyproject-toml/#declaring-project-metadata-the-project-table
 
-    For the time being, `setuptools` will still consider the given value (as a
-    **transitional** measure), but please note that future releases of setuptools will
-    follow strictly the standard.
-
-    To prevent this warning, you can list `{field}` under `dynamic` or alternatively
+    To prevent this problem, you can list `{field}` under `dynamic` or alternatively
     remove the `[project]` table from your file and rely entirely on other means of
     configuration.
     """
-    _DUE_DATE = (2023, 10, 30)  # Initially introduced in 27 May 2022
+    # TODO: Consider removing this check in the future?
+    #       There is a trade-off here between improving "debug-ability" and the cost
+    #       of running/testing/maintaining these unnecessary checks...
+
+    @classmethod
+    def details(cls, field: str, value: Any) -> str:
+        return cls._DETAILS.format(field=field, value=value)
diff --git a/setuptools/config/_validate_pyproject/NOTICE b/setuptools/config/_validate_pyproject/NOTICE
index 286d29082e..74e8821fc8 100644
--- a/setuptools/config/_validate_pyproject/NOTICE
+++ b/setuptools/config/_validate_pyproject/NOTICE
@@ -1,7 +1,7 @@
 The code contained in this directory was automatically generated using the
 following command:
 
-    python -m validate_pyproject.pre_compile --output-dir=setuptools/config/_validate_pyproject --enable-plugins setuptools distutils --very-verbose
+    python -m validate_pyproject.pre_compile --output-dir=setuptools/config/_validate_pyproject --enable-plugins setuptools distutils --very-verbose -t distutils=setuptools/config/distutils.schema.json -t setuptools=setuptools/config/setuptools.schema.json
 
 Please avoid changing it manually.
 
@@ -436,4 +436,3 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice
       This Source Code Form is "Incompatible
       With Secondary Licenses", as defined by
       the Mozilla Public License, v. 2.0.
-
diff --git a/setuptools/config/_validate_pyproject/__init__.py b/setuptools/config/_validate_pyproject/__init__.py
index dbe6cb4ca4..4f612bd51c 100644
--- a/setuptools/config/_validate_pyproject/__init__.py
+++ b/setuptools/config/_validate_pyproject/__init__.py
@@ -30,5 +30,5 @@ def validate(data: Any) -> bool:
     """
     with detailed_errors():
         _validate(data, custom_formats=FORMAT_FUNCTIONS)
-    reduce(lambda acc, fn: fn(acc), EXTRA_VALIDATIONS, data)
+        reduce(lambda acc, fn: fn(acc), EXTRA_VALIDATIONS, data)
     return True
diff --git a/setuptools/config/_validate_pyproject/error_reporting.py b/setuptools/config/_validate_pyproject/error_reporting.py
index f78e4838fb..9ebe6a335c 100644
--- a/setuptools/config/_validate_pyproject/error_reporting.py
+++ b/setuptools/config/_validate_pyproject/error_reporting.py
@@ -1,14 +1,25 @@
+from __future__ import annotations
+
 import io
 import json
 import logging
 import os
 import re
+import typing
 from contextlib import contextmanager
 from textwrap import indent, wrap
-from typing import Any, Dict, Iterator, List, Optional, Sequence, Union, cast
+from typing import Any, Generator, Iterator, Sequence
 
 from .fastjsonschema_exceptions import JsonSchemaValueException
 
+if typing.TYPE_CHECKING:
+    import sys
+
+    if sys.version_info < (3, 11):
+        from typing_extensions import Self
+    else:
+        from typing import Self
+
 _logger = logging.getLogger(__name__)
 
 _MESSAGE_REPLACEMENTS = {
@@ -24,10 +35,10 @@
     "must not be there",
 )
 
-_NEED_DETAILS = {"anyOf", "oneOf", "anyOf", "contains", "propertyNames", "not", "items"}
+_NEED_DETAILS = {"anyOf", "oneOf", "allOf", "contains", "propertyNames", "not", "items"}
 
 _CAMEL_CASE_SPLITTER = re.compile(r"\W+|([A-Z][^A-Z\W]*)")
-_IDENTIFIER = re.compile(r"^[\w_]+$", re.I)
+_IDENTIFIER = re.compile(r"^[\w_]+$", re.IGNORECASE)
 
 _TOML_JARGON = {
     "object": "table",
@@ -36,6 +47,11 @@
     "property names": "keys",
 }
 
+_FORMATS_HELP = """
+For more details about `format` see
+https://validate-pyproject.readthedocs.io/en/latest/api/validate_pyproject.formats.html
+"""
+
 
 class ValidationError(JsonSchemaValueException):
     """Report violations of a given JSON schema.
@@ -59,7 +75,7 @@ class ValidationError(JsonSchemaValueException):
     _original_message = ""
 
     @classmethod
-    def _from_jsonschema(cls, ex: JsonSchemaValueException):
+    def _from_jsonschema(cls, ex: JsonSchemaValueException) -> Self:
         formatter = _ErrorFormatting(ex)
         obj = cls(str(formatter), ex.value, formatter.name, ex.definition, ex.rule)
         debug_code = os.getenv("JSONSCHEMA_DEBUG_CODE_GENERATION", "false").lower()
@@ -72,7 +88,7 @@ def _from_jsonschema(cls, ex: JsonSchemaValueException):
 
 
 @contextmanager
-def detailed_errors():
+def detailed_errors() -> Generator[None, None, None]:
     try:
         yield
     except JsonSchemaValueException as ex:
@@ -83,7 +99,7 @@ class _ErrorFormatting:
     def __init__(self, ex: JsonSchemaValueException):
         self.ex = ex
         self.name = f"`{self._simplify_name(ex.name)}`"
-        self._original_message = self.ex.message.replace(ex.name, self.name)
+        self._original_message: str = self.ex.message.replace(ex.name, self.name)
         self._summary = ""
         self._details = ""
 
@@ -107,11 +123,12 @@ def details(self) -> str:
 
         return self._details
 
-    def _simplify_name(self, name):
+    @staticmethod
+    def _simplify_name(name: str) -> str:
         x = len("data.")
         return name[x:] if name.startswith("data.") else name
 
-    def _expand_summary(self):
+    def _expand_summary(self) -> str:
         msg = self._original_message
 
         for bad, repl in _MESSAGE_REPLACEMENTS.items():
@@ -129,8 +146,9 @@ def _expand_summary(self):
 
     def _expand_details(self) -> str:
         optional = []
-        desc_lines = self.ex.definition.pop("$$description", [])
-        desc = self.ex.definition.pop("description", None) or " ".join(desc_lines)
+        definition = self.ex.definition or {}
+        desc_lines = definition.pop("$$description", [])
+        desc = definition.pop("description", None) or " ".join(desc_lines)
         if desc:
             description = "\n".join(
                 wrap(
@@ -142,21 +160,23 @@ def _expand_details(self) -> str:
                 )
             )
             optional.append(f"DESCRIPTION:\n{description}")
-        schema = json.dumps(self.ex.definition, indent=4)
+        schema = json.dumps(definition, indent=4)
         value = json.dumps(self.ex.value, indent=4)
         defaults = [
             f"GIVEN VALUE:\n{indent(value, '    ')}",
             f"OFFENDING RULE: {self.ex.rule!r}",
             f"DEFINITION:\n{indent(schema, '    ')}",
         ]
-        return "\n\n".join(optional + defaults)
+        msg = "\n\n".join(optional + defaults)
+        epilog = f"\n{_FORMATS_HELP}" if "format" in msg.lower() else ""
+        return msg + epilog
 
 
 class _SummaryWriter:
-    _IGNORE = {"description", "default", "title", "examples"}
+    _IGNORE = frozenset(("description", "default", "title", "examples"))
 
-    def __init__(self, jargon: Optional[Dict[str, str]] = None):
-        self.jargon: Dict[str, str] = jargon or {}
+    def __init__(self, jargon: dict[str, str] | None = None):
+        self.jargon: dict[str, str] = jargon or {}
         # Clarify confusing terms
         self._terms = {
             "anyOf": "at least one of the following",
@@ -189,14 +209,14 @@ def __init__(self, jargon: Optional[Dict[str, str]] = None):
             "multipleOf",
         ]
 
-    def _jargon(self, term: Union[str, List[str]]) -> Union[str, List[str]]:
+    def _jargon(self, term: str | list[str]) -> str | list[str]:
         if isinstance(term, list):
             return [self.jargon.get(t, t) for t in term]
         return self.jargon.get(term, term)
 
     def __call__(
         self,
-        schema: Union[dict, List[dict]],
+        schema: dict | list[dict],
         prefix: str = "",
         *,
         _path: Sequence[str] = (),
@@ -242,14 +262,16 @@ def _is_unecessary(self, path: Sequence[str]) -> bool:
         key = path[-1]
         return any(key.startswith(k) for k in "$_") or key in self._IGNORE
 
-    def _filter_unecessary(self, schema: dict, path: Sequence[str]):
+    def _filter_unecessary(
+        self, schema: dict[str, Any], path: Sequence[str]
+    ) -> dict[str, Any]:
         return {
             key: value
             for key, value in schema.items()
             if not self._is_unecessary([*path, key])
         }
 
-    def _handle_simple_dict(self, value: dict, path: Sequence[str]) -> Optional[str]:
+    def _handle_simple_dict(self, value: dict, path: Sequence[str]) -> str | None:
         inline = any(p in value for p in self._guess_inline_defs)
         simple = not any(isinstance(v, (list, dict)) for v in value.values())
         if inline or simple:
@@ -271,7 +293,7 @@ def _handle_list(
             self(v, item_prefix, _path=[*path, f"[{i}]"]) for i, v in enumerate(schemas)
         )
 
-    def _is_property(self, path: Sequence[str]):
+    def _is_property(self, path: Sequence[str]) -> bool:
         """Check if the given path can correspond to an arbitrarily named property"""
         counter = 0
         for key in path[-2::-1]:
@@ -296,9 +318,7 @@ def _label(self, path: Sequence[str]) -> str:
     def _value(self, value: Any, path: Sequence[str]) -> str:
         if path[-1] == "type" and not self._is_property(path):
             type_ = self._jargon(value)
-            return (
-                f"[{', '.join(type_)}]" if isinstance(value, list) else cast(str, type_)
-            )
+            return f"[{', '.join(type_)}]" if isinstance(type_, list) else type_
         return repr(value)
 
     def _inline_attrs(self, schema: dict, path: Sequence[str]) -> Iterator[str]:
@@ -310,7 +330,7 @@ def _child_prefix(self, parent_prefix: str, child_prefix: str) -> str:
         return len(parent_prefix) * " " + child_prefix
 
 
-def _separate_terms(word: str) -> List[str]:
+def _separate_terms(word: str) -> list[str]:
     """
     >>> _separate_terms("FooBar-foo")
     ['foo', 'bar', 'foo']
diff --git a/setuptools/config/_validate_pyproject/extra_validations.py b/setuptools/config/_validate_pyproject/extra_validations.py
index 4130a421cf..72a7132f2b 100644
--- a/setuptools/config/_validate_pyproject/extra_validations.py
+++ b/setuptools/config/_validate_pyproject/extra_validations.py
@@ -3,7 +3,10 @@
 JSON Schema library).
 """
 
-from typing import Mapping, TypeVar
+import collections
+import itertools
+from inspect import cleandoc
+from typing import Generator, Iterable, Mapping, TypeVar
 
 from .error_reporting import ValidationError
 
@@ -11,11 +14,40 @@
 
 
 class RedefiningStaticFieldAsDynamic(ValidationError):
-    """According to PEP 621:
+    _DESC = """According to PEP 621:
 
     Build back-ends MUST raise an error if the metadata specifies a field
     statically as well as being listed in dynamic.
     """
+    __doc__ = _DESC
+    _URL = (
+        "https://packaging.python.org/en/latest/specifications/pyproject-toml/#dynamic"
+    )
+
+
+class IncludedDependencyGroupMustExist(ValidationError):
+    _DESC = """An included dependency group must exist and must not be cyclic.
+    """
+    __doc__ = _DESC
+    _URL = "https://peps.python.org/pep-0735/"
+
+
+class ImportNameCollision(ValidationError):
+    _DESC = """According to PEP 794:
+
+    All import-names and import-namespaces items must be unique.
+    """
+    __doc__ = _DESC
+    _URL = "https://peps.python.org/pep-0794/"
+
+
+class ImportNameMissing(ValidationError):
+    _DESC = """According to PEP 794:
+
+    An import name must have all parents listed.
+    """
+    __doc__ = _DESC
+    _URL = "https://peps.python.org/pep-0794/"
 
 
 def validate_project_dynamic(pyproject: T) -> T:
@@ -24,13 +56,96 @@ def validate_project_dynamic(pyproject: T) -> T:
 
     for field in dynamic:
         if field in project_table:
-            msg = f"You cannot provide a value for `project.{field}` and "
-            msg += "list it under `project.dynamic` at the same time"
-            name = f"data.project.{field}"
-            value = {field: project_table[field], "...": " # ...", "dynamic": dynamic}
-            raise RedefiningStaticFieldAsDynamic(msg, value, name, rule="PEP 621")
+            raise RedefiningStaticFieldAsDynamic(
+                message=f"You cannot provide a value for `project.{field}` and "
+                "list it under `project.dynamic` at the same time",
+                value={
+                    field: project_table[field],
+                    "...": " # ...",
+                    "dynamic": dynamic,
+                },
+                name=f"data.project.{field}",
+                definition={
+                    "description": cleandoc(RedefiningStaticFieldAsDynamic._DESC),
+                    "see": RedefiningStaticFieldAsDynamic._URL,
+                },
+                rule="PEP 621",
+            )
+
+    return pyproject
+
+
+def validate_include_depenency(pyproject: T) -> T:
+    dependency_groups = pyproject.get("dependency-groups", {})
+    for key, value in dependency_groups.items():
+        for each in value:
+            if (
+                isinstance(each, dict)
+                and (include_group := each.get("include-group"))
+                and include_group not in dependency_groups
+            ):
+                raise IncludedDependencyGroupMustExist(
+                    message=f"The included dependency group {include_group} doesn't exist",
+                    value=each,
+                    name=f"data.dependency_groups.{key}",
+                    definition={
+                        "description": cleandoc(IncludedDependencyGroupMustExist._DESC),
+                        "see": IncludedDependencyGroupMustExist._URL,
+                    },
+                    rule="PEP 735",
+                )
+    # TODO: check for `include-group` cycles (can be conditional to graphlib)
+    return pyproject
+
+
+def _remove_private(items: Iterable[str]) -> Generator[str, None, None]:
+    for item in items:
+        yield item.partition(";")[0].rstrip()
+
+
+def validate_import_name_issues(pyproject: T) -> T:
+    project = pyproject.get("project", {})
+    import_names = collections.Counter(_remove_private(project.get("import-names", [])))
+    import_namespaces = collections.Counter(
+        _remove_private(project.get("import-namespaces", []))
+    )
+
+    duplicated = [k for k, v in (import_names + import_namespaces).items() if v > 1]
+
+    if duplicated:
+        raise ImportNameCollision(
+            message="Duplicated names are not allowed in import-names/import-namespaces",
+            value=duplicated,
+            name="data.project.importnames(paces)",
+            definition={
+                "description": cleandoc(ImportNameCollision._DESC),
+                "see": ImportNameCollision._URL,
+            },
+            rule="PEP 794",
+        )
+
+    names = frozenset(import_names + import_namespaces)
+    for name in names:
+        for parent in itertools.accumulate(
+            name.split(".")[:-1], lambda a, b: f"{a}.{b}"
+        ):
+            if parent not in names:
+                raise ImportNameMissing(
+                    message="All parents of an import name must also be listed in import-namespace/import-names",
+                    value=name,
+                    name="data.project.importnames(paces)",
+                    definition={
+                        "description": cleandoc(ImportNameMissing._DESC),
+                        "see": ImportNameMissing._URL,
+                    },
+                    rule="PEP 794",
+                )
 
     return pyproject
 
 
-EXTRA_VALIDATIONS = (validate_project_dynamic,)
+EXTRA_VALIDATIONS = (
+    validate_project_dynamic,
+    validate_include_depenency,
+    validate_import_name_issues,
+)
diff --git a/setuptools/config/_validate_pyproject/fastjsonschema_validations.py b/setuptools/config/_validate_pyproject/fastjsonschema_validations.py
index b81d13c119..d8a03de9bf 100644
--- a/setuptools/config/_validate_pyproject/fastjsonschema_validations.py
+++ b/setuptools/config/_validate_pyproject/fastjsonschema_validations.py
@@ -1,5 +1,5 @@
 # noqa
-# type: ignore
+# ruff: noqa
 # flake8: noqa
 # pylint: skip-file
 # mypy: ignore-errors
@@ -10,12 +10,14 @@
 # *** PLEASE DO NOT MODIFY DIRECTLY: Automatically generated code *** 
 
 
-VERSION = "2.16.3"
+VERSION = "2.21.2"
+from decimal import Decimal
 import re
 from .fastjsonschema_exceptions import JsonSchemaValueException
 
 
 REGEX_PATTERNS = {
+    '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$': re.compile('^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])\\Z'),
     '^.*$': re.compile('^.*$'),
     '.+': re.compile('.+'),
     '^.+$': re.compile('^.+$'),
@@ -30,7 +32,7 @@ def validate(data, custom_formats={}, name_prefix=None):
 
 def validate_https___packaging_python_org_en_latest_specifications_declaring_build_dependencies(data, custom_formats={}, name_prefix=None):
     if not isinstance(data, (dict)):
-        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-build-dependencies/', 'title': 'Data structure for ``pyproject.toml`` files', '$$description': ['File format containing build-time configurations for the Python ecosystem. ', ':pep:`517` initially defined a build-system independent format for source trees', 'which was complemented by :pep:`518` to provide a way of specifying dependencies ', 'for building Python projects.', 'Please notice the ``project`` table (as initially defined in  :pep:`621`) is not included', 'in this schema and should be considered separately.'], 'type': 'object', 'additionalProperties': False, 'properties': {'build-system': {'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-project-metadata/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points `_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points `_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, 'tool': {'type': 'object', 'properties': {'distutils': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://docs.python.org/3/install/', 'title': '``tool.distutils`` table', '$$description': ['Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` scripts via `distutils configuration files', '`_.', '``tool.distutils`` subtables could be used with the same purpose', '(NOT CURRENTLY IMPLEMENTED).'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, 'setuptools': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://setuptools.pypa.io/en/latest/references/keywords.html', 'title': '``tool.setuptools`` table', '$$description': ['Please notice for the time being the ``setuptools`` project does not specify', 'a way of configuring builds via ``pyproject.toml``.', 'Therefore this schema should be taken just as a *"thought experiment"* on how', 'this *might be done*, by following the principles established in', '`ini2toml `_.', 'It considers only ``setuptools`` `parameters', '`_', 'that can currently be configured via ``setup.cfg`` and are not covered by :pep:`621`', 'but intentionally excludes ``dependency_links`` and ``setup_requires``.', 'NOTE: ``scripts`` was renamed to ``script-files`` to avoid confusion with', 'entry-point based scripts (defined in :pep:`621`).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'description': 'Whether the project can be safely installed and run from a zip file.', 'type': 'boolean'}, 'script-files': {'description': 'Legacy way of defining scripts (entry-points are preferred).', 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$ref': '#/definitions/package-name'}}, {'$ref': '#/definitions/find-directive'}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'const': ''}, {'$ref': '#/definitions/package-name'}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'data-files': {'$$description': ['**DEPRECATED**: dict-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', "Please notice this don't work with wheels. See `data files support", '`_'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['PROVISIONAL: List of glob patterns for all license files being distributed.', '(might become standard with PEP 639).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.'], 'oneOf': [{'$ref': '#/definitions/attr-directive'}, {'$ref': '#/definitions/file-directive'}]}, 'classifiers': {'$ref': '#/definitions/file-directive'}, 'description': {'$ref': '#/definitions/file-directive'}, 'dependencies': {'$ref': '#/definitions/file-directive'}, 'entry-points': {'$ref': '#/definitions/file-directive'}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$ref': '#/definitions/file-directive'}}}, 'readme': {'anyOf': [{'$ref': '#/definitions/file-directive'}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}}}}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-project-metadata/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points `_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points `_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='type')
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-build-dependencies/', 'title': 'Data structure for ``pyproject.toml`` files', '$$description': ['File format containing build-time configurations for the Python ecosystem. ', ':pep:`517` initially defined a build-system independent format for source trees', 'which was complemented by :pep:`518` to provide a way of specifying dependencies ', 'for building Python projects.', 'Please notice the ``project`` table (as initially defined in  :pep:`621`) is not included', 'in this schema and should be considered separately.'], 'type': 'object', 'additionalProperties': False, 'properties': {'build-system': {'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points `_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points `_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'import-names': {'description': 'Lists import names which a project, when installed, would exclusively provide.', 'type': 'array', 'items': {'type': 'string', 'format': 'import-name'}}, 'import-namespaces': {'description': 'Lists import names that, when installed, would be provided by the project, but not exclusively.', 'type': 'array', 'items': {'type': 'string', 'format': 'import-name'}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies', 'import-names', 'import-namespaces']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, 'tool': {'type': 'object', 'properties': {'distutils': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html', 'title': '``tool.distutils`` table', '$$description': ['**EXPERIMENTAL** (NOT OFFICIALLY SUPPORTED): Use ``tool.distutils``', 'subtables to configure arguments for ``distutils`` commands.', 'Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` commands via `distutils configuration files', '`_.', 'See also `the old Python docs _`.'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, 'setuptools': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html', 'title': '``tool.setuptools`` table', '$$description': ['``setuptools``-specific configurations that can be set by users that require', 'customization.', 'These configurations are completely optional and probably can be skipped when', 'creating simple packages. They are equivalent to some of the `Keywords', '`_', 'used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.', 'It considers only ``setuptools`` `parameters', '`_', 'that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``', 'and ``setup_requires`` (incompatible with modern workflows/standards).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, 'script-files': {'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$ref': '#/definitions/package-name'}}, {'$ref': '#/definitions/find-directive'}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$ref': '#/definitions/package-name'}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'$ref': '#/definitions/package-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'$ref': '#/definitions/package-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'ext-modules': {'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$ref': '#/definitions/ext-module'}}, 'data-files': {'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'$ref': '#/definitions/attr-directive'}, {'$ref': '#/definitions/file-directive'}]}, 'classifiers': {'$ref': '#/definitions/file-directive'}, 'description': {'$ref': '#/definitions/file-directive'}, 'entry-points': {'$ref': '#/definitions/file-directive'}, 'dependencies': {'$ref': '#/definitions/file-directive-for-dependencies'}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$ref': '#/definitions/file-directive-for-dependencies'}}}, 'readme': {'type': 'object', 'anyOf': [{'$ref': '#/definitions/file-directive'}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'$ref': '#/definitions/file-directive/properties/file'}}, 'additionalProperties': False}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, 'ext-module': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'file-directive-for-dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}}}, 'dependency-groups': {'type': 'object', 'description': 'Dependency groups following PEP 735', 'additionalProperties': False, 'patternProperties': {'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$': {'type': 'array', 'items': {'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}}}}}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points `_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points `_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'import-names': {'description': 'Lists import names which a project, when installed, would exclusively provide.', 'type': 'array', 'items': {'type': 'string', 'format': 'import-name'}}, 'import-namespaces': {'description': 'Lists import names that, when installed, would be provided by the project, but not exclusively.', 'type': 'array', 'items': {'type': 'string', 'format': 'import-name'}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies', 'import-names', 'import-namespaces']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='type')
     data_is_dict = isinstance(data, dict)
     if data_is_dict:
         data_keys = set(data.keys())
@@ -41,9 +43,9 @@ def validate_https___packaging_python_org_en_latest_specifications_declaring_bui
                 raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system must be object", value=data__buildsystem, name="" + (name_prefix or "data") + ".build-system", definition={'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, rule='type')
             data__buildsystem_is_dict = isinstance(data__buildsystem, dict)
             if data__buildsystem_is_dict:
-                data__buildsystem_len = len(data__buildsystem)
-                if not all(prop in data__buildsystem for prop in ['requires']):
-                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system must contain ['requires'] properties", value=data__buildsystem, name="" + (name_prefix or "data") + ".build-system", definition={'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, rule='required')
+                data__buildsystem__missing_keys = set(['requires']) - data__buildsystem.keys()
+                if data__buildsystem__missing_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system must contain " + (str(sorted(data__buildsystem__missing_keys)) + " properties"), value=data__buildsystem, name="" + (name_prefix or "data") + ".build-system", definition={'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, rule='required')
                 data__buildsystem_keys = set(data__buildsystem.keys())
                 if "requires" in data__buildsystem_keys:
                     data__buildsystem_keys.remove("requires")
@@ -80,30 +82,81 @@ def validate_https___packaging_python_org_en_latest_specifications_declaring_bui
         if "project" in data_keys:
             data_keys.remove("project")
             data__project = data["project"]
-            validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata(data__project, custom_formats, (name_prefix or "data") + ".project")
+            validate_https___packaging_python_org_en_latest_specifications_pyproject_toml(data__project, custom_formats, (name_prefix or "data") + ".project")
         if "tool" in data_keys:
             data_keys.remove("tool")
             data__tool = data["tool"]
             if not isinstance(data__tool, (dict)):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".tool must be object", value=data__tool, name="" + (name_prefix or "data") + ".tool", definition={'type': 'object', 'properties': {'distutils': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://docs.python.org/3/install/', 'title': '``tool.distutils`` table', '$$description': ['Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` scripts via `distutils configuration files', '`_.', '``tool.distutils`` subtables could be used with the same purpose', '(NOT CURRENTLY IMPLEMENTED).'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, 'setuptools': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://setuptools.pypa.io/en/latest/references/keywords.html', 'title': '``tool.setuptools`` table', '$$description': ['Please notice for the time being the ``setuptools`` project does not specify', 'a way of configuring builds via ``pyproject.toml``.', 'Therefore this schema should be taken just as a *"thought experiment"* on how', 'this *might be done*, by following the principles established in', '`ini2toml `_.', 'It considers only ``setuptools`` `parameters', '`_', 'that can currently be configured via ``setup.cfg`` and are not covered by :pep:`621`', 'but intentionally excludes ``dependency_links`` and ``setup_requires``.', 'NOTE: ``scripts`` was renamed to ``script-files`` to avoid confusion with', 'entry-point based scripts (defined in :pep:`621`).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'description': 'Whether the project can be safely installed and run from a zip file.', 'type': 'boolean'}, 'script-files': {'description': 'Legacy way of defining scripts (entry-points are preferred).', 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$ref': '#/definitions/package-name'}}, {'$ref': '#/definitions/find-directive'}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'const': ''}, {'$ref': '#/definitions/package-name'}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'data-files': {'$$description': ['**DEPRECATED**: dict-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', "Please notice this don't work with wheels. See `data files support", '`_'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['PROVISIONAL: List of glob patterns for all license files being distributed.', '(might become standard with PEP 639).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.'], 'oneOf': [{'$ref': '#/definitions/attr-directive'}, {'$ref': '#/definitions/file-directive'}]}, 'classifiers': {'$ref': '#/definitions/file-directive'}, 'description': {'$ref': '#/definitions/file-directive'}, 'dependencies': {'$ref': '#/definitions/file-directive'}, 'entry-points': {'$ref': '#/definitions/file-directive'}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$ref': '#/definitions/file-directive'}}}, 'readme': {'anyOf': [{'$ref': '#/definitions/file-directive'}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}}}, rule='type')
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".tool must be object", value=data__tool, name="" + (name_prefix or "data") + ".tool", definition={'type': 'object', 'properties': {'distutils': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html', 'title': '``tool.distutils`` table', '$$description': ['**EXPERIMENTAL** (NOT OFFICIALLY SUPPORTED): Use ``tool.distutils``', 'subtables to configure arguments for ``distutils`` commands.', 'Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` commands via `distutils configuration files', '`_.', 'See also `the old Python docs _`.'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, 'setuptools': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html', 'title': '``tool.setuptools`` table', '$$description': ['``setuptools``-specific configurations that can be set by users that require', 'customization.', 'These configurations are completely optional and probably can be skipped when', 'creating simple packages. They are equivalent to some of the `Keywords', '`_', 'used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.', 'It considers only ``setuptools`` `parameters', '`_', 'that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``', 'and ``setup_requires`` (incompatible with modern workflows/standards).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, 'script-files': {'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$ref': '#/definitions/package-name'}}, {'$ref': '#/definitions/find-directive'}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$ref': '#/definitions/package-name'}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'$ref': '#/definitions/package-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'$ref': '#/definitions/package-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'ext-modules': {'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$ref': '#/definitions/ext-module'}}, 'data-files': {'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'$ref': '#/definitions/attr-directive'}, {'$ref': '#/definitions/file-directive'}]}, 'classifiers': {'$ref': '#/definitions/file-directive'}, 'description': {'$ref': '#/definitions/file-directive'}, 'entry-points': {'$ref': '#/definitions/file-directive'}, 'dependencies': {'$ref': '#/definitions/file-directive-for-dependencies'}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$ref': '#/definitions/file-directive-for-dependencies'}}}, 'readme': {'type': 'object', 'anyOf': [{'$ref': '#/definitions/file-directive'}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'$ref': '#/definitions/file-directive/properties/file'}}, 'additionalProperties': False}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, 'ext-module': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'file-directive-for-dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}}}, rule='type')
             data__tool_is_dict = isinstance(data__tool, dict)
             if data__tool_is_dict:
                 data__tool_keys = set(data__tool.keys())
                 if "distutils" in data__tool_keys:
                     data__tool_keys.remove("distutils")
                     data__tool__distutils = data__tool["distutils"]
-                    validate_https___docs_python_org_3_install(data__tool__distutils, custom_formats, (name_prefix or "data") + ".tool.distutils")
+                    validate_https___setuptools_pypa_io_en_latest_deprecated_distutils_configfile_html(data__tool__distutils, custom_formats, (name_prefix or "data") + ".tool.distutils")
                 if "setuptools" in data__tool_keys:
                     data__tool_keys.remove("setuptools")
                     data__tool__setuptools = data__tool["setuptools"]
-                    validate_https___setuptools_pypa_io_en_latest_references_keywords_html(data__tool__setuptools, custom_formats, (name_prefix or "data") + ".tool.setuptools")
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html(data__tool__setuptools, custom_formats, (name_prefix or "data") + ".tool.setuptools")
+        if "dependency-groups" in data_keys:
+            data_keys.remove("dependency-groups")
+            data__dependencygroups = data["dependency-groups"]
+            if not isinstance(data__dependencygroups, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups must be object", value=data__dependencygroups, name="" + (name_prefix or "data") + ".dependency-groups", definition={'type': 'object', 'description': 'Dependency groups following PEP 735', 'additionalProperties': False, 'patternProperties': {'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$': {'type': 'array', 'items': {'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}}}}, rule='type')
+            data__dependencygroups_is_dict = isinstance(data__dependencygroups, dict)
+            if data__dependencygroups_is_dict:
+                data__dependencygroups_keys = set(data__dependencygroups.keys())
+                for data__dependencygroups_key, data__dependencygroups_val in data__dependencygroups.items():
+                    if REGEX_PATTERNS['^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'].search(data__dependencygroups_key):
+                        if data__dependencygroups_key in data__dependencygroups_keys:
+                            data__dependencygroups_keys.remove(data__dependencygroups_key)
+                        if not isinstance(data__dependencygroups_val, (list, tuple)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}".format(**locals()) + " must be array", value=data__dependencygroups_val, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}".format(**locals()) + "", definition={'type': 'array', 'items': {'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}}, rule='type')
+                        data__dependencygroups_val_is_list = isinstance(data__dependencygroups_val, (list, tuple))
+                        if data__dependencygroups_val_is_list:
+                            data__dependencygroups_val_len = len(data__dependencygroups_val)
+                            for data__dependencygroups_val_x, data__dependencygroups_val_item in enumerate(data__dependencygroups_val):
+                                data__dependencygroups_val_item_one_of_count1 = 0
+                                if data__dependencygroups_val_item_one_of_count1 < 2:
+                                    try:
+                                        if not isinstance(data__dependencygroups_val_item, (str)):
+                                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + " must be string", value=data__dependencygroups_val_item, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + "", definition={'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, rule='type')
+                                        if isinstance(data__dependencygroups_val_item, str):
+                                            if not custom_formats["pep508"](data__dependencygroups_val_item):
+                                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + " must be pep508", value=data__dependencygroups_val_item, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + "", definition={'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, rule='format')
+                                        data__dependencygroups_val_item_one_of_count1 += 1
+                                    except JsonSchemaValueException: pass
+                                if data__dependencygroups_val_item_one_of_count1 < 2:
+                                    try:
+                                        if not isinstance(data__dependencygroups_val_item, (dict)):
+                                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + " must be object", value=data__dependencygroups_val_item, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + "", definition={'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}, rule='type')
+                                        data__dependencygroups_val_item_is_dict = isinstance(data__dependencygroups_val_item, dict)
+                                        if data__dependencygroups_val_item_is_dict:
+                                            data__dependencygroups_val_item_keys = set(data__dependencygroups_val_item.keys())
+                                            if "include-group" in data__dependencygroups_val_item_keys:
+                                                data__dependencygroups_val_item_keys.remove("include-group")
+                                                data__dependencygroups_val_item__includegroup = data__dependencygroups_val_item["include-group"]
+                                                if not isinstance(data__dependencygroups_val_item__includegroup, (str)):
+                                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}].include-group".format(**locals()) + " must be string", value=data__dependencygroups_val_item__includegroup, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}].include-group".format(**locals()) + "", definition={'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}, rule='type')
+                                                if isinstance(data__dependencygroups_val_item__includegroup, str):
+                                                    if not REGEX_PATTERNS['^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'].search(data__dependencygroups_val_item__includegroup):
+                                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}].include-group".format(**locals()) + " must match pattern ^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$", value=data__dependencygroups_val_item__includegroup, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}].include-group".format(**locals()) + "", definition={'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}, rule='pattern')
+                                            if data__dependencygroups_val_item_keys:
+                                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + " must not contain "+str(data__dependencygroups_val_item_keys)+" properties", value=data__dependencygroups_val_item, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + "", definition={'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}, rule='additionalProperties')
+                                        data__dependencygroups_val_item_one_of_count1 += 1
+                                    except JsonSchemaValueException: pass
+                                if data__dependencygroups_val_item_one_of_count1 != 1:
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + " must be valid exactly by one definition" + (" (" + str(data__dependencygroups_val_item_one_of_count1) + " matches found)"), value=data__dependencygroups_val_item, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + "", definition={'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}, rule='oneOf')
+                if data__dependencygroups_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups must not contain "+str(data__dependencygroups_keys)+" properties", value=data__dependencygroups, name="" + (name_prefix or "data") + ".dependency-groups", definition={'type': 'object', 'description': 'Dependency groups following PEP 735', 'additionalProperties': False, 'patternProperties': {'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$': {'type': 'array', 'items': {'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}}}}, rule='additionalProperties')
         if data_keys:
-            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-build-dependencies/', 'title': 'Data structure for ``pyproject.toml`` files', '$$description': ['File format containing build-time configurations for the Python ecosystem. ', ':pep:`517` initially defined a build-system independent format for source trees', 'which was complemented by :pep:`518` to provide a way of specifying dependencies ', 'for building Python projects.', 'Please notice the ``project`` table (as initially defined in  :pep:`621`) is not included', 'in this schema and should be considered separately.'], 'type': 'object', 'additionalProperties': False, 'properties': {'build-system': {'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-project-metadata/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points `_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points `_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, 'tool': {'type': 'object', 'properties': {'distutils': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://docs.python.org/3/install/', 'title': '``tool.distutils`` table', '$$description': ['Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` scripts via `distutils configuration files', '`_.', '``tool.distutils`` subtables could be used with the same purpose', '(NOT CURRENTLY IMPLEMENTED).'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, 'setuptools': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://setuptools.pypa.io/en/latest/references/keywords.html', 'title': '``tool.setuptools`` table', '$$description': ['Please notice for the time being the ``setuptools`` project does not specify', 'a way of configuring builds via ``pyproject.toml``.', 'Therefore this schema should be taken just as a *"thought experiment"* on how', 'this *might be done*, by following the principles established in', '`ini2toml `_.', 'It considers only ``setuptools`` `parameters', '`_', 'that can currently be configured via ``setup.cfg`` and are not covered by :pep:`621`', 'but intentionally excludes ``dependency_links`` and ``setup_requires``.', 'NOTE: ``scripts`` was renamed to ``script-files`` to avoid confusion with', 'entry-point based scripts (defined in :pep:`621`).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'description': 'Whether the project can be safely installed and run from a zip file.', 'type': 'boolean'}, 'script-files': {'description': 'Legacy way of defining scripts (entry-points are preferred).', 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$ref': '#/definitions/package-name'}}, {'$ref': '#/definitions/find-directive'}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'const': ''}, {'$ref': '#/definitions/package-name'}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'data-files': {'$$description': ['**DEPRECATED**: dict-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', "Please notice this don't work with wheels. See `data files support", '`_'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['PROVISIONAL: List of glob patterns for all license files being distributed.', '(might become standard with PEP 639).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.'], 'oneOf': [{'$ref': '#/definitions/attr-directive'}, {'$ref': '#/definitions/file-directive'}]}, 'classifiers': {'$ref': '#/definitions/file-directive'}, 'description': {'$ref': '#/definitions/file-directive'}, 'dependencies': {'$ref': '#/definitions/file-directive'}, 'entry-points': {'$ref': '#/definitions/file-directive'}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$ref': '#/definitions/file-directive'}}}, 'readme': {'anyOf': [{'$ref': '#/definitions/file-directive'}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}}}}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-project-metadata/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points `_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points `_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='additionalProperties')
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-build-dependencies/', 'title': 'Data structure for ``pyproject.toml`` files', '$$description': ['File format containing build-time configurations for the Python ecosystem. ', ':pep:`517` initially defined a build-system independent format for source trees', 'which was complemented by :pep:`518` to provide a way of specifying dependencies ', 'for building Python projects.', 'Please notice the ``project`` table (as initially defined in  :pep:`621`) is not included', 'in this schema and should be considered separately.'], 'type': 'object', 'additionalProperties': False, 'properties': {'build-system': {'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points `_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points `_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'import-names': {'description': 'Lists import names which a project, when installed, would exclusively provide.', 'type': 'array', 'items': {'type': 'string', 'format': 'import-name'}}, 'import-namespaces': {'description': 'Lists import names that, when installed, would be provided by the project, but not exclusively.', 'type': 'array', 'items': {'type': 'string', 'format': 'import-name'}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies', 'import-names', 'import-namespaces']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, 'tool': {'type': 'object', 'properties': {'distutils': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html', 'title': '``tool.distutils`` table', '$$description': ['**EXPERIMENTAL** (NOT OFFICIALLY SUPPORTED): Use ``tool.distutils``', 'subtables to configure arguments for ``distutils`` commands.', 'Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` commands via `distutils configuration files', '`_.', 'See also `the old Python docs _`.'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, 'setuptools': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html', 'title': '``tool.setuptools`` table', '$$description': ['``setuptools``-specific configurations that can be set by users that require', 'customization.', 'These configurations are completely optional and probably can be skipped when', 'creating simple packages. They are equivalent to some of the `Keywords', '`_', 'used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.', 'It considers only ``setuptools`` `parameters', '`_', 'that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``', 'and ``setup_requires`` (incompatible with modern workflows/standards).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, 'script-files': {'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$ref': '#/definitions/package-name'}}, {'$ref': '#/definitions/find-directive'}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$ref': '#/definitions/package-name'}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'$ref': '#/definitions/package-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'$ref': '#/definitions/package-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'ext-modules': {'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$ref': '#/definitions/ext-module'}}, 'data-files': {'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'$ref': '#/definitions/attr-directive'}, {'$ref': '#/definitions/file-directive'}]}, 'classifiers': {'$ref': '#/definitions/file-directive'}, 'description': {'$ref': '#/definitions/file-directive'}, 'entry-points': {'$ref': '#/definitions/file-directive'}, 'dependencies': {'$ref': '#/definitions/file-directive-for-dependencies'}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$ref': '#/definitions/file-directive-for-dependencies'}}}, 'readme': {'type': 'object', 'anyOf': [{'$ref': '#/definitions/file-directive'}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'$ref': '#/definitions/file-directive/properties/file'}}, 'additionalProperties': False}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, 'ext-module': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'file-directive-for-dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}}}, 'dependency-groups': {'type': 'object', 'description': 'Dependency groups following PEP 735', 'additionalProperties': False, 'patternProperties': {'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$': {'type': 'array', 'items': {'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}}}}}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points `_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points `_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'import-names': {'description': 'Lists import names which a project, when installed, would exclusively provide.', 'type': 'array', 'items': {'type': 'string', 'format': 'import-name'}}, 'import-namespaces': {'description': 'Lists import names that, when installed, would be provided by the project, but not exclusively.', 'type': 'array', 'items': {'type': 'string', 'format': 'import-name'}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies', 'import-names', 'import-namespaces']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='additionalProperties')
     return data
 
-def validate_https___setuptools_pypa_io_en_latest_references_keywords_html(data, custom_formats={}, name_prefix=None):
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html(data, custom_formats={}, name_prefix=None):
     if not isinstance(data, (dict)):
-        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://setuptools.pypa.io/en/latest/references/keywords.html', 'title': '``tool.setuptools`` table', '$$description': ['Please notice for the time being the ``setuptools`` project does not specify', 'a way of configuring builds via ``pyproject.toml``.', 'Therefore this schema should be taken just as a *"thought experiment"* on how', 'this *might be done*, by following the principles established in', '`ini2toml `_.', 'It considers only ``setuptools`` `parameters', '`_', 'that can currently be configured via ``setup.cfg`` and are not covered by :pep:`621`', 'but intentionally excludes ``dependency_links`` and ``setup_requires``.', 'NOTE: ``scripts`` was renamed to ``script-files`` to avoid confusion with', 'entry-point based scripts (defined in :pep:`621`).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'description': 'Whether the project can be safely installed and run from a zip file.', 'type': 'boolean'}, 'script-files': {'description': 'Legacy way of defining scripts (entry-points are preferred).', 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}}, {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'data-files': {'$$description': ['**DEPRECATED**: dict-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', "Please notice this don't work with wheels. See `data files support", '`_'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['PROVISIONAL: List of glob patterns for all license files being distributed.', '(might become standard with PEP 639).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}}}, 'readme': {'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}, rule='type')
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html', 'title': '``tool.setuptools`` table', '$$description': ['``setuptools``-specific configurations that can be set by users that require', 'customization.', 'These configurations are completely optional and probably can be skipped when', 'creating simple packages. They are equivalent to some of the `Keywords', '`_', 'used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.', 'It considers only ``setuptools`` `parameters', '`_', 'that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``', 'and ``setup_requires`` (incompatible with modern workflows/standards).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, 'script-files': {'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}}, {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'ext-modules': {'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}}, 'data-files': {'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, 'readme': {'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, 'ext-module': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'file-directive-for-dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}, rule='type')
     data_is_dict = isinstance(data, dict)
     if data_is_dict:
         data_keys = set(data.keys())
@@ -150,12 +203,12 @@ def validate_https___setuptools_pypa_io_en_latest_references_keywords_html(data,
             data_keys.remove("zip-safe")
             data__zipsafe = data["zip-safe"]
             if not isinstance(data__zipsafe, (bool)):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".zip-safe must be boolean", value=data__zipsafe, name="" + (name_prefix or "data") + ".zip-safe", definition={'description': 'Whether the project can be safely installed and run from a zip file.', 'type': 'boolean'}, rule='type')
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".zip-safe must be boolean", value=data__zipsafe, name="" + (name_prefix or "data") + ".zip-safe", definition={'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, rule='type')
         if "script-files" in data_keys:
             data_keys.remove("script-files")
             data__scriptfiles = data["script-files"]
             if not isinstance(data__scriptfiles, (list, tuple)):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".script-files must be array", value=data__scriptfiles, name="" + (name_prefix or "data") + ".script-files", definition={'description': 'Legacy way of defining scripts (entry-points are preferred).', 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, rule='type')
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".script-files must be array", value=data__scriptfiles, name="" + (name_prefix or "data") + ".script-files", definition={'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, rule='type')
             data__scriptfiles_is_list = isinstance(data__scriptfiles, (list, tuple))
             if data__scriptfiles_is_list:
                 data__scriptfiles_len = len(data__scriptfiles)
@@ -166,7 +219,7 @@ def validate_https___setuptools_pypa_io_en_latest_references_keywords_html(data,
             data_keys.remove("eager-resources")
             data__eagerresources = data["eager-resources"]
             if not isinstance(data__eagerresources, (list, tuple)):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".eager-resources must be array", value=data__eagerresources, name="" + (name_prefix or "data") + ".eager-resources", definition={'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.'], 'type': 'array', 'items': {'type': 'string'}}, rule='type')
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".eager-resources must be array", value=data__eagerresources, name="" + (name_prefix or "data") + ".eager-resources", definition={'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, rule='type')
             data__eagerresources_is_list = isinstance(data__eagerresources, (list, tuple))
             if data__eagerresources_is_list:
                 data__eagerresources_len = len(data__eagerresources)
@@ -176,30 +229,30 @@ def validate_https___setuptools_pypa_io_en_latest_references_keywords_html(data,
         if "packages" in data_keys:
             data_keys.remove("packages")
             data__packages = data["packages"]
-            data__packages_one_of_count1 = 0
-            if data__packages_one_of_count1 < 2:
+            data__packages_one_of_count2 = 0
+            if data__packages_one_of_count2 < 2:
                 try:
                     if not isinstance(data__packages, (list, tuple)):
-                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".packages must be array", value=data__packages, name="" + (name_prefix or "data") + ".packages", definition={'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}}, rule='type')
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".packages must be array", value=data__packages, name="" + (name_prefix or "data") + ".packages", definition={'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}}, rule='type')
                     data__packages_is_list = isinstance(data__packages, (list, tuple))
                     if data__packages_is_list:
                         data__packages_len = len(data__packages)
                         for data__packages_x, data__packages_item in enumerate(data__packages):
-                            validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_package_name(data__packages_item, custom_formats, (name_prefix or "data") + ".packages[{data__packages_x}]".format(**locals()))
-                    data__packages_one_of_count1 += 1
+                            validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_package_name(data__packages_item, custom_formats, (name_prefix or "data") + ".packages[{data__packages_x}]".format(**locals()))
+                    data__packages_one_of_count2 += 1
                 except JsonSchemaValueException: pass
-            if data__packages_one_of_count1 < 2:
+            if data__packages_one_of_count2 < 2:
                 try:
-                    validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_find_directive(data__packages, custom_formats, (name_prefix or "data") + ".packages")
-                    data__packages_one_of_count1 += 1
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_find_directive(data__packages, custom_formats, (name_prefix or "data") + ".packages")
+                    data__packages_one_of_count2 += 1
                 except JsonSchemaValueException: pass
-            if data__packages_one_of_count1 != 1:
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".packages must be valid exactly by one definition" + (" (" + str(data__packages_one_of_count1) + " matches found)"), value=data__packages, name="" + (name_prefix or "data") + ".packages", definition={'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}}, {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}]}, rule='oneOf')
+            if data__packages_one_of_count2 != 1:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".packages must be valid exactly by one definition" + (" (" + str(data__packages_one_of_count2) + " matches found)"), value=data__packages, name="" + (name_prefix or "data") + ".packages", definition={'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}}, {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}]}, rule='oneOf')
         if "package-dir" in data_keys:
             data_keys.remove("package-dir")
             data__packagedir = data["package-dir"]
             if not isinstance(data__packagedir, (dict)):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir must be object", value=data__packagedir, name="" + (name_prefix or "data") + ".package-dir", definition={'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, rule='type')
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir must be object", value=data__packagedir, name="" + (name_prefix or "data") + ".package-dir", definition={'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, rule='type')
             data__packagedir_is_dict = isinstance(data__packagedir, dict)
             if data__packagedir_is_dict:
                 data__packagedir_keys = set(data__packagedir.keys())
@@ -210,35 +263,35 @@ def validate_https___setuptools_pypa_io_en_latest_references_keywords_html(data,
                         if not isinstance(data__packagedir_val, (str)):
                             raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir.{data__packagedir_key}".format(**locals()) + " must be string", value=data__packagedir_val, name="" + (name_prefix or "data") + ".package-dir.{data__packagedir_key}".format(**locals()) + "", definition={'type': 'string'}, rule='type')
                 if data__packagedir_keys:
-                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir must not contain "+str(data__packagedir_keys)+" properties", value=data__packagedir, name="" + (name_prefix or "data") + ".package-dir", definition={'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, rule='additionalProperties')
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir must not contain "+str(data__packagedir_keys)+" properties", value=data__packagedir, name="" + (name_prefix or "data") + ".package-dir", definition={'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, rule='additionalProperties')
                 data__packagedir_len = len(data__packagedir)
                 if data__packagedir_len != 0:
                     data__packagedir_property_names = True
                     for data__packagedir_key in data__packagedir:
                         try:
-                            data__packagedir_key_one_of_count2 = 0
-                            if data__packagedir_key_one_of_count2 < 2:
+                            data__packagedir_key_any_of_count3 = 0
+                            if not data__packagedir_key_any_of_count3:
                                 try:
                                     if data__packagedir_key != "":
                                         raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir must be same as const definition: ", value=data__packagedir_key, name="" + (name_prefix or "data") + ".package-dir", definition={'const': ''}, rule='const')
-                                    data__packagedir_key_one_of_count2 += 1
+                                    data__packagedir_key_any_of_count3 += 1
                                 except JsonSchemaValueException: pass
-                            if data__packagedir_key_one_of_count2 < 2:
+                            if not data__packagedir_key_any_of_count3:
                                 try:
-                                    validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_package_name(data__packagedir_key, custom_formats, (name_prefix or "data") + ".package-dir")
-                                    data__packagedir_key_one_of_count2 += 1
+                                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_package_name(data__packagedir_key, custom_formats, (name_prefix or "data") + ".package-dir")
+                                    data__packagedir_key_any_of_count3 += 1
                                 except JsonSchemaValueException: pass
-                            if data__packagedir_key_one_of_count2 != 1:
-                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir must be valid exactly by one definition" + (" (" + str(data__packagedir_key_one_of_count2) + " matches found)"), value=data__packagedir_key, name="" + (name_prefix or "data") + ".package-dir", definition={'oneOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}]}, rule='oneOf')
+                            if not data__packagedir_key_any_of_count3:
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir cannot be validated by any definition", value=data__packagedir_key, name="" + (name_prefix or "data") + ".package-dir", definition={'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, rule='anyOf')
                         except JsonSchemaValueException:
                             data__packagedir_property_names = False
                     if not data__packagedir_property_names:
-                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir must be named by propertyName definition", value=data__packagedir, name="" + (name_prefix or "data") + ".package-dir", definition={'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, rule='propertyNames')
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir must be named by propertyName definition", value=data__packagedir, name="" + (name_prefix or "data") + ".package-dir", definition={'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, rule='propertyNames')
         if "package-data" in data_keys:
             data_keys.remove("package-data")
             data__packagedata = data["package-data"]
             if not isinstance(data__packagedata, (dict)):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be object", value=data__packagedata, name="" + (name_prefix or "data") + ".package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='type')
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be object", value=data__packagedata, name="" + (name_prefix or "data") + ".package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='type')
             data__packagedata_is_dict = isinstance(data__packagedata, dict)
             if data__packagedata_is_dict:
                 data__packagedata_keys = set(data__packagedata.keys())
@@ -255,32 +308,30 @@ def validate_https___setuptools_pypa_io_en_latest_references_keywords_html(data,
                                 if not isinstance(data__packagedata_val_item, (str)):
                                     raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data.{data__packagedata_key}[{data__packagedata_val_x}]".format(**locals()) + " must be string", value=data__packagedata_val_item, name="" + (name_prefix or "data") + ".package-data.{data__packagedata_key}[{data__packagedata_val_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
                 if data__packagedata_keys:
-                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must not contain "+str(data__packagedata_keys)+" properties", value=data__packagedata, name="" + (name_prefix or "data") + ".package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='additionalProperties')
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must not contain "+str(data__packagedata_keys)+" properties", value=data__packagedata, name="" + (name_prefix or "data") + ".package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='additionalProperties')
                 data__packagedata_len = len(data__packagedata)
                 if data__packagedata_len != 0:
                     data__packagedata_property_names = True
                     for data__packagedata_key in data__packagedata:
                         try:
-                            data__packagedata_key_one_of_count3 = 0
-                            if data__packagedata_key_one_of_count3 < 2:
+                            data__packagedata_key_any_of_count4 = 0
+                            if not data__packagedata_key_any_of_count4:
                                 try:
-                                    if isinstance(data__packagedata_key, str):
-                                        if not custom_formats["python-module-name"](data__packagedata_key):
-                                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be python-module-name", value=data__packagedata_key, name="" + (name_prefix or "data") + ".package-data", definition={'format': 'python-module-name'}, rule='format')
-                                    data__packagedata_key_one_of_count3 += 1
+                                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_package_name(data__packagedata_key, custom_formats, (name_prefix or "data") + ".package-data")
+                                    data__packagedata_key_any_of_count4 += 1
                                 except JsonSchemaValueException: pass
-                            if data__packagedata_key_one_of_count3 < 2:
+                            if not data__packagedata_key_any_of_count4:
                                 try:
                                     if data__packagedata_key != "*":
                                         raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be same as const definition: *", value=data__packagedata_key, name="" + (name_prefix or "data") + ".package-data", definition={'const': '*'}, rule='const')
-                                    data__packagedata_key_one_of_count3 += 1
+                                    data__packagedata_key_any_of_count4 += 1
                                 except JsonSchemaValueException: pass
-                            if data__packagedata_key_one_of_count3 != 1:
-                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be valid exactly by one definition" + (" (" + str(data__packagedata_key_one_of_count3) + " matches found)"), value=data__packagedata_key, name="" + (name_prefix or "data") + ".package-data", definition={'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, rule='oneOf')
+                            if not data__packagedata_key_any_of_count4:
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data cannot be validated by any definition", value=data__packagedata_key, name="" + (name_prefix or "data") + ".package-data", definition={'anyOf': [{'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, {'const': '*'}]}, rule='anyOf')
                         except JsonSchemaValueException:
                             data__packagedata_property_names = False
                     if not data__packagedata_property_names:
-                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be named by propertyName definition", value=data__packagedata, name="" + (name_prefix or "data") + ".package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='propertyNames')
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be named by propertyName definition", value=data__packagedata, name="" + (name_prefix or "data") + ".package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='propertyNames')
         if "include-package-data" in data_keys:
             data_keys.remove("include-package-data")
             data__includepackagedata = data["include-package-data"]
@@ -290,7 +341,7 @@ def validate_https___setuptools_pypa_io_en_latest_references_keywords_html(data,
             data_keys.remove("exclude-package-data")
             data__excludepackagedata = data["exclude-package-data"]
             if not isinstance(data__excludepackagedata, (dict)):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be object", value=data__excludepackagedata, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='type')
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be object", value=data__excludepackagedata, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='type')
             data__excludepackagedata_is_dict = isinstance(data__excludepackagedata, dict)
             if data__excludepackagedata_is_dict:
                 data__excludepackagedata_keys = set(data__excludepackagedata.keys())
@@ -307,65 +358,73 @@ def validate_https___setuptools_pypa_io_en_latest_references_keywords_html(data,
                                 if not isinstance(data__excludepackagedata_val_item, (str)):
                                     raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data.{data__excludepackagedata_key}[{data__excludepackagedata_val_x}]".format(**locals()) + " must be string", value=data__excludepackagedata_val_item, name="" + (name_prefix or "data") + ".exclude-package-data.{data__excludepackagedata_key}[{data__excludepackagedata_val_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
                 if data__excludepackagedata_keys:
-                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must not contain "+str(data__excludepackagedata_keys)+" properties", value=data__excludepackagedata, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='additionalProperties')
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must not contain "+str(data__excludepackagedata_keys)+" properties", value=data__excludepackagedata, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='additionalProperties')
                 data__excludepackagedata_len = len(data__excludepackagedata)
                 if data__excludepackagedata_len != 0:
                     data__excludepackagedata_property_names = True
                     for data__excludepackagedata_key in data__excludepackagedata:
                         try:
-                            data__excludepackagedata_key_one_of_count4 = 0
-                            if data__excludepackagedata_key_one_of_count4 < 2:
+                            data__excludepackagedata_key_any_of_count5 = 0
+                            if not data__excludepackagedata_key_any_of_count5:
                                 try:
-                                    if isinstance(data__excludepackagedata_key, str):
-                                        if not custom_formats["python-module-name"](data__excludepackagedata_key):
-                                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be python-module-name", value=data__excludepackagedata_key, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'format': 'python-module-name'}, rule='format')
-                                    data__excludepackagedata_key_one_of_count4 += 1
+                                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_package_name(data__excludepackagedata_key, custom_formats, (name_prefix or "data") + ".exclude-package-data")
+                                    data__excludepackagedata_key_any_of_count5 += 1
                                 except JsonSchemaValueException: pass
-                            if data__excludepackagedata_key_one_of_count4 < 2:
+                            if not data__excludepackagedata_key_any_of_count5:
                                 try:
                                     if data__excludepackagedata_key != "*":
                                         raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be same as const definition: *", value=data__excludepackagedata_key, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'const': '*'}, rule='const')
-                                    data__excludepackagedata_key_one_of_count4 += 1
+                                    data__excludepackagedata_key_any_of_count5 += 1
                                 except JsonSchemaValueException: pass
-                            if data__excludepackagedata_key_one_of_count4 != 1:
-                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be valid exactly by one definition" + (" (" + str(data__excludepackagedata_key_one_of_count4) + " matches found)"), value=data__excludepackagedata_key, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, rule='oneOf')
+                            if not data__excludepackagedata_key_any_of_count5:
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data cannot be validated by any definition", value=data__excludepackagedata_key, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'anyOf': [{'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, {'const': '*'}]}, rule='anyOf')
                         except JsonSchemaValueException:
                             data__excludepackagedata_property_names = False
                     if not data__excludepackagedata_property_names:
-                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be named by propertyName definition", value=data__excludepackagedata, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='propertyNames')
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be named by propertyName definition", value=data__excludepackagedata, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='propertyNames')
         if "namespace-packages" in data_keys:
             data_keys.remove("namespace-packages")
             data__namespacepackages = data["namespace-packages"]
             if not isinstance(data__namespacepackages, (list, tuple)):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".namespace-packages must be array", value=data__namespacepackages, name="" + (name_prefix or "data") + ".namespace-packages", definition={'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html'}, rule='type')
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".namespace-packages must be array", value=data__namespacepackages, name="" + (name_prefix or "data") + ".namespace-packages", definition={'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, rule='type')
             data__namespacepackages_is_list = isinstance(data__namespacepackages, (list, tuple))
             if data__namespacepackages_is_list:
                 data__namespacepackages_len = len(data__namespacepackages)
                 for data__namespacepackages_x, data__namespacepackages_item in enumerate(data__namespacepackages):
                     if not isinstance(data__namespacepackages_item, (str)):
-                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".namespace-packages[{data__namespacepackages_x}]".format(**locals()) + " must be string", value=data__namespacepackages_item, name="" + (name_prefix or "data") + ".namespace-packages[{data__namespacepackages_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'python-module-name'}, rule='type')
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".namespace-packages[{data__namespacepackages_x}]".format(**locals()) + " must be string", value=data__namespacepackages_item, name="" + (name_prefix or "data") + ".namespace-packages[{data__namespacepackages_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='type')
                     if isinstance(data__namespacepackages_item, str):
-                        if not custom_formats["python-module-name"](data__namespacepackages_item):
-                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".namespace-packages[{data__namespacepackages_x}]".format(**locals()) + " must be python-module-name", value=data__namespacepackages_item, name="" + (name_prefix or "data") + ".namespace-packages[{data__namespacepackages_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'python-module-name'}, rule='format')
+                        if not custom_formats["python-module-name-relaxed"](data__namespacepackages_item):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".namespace-packages[{data__namespacepackages_x}]".format(**locals()) + " must be python-module-name-relaxed", value=data__namespacepackages_item, name="" + (name_prefix or "data") + ".namespace-packages[{data__namespacepackages_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='format')
         if "py-modules" in data_keys:
             data_keys.remove("py-modules")
             data__pymodules = data["py-modules"]
             if not isinstance(data__pymodules, (list, tuple)):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".py-modules must be array", value=data__pymodules, name="" + (name_prefix or "data") + ".py-modules", definition={'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, rule='type')
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".py-modules must be array", value=data__pymodules, name="" + (name_prefix or "data") + ".py-modules", definition={'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, rule='type')
             data__pymodules_is_list = isinstance(data__pymodules, (list, tuple))
             if data__pymodules_is_list:
                 data__pymodules_len = len(data__pymodules)
                 for data__pymodules_x, data__pymodules_item in enumerate(data__pymodules):
                     if not isinstance(data__pymodules_item, (str)):
-                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".py-modules[{data__pymodules_x}]".format(**locals()) + " must be string", value=data__pymodules_item, name="" + (name_prefix or "data") + ".py-modules[{data__pymodules_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'python-module-name'}, rule='type')
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".py-modules[{data__pymodules_x}]".format(**locals()) + " must be string", value=data__pymodules_item, name="" + (name_prefix or "data") + ".py-modules[{data__pymodules_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='type')
                     if isinstance(data__pymodules_item, str):
-                        if not custom_formats["python-module-name"](data__pymodules_item):
-                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".py-modules[{data__pymodules_x}]".format(**locals()) + " must be python-module-name", value=data__pymodules_item, name="" + (name_prefix or "data") + ".py-modules[{data__pymodules_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'python-module-name'}, rule='format')
+                        if not custom_formats["python-module-name-relaxed"](data__pymodules_item):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".py-modules[{data__pymodules_x}]".format(**locals()) + " must be python-module-name-relaxed", value=data__pymodules_item, name="" + (name_prefix or "data") + ".py-modules[{data__pymodules_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='format')
+        if "ext-modules" in data_keys:
+            data_keys.remove("ext-modules")
+            data__extmodules = data["ext-modules"]
+            if not isinstance(data__extmodules, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".ext-modules must be array", value=data__extmodules, name="" + (name_prefix or "data") + ".ext-modules", definition={'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}}, rule='type')
+            data__extmodules_is_list = isinstance(data__extmodules, (list, tuple))
+            if data__extmodules_is_list:
+                data__extmodules_len = len(data__extmodules)
+                for data__extmodules_x, data__extmodules_item in enumerate(data__extmodules):
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_ext_module(data__extmodules_item, custom_formats, (name_prefix or "data") + ".ext-modules[{data__extmodules_x}]".format(**locals()))
         if "data-files" in data_keys:
             data_keys.remove("data-files")
             data__datafiles = data["data-files"]
             if not isinstance(data__datafiles, (dict)):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".data-files must be object", value=data__datafiles, name="" + (name_prefix or "data") + ".data-files", definition={'$$description': ['**DEPRECATED**: dict-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', "Please notice this don't work with wheels. See `data files support", '`_'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='type')
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".data-files must be object", value=data__datafiles, name="" + (name_prefix or "data") + ".data-files", definition={'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='type')
             data__datafiles_is_dict = isinstance(data__datafiles, dict)
             if data__datafiles_is_dict:
                 data__datafiles_keys = set(data__datafiles.keys())
@@ -402,7 +461,7 @@ def validate_https___setuptools_pypa_io_en_latest_references_keywords_html(data,
             data_keys.remove("license-files")
             data__licensefiles = data["license-files"]
             if not isinstance(data__licensefiles, (list, tuple)):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".license-files must be array", value=data__licensefiles, name="" + (name_prefix or "data") + ".license-files", definition={'type': 'array', 'items': {'type': 'string'}, '$$description': ['PROVISIONAL: List of glob patterns for all license files being distributed.', '(might become standard with PEP 639).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, rule='type')
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".license-files must be array", value=data__licensefiles, name="" + (name_prefix or "data") + ".license-files", definition={'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, rule='type')
             data__licensefiles_is_list = isinstance(data__licensefiles, (list, tuple))
             if data__licensefiles_is_list:
                 data__licensefiles_len = len(data__licensefiles)
@@ -413,47 +472,47 @@ def validate_https___setuptools_pypa_io_en_latest_references_keywords_html(data,
             data_keys.remove("dynamic")
             data__dynamic = data["dynamic"]
             if not isinstance(data__dynamic, (dict)):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must be object", value=data__dynamic, name="" + (name_prefix or "data") + ".dynamic", definition={'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}}}, 'readme': {'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}}}, rule='type')
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must be object", value=data__dynamic, name="" + (name_prefix or "data") + ".dynamic", definition={'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, 'readme': {'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}}}, rule='type')
             data__dynamic_is_dict = isinstance(data__dynamic, dict)
             if data__dynamic_is_dict:
                 data__dynamic_keys = set(data__dynamic.keys())
                 if "version" in data__dynamic_keys:
                     data__dynamic_keys.remove("version")
                     data__dynamic__version = data__dynamic["version"]
-                    data__dynamic__version_one_of_count5 = 0
-                    if data__dynamic__version_one_of_count5 < 2:
+                    data__dynamic__version_one_of_count6 = 0
+                    if data__dynamic__version_one_of_count6 < 2:
                         try:
-                            validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_attr_directive(data__dynamic__version, custom_formats, (name_prefix or "data") + ".dynamic.version")
-                            data__dynamic__version_one_of_count5 += 1
+                            validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_attr_directive(data__dynamic__version, custom_formats, (name_prefix or "data") + ".dynamic.version")
+                            data__dynamic__version_one_of_count6 += 1
                         except JsonSchemaValueException: pass
-                    if data__dynamic__version_one_of_count5 < 2:
+                    if data__dynamic__version_one_of_count6 < 2:
                         try:
-                            validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_file_directive(data__dynamic__version, custom_formats, (name_prefix or "data") + ".dynamic.version")
-                            data__dynamic__version_one_of_count5 += 1
+                            validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data__dynamic__version, custom_formats, (name_prefix or "data") + ".dynamic.version")
+                            data__dynamic__version_one_of_count6 += 1
                         except JsonSchemaValueException: pass
-                    if data__dynamic__version_one_of_count5 != 1:
-                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.version must be valid exactly by one definition" + (" (" + str(data__dynamic__version_one_of_count5) + " matches found)"), value=data__dynamic__version, name="" + (name_prefix or "data") + ".dynamic.version", definition={'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, rule='oneOf')
+                    if data__dynamic__version_one_of_count6 != 1:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.version must be valid exactly by one definition" + (" (" + str(data__dynamic__version_one_of_count6) + " matches found)"), value=data__dynamic__version, name="" + (name_prefix or "data") + ".dynamic.version", definition={'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, rule='oneOf')
                 if "classifiers" in data__dynamic_keys:
                     data__dynamic_keys.remove("classifiers")
                     data__dynamic__classifiers = data__dynamic["classifiers"]
-                    validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_file_directive(data__dynamic__classifiers, custom_formats, (name_prefix or "data") + ".dynamic.classifiers")
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data__dynamic__classifiers, custom_formats, (name_prefix or "data") + ".dynamic.classifiers")
                 if "description" in data__dynamic_keys:
                     data__dynamic_keys.remove("description")
                     data__dynamic__description = data__dynamic["description"]
-                    validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_file_directive(data__dynamic__description, custom_formats, (name_prefix or "data") + ".dynamic.description")
-                if "dependencies" in data__dynamic_keys:
-                    data__dynamic_keys.remove("dependencies")
-                    data__dynamic__dependencies = data__dynamic["dependencies"]
-                    validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_file_directive(data__dynamic__dependencies, custom_formats, (name_prefix or "data") + ".dynamic.dependencies")
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data__dynamic__description, custom_formats, (name_prefix or "data") + ".dynamic.description")
                 if "entry-points" in data__dynamic_keys:
                     data__dynamic_keys.remove("entry-points")
                     data__dynamic__entrypoints = data__dynamic["entry-points"]
-                    validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_file_directive(data__dynamic__entrypoints, custom_formats, (name_prefix or "data") + ".dynamic.entry-points")
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data__dynamic__entrypoints, custom_formats, (name_prefix or "data") + ".dynamic.entry-points")
+                if "dependencies" in data__dynamic_keys:
+                    data__dynamic_keys.remove("dependencies")
+                    data__dynamic__dependencies = data__dynamic["dependencies"]
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive_for_dependencies(data__dynamic__dependencies, custom_formats, (name_prefix or "data") + ".dynamic.dependencies")
                 if "optional-dependencies" in data__dynamic_keys:
                     data__dynamic_keys.remove("optional-dependencies")
                     data__dynamic__optionaldependencies = data__dynamic["optional-dependencies"]
                     if not isinstance(data__dynamic__optionaldependencies, (dict)):
-                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must be object", value=data__dynamic__optionaldependencies, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}}}, rule='type')
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must be object", value=data__dynamic__optionaldependencies, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, rule='type')
                     data__dynamic__optionaldependencies_is_dict = isinstance(data__dynamic__optionaldependencies, dict)
                     if data__dynamic__optionaldependencies_is_dict:
                         data__dynamic__optionaldependencies_keys = set(data__dynamic__optionaldependencies.keys())
@@ -461,32 +520,38 @@ def validate_https___setuptools_pypa_io_en_latest_references_keywords_html(data,
                             if REGEX_PATTERNS['.+'].search(data__dynamic__optionaldependencies_key):
                                 if data__dynamic__optionaldependencies_key in data__dynamic__optionaldependencies_keys:
                                     data__dynamic__optionaldependencies_keys.remove(data__dynamic__optionaldependencies_key)
-                                validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_file_directive(data__dynamic__optionaldependencies_val, custom_formats, (name_prefix or "data") + ".dynamic.optional-dependencies.{data__dynamic__optionaldependencies_key}".format(**locals()))
+                                validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive_for_dependencies(data__dynamic__optionaldependencies_val, custom_formats, (name_prefix or "data") + ".dynamic.optional-dependencies.{data__dynamic__optionaldependencies_key}".format(**locals()))
                         if data__dynamic__optionaldependencies_keys:
-                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must not contain "+str(data__dynamic__optionaldependencies_keys)+" properties", value=data__dynamic__optionaldependencies, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}}}, rule='additionalProperties')
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must not contain "+str(data__dynamic__optionaldependencies_keys)+" properties", value=data__dynamic__optionaldependencies, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, rule='additionalProperties')
                         data__dynamic__optionaldependencies_len = len(data__dynamic__optionaldependencies)
                         if data__dynamic__optionaldependencies_len != 0:
                             data__dynamic__optionaldependencies_property_names = True
                             for data__dynamic__optionaldependencies_key in data__dynamic__optionaldependencies:
                                 try:
+                                    if not isinstance(data__dynamic__optionaldependencies_key, (str)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must be string", value=data__dynamic__optionaldependencies_key, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='type')
                                     if isinstance(data__dynamic__optionaldependencies_key, str):
-                                        if not custom_formats["python-identifier"](data__dynamic__optionaldependencies_key):
-                                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must be python-identifier", value=data__dynamic__optionaldependencies_key, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'format': 'python-identifier'}, rule='format')
+                                        if not custom_formats["pep508-identifier"](data__dynamic__optionaldependencies_key):
+                                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must be pep508-identifier", value=data__dynamic__optionaldependencies_key, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='format')
                                 except JsonSchemaValueException:
                                     data__dynamic__optionaldependencies_property_names = False
                             if not data__dynamic__optionaldependencies_property_names:
-                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must be named by propertyName definition", value=data__dynamic__optionaldependencies, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}}}, rule='propertyNames')
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must be named by propertyName definition", value=data__dynamic__optionaldependencies, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, rule='propertyNames')
                 if "readme" in data__dynamic_keys:
                     data__dynamic_keys.remove("readme")
                     data__dynamic__readme = data__dynamic["readme"]
-                    data__dynamic__readme_any_of_count6 = 0
-                    if not data__dynamic__readme_any_of_count6:
+                    if not isinstance(data__dynamic__readme, (dict)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme must be object", value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}, rule='type')
+                    data__dynamic__readme_any_of_count7 = 0
+                    if not data__dynamic__readme_any_of_count7:
                         try:
-                            validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_file_directive(data__dynamic__readme, custom_formats, (name_prefix or "data") + ".dynamic.readme")
-                            data__dynamic__readme_any_of_count6 += 1
+                            validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data__dynamic__readme, custom_formats, (name_prefix or "data") + ".dynamic.readme")
+                            data__dynamic__readme_any_of_count7 += 1
                         except JsonSchemaValueException: pass
-                    if not data__dynamic__readme_any_of_count6:
+                    if not data__dynamic__readme_any_of_count7:
                         try:
+                            if not isinstance(data__dynamic__readme, (dict)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme must be object", value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}, rule='type')
                             data__dynamic__readme_is_dict = isinstance(data__dynamic__readme, dict)
                             if data__dynamic__readme_is_dict:
                                 data__dynamic__readme_keys = set(data__dynamic__readme.keys())
@@ -495,41 +560,75 @@ def validate_https___setuptools_pypa_io_en_latest_references_keywords_html(data,
                                     data__dynamic__readme__contenttype = data__dynamic__readme["content-type"]
                                     if not isinstance(data__dynamic__readme__contenttype, (str)):
                                         raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme.content-type must be string", value=data__dynamic__readme__contenttype, name="" + (name_prefix or "data") + ".dynamic.readme.content-type", definition={'type': 'string'}, rule='type')
-                            data__dynamic__readme_any_of_count6 += 1
+                                if "file" in data__dynamic__readme_keys:
+                                    data__dynamic__readme_keys.remove("file")
+                                    data__dynamic__readme__file = data__dynamic__readme["file"]
+                                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive_properties_file(data__dynamic__readme__file, custom_formats, (name_prefix or "data") + ".dynamic.readme.file")
+                                if data__dynamic__readme_keys:
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme must not contain "+str(data__dynamic__readme_keys)+" properties", value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}, rule='additionalProperties')
+                            data__dynamic__readme_any_of_count7 += 1
                         except JsonSchemaValueException: pass
-                    if not data__dynamic__readme_any_of_count6:
-                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme cannot be validated by any definition", value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}, rule='anyOf')
+                    if not data__dynamic__readme_any_of_count7:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme cannot be validated by any definition", value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}, rule='anyOf')
                     data__dynamic__readme_is_dict = isinstance(data__dynamic__readme, dict)
                     if data__dynamic__readme_is_dict:
-                        data__dynamic__readme_len = len(data__dynamic__readme)
-                        if not all(prop in data__dynamic__readme for prop in ['file']):
-                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme must contain ['file'] properties", value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}, rule='required')
+                        data__dynamic__readme__missing_keys = set(['file']) - data__dynamic__readme.keys()
+                        if data__dynamic__readme__missing_keys:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme must contain " + (str(sorted(data__dynamic__readme__missing_keys)) + " properties"), value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}, rule='required')
                 if data__dynamic_keys:
-                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must not contain "+str(data__dynamic_keys)+" properties", value=data__dynamic, name="" + (name_prefix or "data") + ".dynamic", definition={'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}}}, 'readme': {'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}}}, rule='additionalProperties')
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must not contain "+str(data__dynamic_keys)+" properties", value=data__dynamic, name="" + (name_prefix or "data") + ".dynamic", definition={'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, 'readme': {'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}}}, rule='additionalProperties')
         if data_keys:
-            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://setuptools.pypa.io/en/latest/references/keywords.html', 'title': '``tool.setuptools`` table', '$$description': ['Please notice for the time being the ``setuptools`` project does not specify', 'a way of configuring builds via ``pyproject.toml``.', 'Therefore this schema should be taken just as a *"thought experiment"* on how', 'this *might be done*, by following the principles established in', '`ini2toml `_.', 'It considers only ``setuptools`` `parameters', '`_', 'that can currently be configured via ``setup.cfg`` and are not covered by :pep:`621`', 'but intentionally excludes ``dependency_links`` and ``setup_requires``.', 'NOTE: ``scripts`` was renamed to ``script-files`` to avoid confusion with', 'entry-point based scripts (defined in :pep:`621`).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'description': 'Whether the project can be safely installed and run from a zip file.', 'type': 'boolean'}, 'script-files': {'description': 'Legacy way of defining scripts (entry-points are preferred).', 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}}, {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'data-files': {'$$description': ['**DEPRECATED**: dict-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', "Please notice this don't work with wheels. See `data files support", '`_'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['PROVISIONAL: List of glob patterns for all license files being distributed.', '(might become standard with PEP 639).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}}}, 'readme': {'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}, rule='additionalProperties')
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html', 'title': '``tool.setuptools`` table', '$$description': ['``setuptools``-specific configurations that can be set by users that require', 'customization.', 'These configurations are completely optional and probably can be skipped when', 'creating simple packages. They are equivalent to some of the `Keywords', '`_', 'used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.', 'It considers only ``setuptools`` `parameters', '`_', 'that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``', 'and ``setup_requires`` (incompatible with modern workflows/standards).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, 'script-files': {'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}}, {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'ext-modules': {'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}}, 'data-files': {'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, 'readme': {'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, 'ext-module': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'file-directive-for-dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}, rule='additionalProperties')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive_properties_file(data, custom_formats={}, name_prefix=None):
+    data_one_of_count8 = 0
+    if data_one_of_count8 < 2:
+        try:
+            if not isinstance(data, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must be string", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'string'}, rule='type')
+            data_one_of_count8 += 1
+        except JsonSchemaValueException: pass
+    if data_one_of_count8 < 2:
+        try:
+            if not isinstance(data, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must be array", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data_is_list = isinstance(data, (list, tuple))
+            if data_is_list:
+                data_len = len(data)
+                for data_x, data_item in enumerate(data):
+                    if not isinstance(data_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + "[{data_x}]".format(**locals()) + " must be string", value=data_item, name="" + (name_prefix or "data") + "[{data_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+            data_one_of_count8 += 1
+        except JsonSchemaValueException: pass
+    if data_one_of_count8 != 1:
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be valid exactly by one definition" + (" (" + str(data_one_of_count8) + " matches found)"), value=data, name="" + (name_prefix or "data") + "", definition={'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}, rule='oneOf')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive_for_dependencies(data, custom_formats={}, name_prefix=None):
+    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data, custom_formats, (name_prefix or "data") + "")
     return data
 
-def validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_file_directive(data, custom_formats={}, name_prefix=None):
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data, custom_formats={}, name_prefix=None):
     if not isinstance(data, (dict)):
         raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, rule='type')
     data_is_dict = isinstance(data, dict)
     if data_is_dict:
-        data_len = len(data)
-        if not all(prop in data for prop in ['file']):
-            raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain ['file'] properties", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, rule='required')
+        data__missing_keys = set(['file']) - data.keys()
+        if data__missing_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, rule='required')
         data_keys = set(data.keys())
         if "file" in data_keys:
             data_keys.remove("file")
             data__file = data["file"]
-            data__file_one_of_count7 = 0
-            if data__file_one_of_count7 < 2:
+            data__file_one_of_count9 = 0
+            if data__file_one_of_count9 < 2:
                 try:
                     if not isinstance(data__file, (str)):
                         raise JsonSchemaValueException("" + (name_prefix or "data") + ".file must be string", value=data__file, name="" + (name_prefix or "data") + ".file", definition={'type': 'string'}, rule='type')
-                    data__file_one_of_count7 += 1
+                    data__file_one_of_count9 += 1
                 except JsonSchemaValueException: pass
-            if data__file_one_of_count7 < 2:
+            if data__file_one_of_count9 < 2:
                 try:
                     if not isinstance(data__file, (list, tuple)):
                         raise JsonSchemaValueException("" + (name_prefix or "data") + ".file must be array", value=data__file, name="" + (name_prefix or "data") + ".file", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
@@ -539,33 +638,241 @@ def validate_https___setuptools_pypa_io_en_latest_references_keywords_html__defi
                         for data__file_x, data__file_item in enumerate(data__file):
                             if not isinstance(data__file_item, (str)):
                                 raise JsonSchemaValueException("" + (name_prefix or "data") + ".file[{data__file_x}]".format(**locals()) + " must be string", value=data__file_item, name="" + (name_prefix or "data") + ".file[{data__file_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
-                    data__file_one_of_count7 += 1
+                    data__file_one_of_count9 += 1
                 except JsonSchemaValueException: pass
-            if data__file_one_of_count7 != 1:
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".file must be valid exactly by one definition" + (" (" + str(data__file_one_of_count7) + " matches found)"), value=data__file, name="" + (name_prefix or "data") + ".file", definition={'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}, rule='oneOf')
+            if data__file_one_of_count9 != 1:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".file must be valid exactly by one definition" + (" (" + str(data__file_one_of_count9) + " matches found)"), value=data__file, name="" + (name_prefix or "data") + ".file", definition={'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}, rule='oneOf')
         if data_keys:
             raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, rule='additionalProperties')
     return data
 
-def validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_attr_directive(data, custom_formats={}, name_prefix=None):
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_attr_directive(data, custom_formats={}, name_prefix=None):
     if not isinstance(data, (dict)):
-        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, rule='type')
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, rule='type')
     data_is_dict = isinstance(data, dict)
     if data_is_dict:
-        data_len = len(data)
-        if not all(prop in data for prop in ['attr']):
-            raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain ['attr'] properties", value=data, name="" + (name_prefix or "data") + "", definition={'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, rule='required')
+        data__missing_keys = set(['attr']) - data.keys()
+        if data__missing_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, rule='required')
         data_keys = set(data.keys())
         if "attr" in data_keys:
             data_keys.remove("attr")
             data__attr = data["attr"]
             if not isinstance(data__attr, (str)):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".attr must be string", value=data__attr, name="" + (name_prefix or "data") + ".attr", definition={'type': 'string'}, rule='type')
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".attr must be string", value=data__attr, name="" + (name_prefix or "data") + ".attr", definition={'type': 'string', 'format': 'python-qualified-identifier'}, rule='type')
+            if isinstance(data__attr, str):
+                if not custom_formats["python-qualified-identifier"](data__attr):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".attr must be python-qualified-identifier", value=data__attr, name="" + (name_prefix or "data") + ".attr", definition={'type': 'string', 'format': 'python-qualified-identifier'}, rule='format')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, rule='additionalProperties')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_ext_module(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data__missing_keys = set(['name', 'sources']) - data.keys()
+        if data__missing_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, rule='required')
+        data_keys = set(data.keys())
+        if "name" in data_keys:
+            data_keys.remove("name")
+            data__name = data["name"]
+            if not isinstance(data__name, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".name must be string", value=data__name, name="" + (name_prefix or "data") + ".name", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='type')
+            if isinstance(data__name, str):
+                if not custom_formats["python-module-name-relaxed"](data__name):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".name must be python-module-name-relaxed", value=data__name, name="" + (name_prefix or "data") + ".name", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='format')
+        if "sources" in data_keys:
+            data_keys.remove("sources")
+            data__sources = data["sources"]
+            if not isinstance(data__sources, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".sources must be array", value=data__sources, name="" + (name_prefix or "data") + ".sources", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__sources_is_list = isinstance(data__sources, (list, tuple))
+            if data__sources_is_list:
+                data__sources_len = len(data__sources)
+                for data__sources_x, data__sources_item in enumerate(data__sources):
+                    if not isinstance(data__sources_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".sources[{data__sources_x}]".format(**locals()) + " must be string", value=data__sources_item, name="" + (name_prefix or "data") + ".sources[{data__sources_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "include-dirs" in data_keys:
+            data_keys.remove("include-dirs")
+            data__includedirs = data["include-dirs"]
+            if not isinstance(data__includedirs, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".include-dirs must be array", value=data__includedirs, name="" + (name_prefix or "data") + ".include-dirs", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__includedirs_is_list = isinstance(data__includedirs, (list, tuple))
+            if data__includedirs_is_list:
+                data__includedirs_len = len(data__includedirs)
+                for data__includedirs_x, data__includedirs_item in enumerate(data__includedirs):
+                    if not isinstance(data__includedirs_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".include-dirs[{data__includedirs_x}]".format(**locals()) + " must be string", value=data__includedirs_item, name="" + (name_prefix or "data") + ".include-dirs[{data__includedirs_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "define-macros" in data_keys:
+            data_keys.remove("define-macros")
+            data__definemacros = data["define-macros"]
+            if not isinstance(data__definemacros, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros must be array", value=data__definemacros, name="" + (name_prefix or "data") + ".define-macros", definition={'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, rule='type')
+            data__definemacros_is_list = isinstance(data__definemacros, (list, tuple))
+            if data__definemacros_is_list:
+                data__definemacros_len = len(data__definemacros)
+                for data__definemacros_x, data__definemacros_item in enumerate(data__definemacros):
+                    if not isinstance(data__definemacros_item, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}]".format(**locals()) + " must be array", value=data__definemacros_item, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}]".format(**locals()) + "", definition={'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}, rule='type')
+                    data__definemacros_item_is_list = isinstance(data__definemacros_item, (list, tuple))
+                    if data__definemacros_item_is_list:
+                        data__definemacros_item_len = len(data__definemacros_item)
+                        if data__definemacros_item_len > 0:
+                            data__definemacros_item__0 = data__definemacros_item[0]
+                            if not isinstance(data__definemacros_item__0, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][0]".format(**locals()) + " must be string", value=data__definemacros_item__0, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][0]".format(**locals()) + "", definition={'description': 'macro name', 'type': 'string'}, rule='type')
+                        if data__definemacros_item_len > 1:
+                            data__definemacros_item__1 = data__definemacros_item[1]
+                            data__definemacros_item__1_one_of_count10 = 0
+                            if data__definemacros_item__1_one_of_count10 < 2:
+                                try:
+                                    if not isinstance(data__definemacros_item__1, (str)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + " must be string", value=data__definemacros_item__1, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                                    data__definemacros_item__1_one_of_count10 += 1
+                                except JsonSchemaValueException: pass
+                            if data__definemacros_item__1_one_of_count10 < 2:
+                                try:
+                                    if not isinstance(data__definemacros_item__1, (NoneType)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + " must be null", value=data__definemacros_item__1, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + "", definition={'type': 'null'}, rule='type')
+                                    data__definemacros_item__1_one_of_count10 += 1
+                                except JsonSchemaValueException: pass
+                            if data__definemacros_item__1_one_of_count10 != 1:
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + " must be valid exactly by one definition" + (" (" + str(data__definemacros_item__1_one_of_count10) + " matches found)"), value=data__definemacros_item__1, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + "", definition={'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}, rule='oneOf')
+                        if data__definemacros_item_len > 2:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}]".format(**locals()) + " must contain only specified items", value=data__definemacros_item, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}]".format(**locals()) + "", definition={'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}, rule='items')
+        if "undef-macros" in data_keys:
+            data_keys.remove("undef-macros")
+            data__undefmacros = data["undef-macros"]
+            if not isinstance(data__undefmacros, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".undef-macros must be array", value=data__undefmacros, name="" + (name_prefix or "data") + ".undef-macros", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__undefmacros_is_list = isinstance(data__undefmacros, (list, tuple))
+            if data__undefmacros_is_list:
+                data__undefmacros_len = len(data__undefmacros)
+                for data__undefmacros_x, data__undefmacros_item in enumerate(data__undefmacros):
+                    if not isinstance(data__undefmacros_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".undef-macros[{data__undefmacros_x}]".format(**locals()) + " must be string", value=data__undefmacros_item, name="" + (name_prefix or "data") + ".undef-macros[{data__undefmacros_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "library-dirs" in data_keys:
+            data_keys.remove("library-dirs")
+            data__librarydirs = data["library-dirs"]
+            if not isinstance(data__librarydirs, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".library-dirs must be array", value=data__librarydirs, name="" + (name_prefix or "data") + ".library-dirs", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__librarydirs_is_list = isinstance(data__librarydirs, (list, tuple))
+            if data__librarydirs_is_list:
+                data__librarydirs_len = len(data__librarydirs)
+                for data__librarydirs_x, data__librarydirs_item in enumerate(data__librarydirs):
+                    if not isinstance(data__librarydirs_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".library-dirs[{data__librarydirs_x}]".format(**locals()) + " must be string", value=data__librarydirs_item, name="" + (name_prefix or "data") + ".library-dirs[{data__librarydirs_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "libraries" in data_keys:
+            data_keys.remove("libraries")
+            data__libraries = data["libraries"]
+            if not isinstance(data__libraries, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".libraries must be array", value=data__libraries, name="" + (name_prefix or "data") + ".libraries", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__libraries_is_list = isinstance(data__libraries, (list, tuple))
+            if data__libraries_is_list:
+                data__libraries_len = len(data__libraries)
+                for data__libraries_x, data__libraries_item in enumerate(data__libraries):
+                    if not isinstance(data__libraries_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".libraries[{data__libraries_x}]".format(**locals()) + " must be string", value=data__libraries_item, name="" + (name_prefix or "data") + ".libraries[{data__libraries_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "runtime-library-dirs" in data_keys:
+            data_keys.remove("runtime-library-dirs")
+            data__runtimelibrarydirs = data["runtime-library-dirs"]
+            if not isinstance(data__runtimelibrarydirs, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".runtime-library-dirs must be array", value=data__runtimelibrarydirs, name="" + (name_prefix or "data") + ".runtime-library-dirs", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__runtimelibrarydirs_is_list = isinstance(data__runtimelibrarydirs, (list, tuple))
+            if data__runtimelibrarydirs_is_list:
+                data__runtimelibrarydirs_len = len(data__runtimelibrarydirs)
+                for data__runtimelibrarydirs_x, data__runtimelibrarydirs_item in enumerate(data__runtimelibrarydirs):
+                    if not isinstance(data__runtimelibrarydirs_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".runtime-library-dirs[{data__runtimelibrarydirs_x}]".format(**locals()) + " must be string", value=data__runtimelibrarydirs_item, name="" + (name_prefix or "data") + ".runtime-library-dirs[{data__runtimelibrarydirs_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "extra-objects" in data_keys:
+            data_keys.remove("extra-objects")
+            data__extraobjects = data["extra-objects"]
+            if not isinstance(data__extraobjects, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-objects must be array", value=data__extraobjects, name="" + (name_prefix or "data") + ".extra-objects", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__extraobjects_is_list = isinstance(data__extraobjects, (list, tuple))
+            if data__extraobjects_is_list:
+                data__extraobjects_len = len(data__extraobjects)
+                for data__extraobjects_x, data__extraobjects_item in enumerate(data__extraobjects):
+                    if not isinstance(data__extraobjects_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-objects[{data__extraobjects_x}]".format(**locals()) + " must be string", value=data__extraobjects_item, name="" + (name_prefix or "data") + ".extra-objects[{data__extraobjects_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "extra-compile-args" in data_keys:
+            data_keys.remove("extra-compile-args")
+            data__extracompileargs = data["extra-compile-args"]
+            if not isinstance(data__extracompileargs, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-compile-args must be array", value=data__extracompileargs, name="" + (name_prefix or "data") + ".extra-compile-args", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__extracompileargs_is_list = isinstance(data__extracompileargs, (list, tuple))
+            if data__extracompileargs_is_list:
+                data__extracompileargs_len = len(data__extracompileargs)
+                for data__extracompileargs_x, data__extracompileargs_item in enumerate(data__extracompileargs):
+                    if not isinstance(data__extracompileargs_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-compile-args[{data__extracompileargs_x}]".format(**locals()) + " must be string", value=data__extracompileargs_item, name="" + (name_prefix or "data") + ".extra-compile-args[{data__extracompileargs_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "extra-link-args" in data_keys:
+            data_keys.remove("extra-link-args")
+            data__extralinkargs = data["extra-link-args"]
+            if not isinstance(data__extralinkargs, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-link-args must be array", value=data__extralinkargs, name="" + (name_prefix or "data") + ".extra-link-args", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__extralinkargs_is_list = isinstance(data__extralinkargs, (list, tuple))
+            if data__extralinkargs_is_list:
+                data__extralinkargs_len = len(data__extralinkargs)
+                for data__extralinkargs_x, data__extralinkargs_item in enumerate(data__extralinkargs):
+                    if not isinstance(data__extralinkargs_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-link-args[{data__extralinkargs_x}]".format(**locals()) + " must be string", value=data__extralinkargs_item, name="" + (name_prefix or "data") + ".extra-link-args[{data__extralinkargs_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "export-symbols" in data_keys:
+            data_keys.remove("export-symbols")
+            data__exportsymbols = data["export-symbols"]
+            if not isinstance(data__exportsymbols, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".export-symbols must be array", value=data__exportsymbols, name="" + (name_prefix or "data") + ".export-symbols", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__exportsymbols_is_list = isinstance(data__exportsymbols, (list, tuple))
+            if data__exportsymbols_is_list:
+                data__exportsymbols_len = len(data__exportsymbols)
+                for data__exportsymbols_x, data__exportsymbols_item in enumerate(data__exportsymbols):
+                    if not isinstance(data__exportsymbols_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".export-symbols[{data__exportsymbols_x}]".format(**locals()) + " must be string", value=data__exportsymbols_item, name="" + (name_prefix or "data") + ".export-symbols[{data__exportsymbols_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "swig-opts" in data_keys:
+            data_keys.remove("swig-opts")
+            data__swigopts = data["swig-opts"]
+            if not isinstance(data__swigopts, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".swig-opts must be array", value=data__swigopts, name="" + (name_prefix or "data") + ".swig-opts", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__swigopts_is_list = isinstance(data__swigopts, (list, tuple))
+            if data__swigopts_is_list:
+                data__swigopts_len = len(data__swigopts)
+                for data__swigopts_x, data__swigopts_item in enumerate(data__swigopts):
+                    if not isinstance(data__swigopts_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".swig-opts[{data__swigopts_x}]".format(**locals()) + " must be string", value=data__swigopts_item, name="" + (name_prefix or "data") + ".swig-opts[{data__swigopts_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "depends" in data_keys:
+            data_keys.remove("depends")
+            data__depends = data["depends"]
+            if not isinstance(data__depends, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".depends must be array", value=data__depends, name="" + (name_prefix or "data") + ".depends", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__depends_is_list = isinstance(data__depends, (list, tuple))
+            if data__depends_is_list:
+                data__depends_len = len(data__depends)
+                for data__depends_x, data__depends_item in enumerate(data__depends):
+                    if not isinstance(data__depends_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".depends[{data__depends_x}]".format(**locals()) + " must be string", value=data__depends_item, name="" + (name_prefix or "data") + ".depends[{data__depends_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "language" in data_keys:
+            data_keys.remove("language")
+            data__language = data["language"]
+            if not isinstance(data__language, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".language must be string", value=data__language, name="" + (name_prefix or "data") + ".language", definition={'type': 'string'}, rule='type')
+        if "optional" in data_keys:
+            data_keys.remove("optional")
+            data__optional = data["optional"]
+            if not isinstance(data__optional, (bool)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".optional must be boolean", value=data__optional, name="" + (name_prefix or "data") + ".optional", definition={'type': 'boolean'}, rule='type')
+        if "py-limited-api" in data_keys:
+            data_keys.remove("py-limited-api")
+            data__pylimitedapi = data["py-limited-api"]
+            if not isinstance(data__pylimitedapi, (bool)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".py-limited-api must be boolean", value=data__pylimitedapi, name="" + (name_prefix or "data") + ".py-limited-api", definition={'type': 'boolean'}, rule='type')
         if data_keys:
-            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, rule='additionalProperties')
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, rule='additionalProperties')
     return data
 
-def validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_find_directive(data, custom_formats={}, name_prefix=None):
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_find_directive(data, custom_formats={}, name_prefix=None):
     if not isinstance(data, (dict)):
         raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}, rule='type')
     data_is_dict = isinstance(data, dict)
@@ -623,31 +930,35 @@ def validate_https___setuptools_pypa_io_en_latest_references_keywords_html__defi
             raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}, rule='additionalProperties')
     return data
 
-def validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_package_name(data, custom_formats={}, name_prefix=None):
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_package_name(data, custom_formats={}, name_prefix=None):
     if not isinstance(data, (str)):
-        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be string", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}, rule='type')
-    data_any_of_count8 = 0
-    if not data_any_of_count8:
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be string", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, rule='type')
+    data_any_of_count11 = 0
+    if not data_any_of_count11:
         try:
+            if not isinstance(data, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must be string", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='type')
             if isinstance(data, str):
-                if not custom_formats["python-module-name"](data):
-                    raise JsonSchemaValueException("" + (name_prefix or "data") + " must be python-module-name", value=data, name="" + (name_prefix or "data") + "", definition={'format': 'python-module-name'}, rule='format')
-            data_any_of_count8 += 1
+                if not custom_formats["python-module-name-relaxed"](data):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + " must be python-module-name-relaxed", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='format')
+            data_any_of_count11 += 1
         except JsonSchemaValueException: pass
-    if not data_any_of_count8:
+    if not data_any_of_count11:
         try:
+            if not isinstance(data, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must be string", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'string', 'format': 'pep561-stub-name'}, rule='type')
             if isinstance(data, str):
                 if not custom_formats["pep561-stub-name"](data):
-                    raise JsonSchemaValueException("" + (name_prefix or "data") + " must be pep561-stub-name", value=data, name="" + (name_prefix or "data") + "", definition={'format': 'pep561-stub-name'}, rule='format')
-            data_any_of_count8 += 1
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + " must be pep561-stub-name", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'string', 'format': 'pep561-stub-name'}, rule='format')
+            data_any_of_count11 += 1
         except JsonSchemaValueException: pass
-    if not data_any_of_count8:
-        raise JsonSchemaValueException("" + (name_prefix or "data") + " cannot be validated by any definition", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or PEP 561).', 'type': 'string', 'anyOf': [{'format': 'python-module-name'}, {'format': 'pep561-stub-name'}]}, rule='anyOf')
+    if not data_any_of_count11:
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " cannot be validated by any definition", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, rule='anyOf')
     return data
 
-def validate_https___docs_python_org_3_install(data, custom_formats={}, name_prefix=None):
+def validate_https___setuptools_pypa_io_en_latest_deprecated_distutils_configfile_html(data, custom_formats={}, name_prefix=None):
     if not isinstance(data, (dict)):
-        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://docs.python.org/3/install/', 'title': '``tool.distutils`` table', '$$description': ['Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` scripts via `distutils configuration files', '`_.', '``tool.distutils`` subtables could be used with the same purpose', '(NOT CURRENTLY IMPLEMENTED).'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, rule='type')
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html', 'title': '``tool.distutils`` table', '$$description': ['**EXPERIMENTAL** (NOT OFFICIALLY SUPPORTED): Use ``tool.distutils``', 'subtables to configure arguments for ``distutils`` commands.', 'Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` commands via `distutils configuration files', '`_.', 'See also `the old Python docs _`.'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, rule='type')
     data_is_dict = isinstance(data, dict)
     if data_is_dict:
         data_keys = set(data.keys())
@@ -664,14 +975,65 @@ def validate_https___docs_python_org_3_install(data, custom_formats={}, name_pre
                     raise JsonSchemaValueException("" + (name_prefix or "data") + ".{data_key}".format(**locals()) + " must be object", value=data_val, name="" + (name_prefix or "data") + ".{data_key}".format(**locals()) + "", definition={'type': 'object'}, rule='type')
     return data
 
-def validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata(data, custom_formats={}, name_prefix=None):
+def validate_https___packaging_python_org_en_latest_specifications_pyproject_toml(data, custom_formats={}, name_prefix=None):
     if not isinstance(data, (dict)):
-        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-project-metadata/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'authors': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'gui-scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, rule='type')
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'gui-scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, 'import-names': {'description': 'Lists import names which a project, when installed, would exclusively provide.', 'type': 'array', 'items': {'type': 'string', 'format': 'import-name'}}, 'import-namespaces': {'description': 'Lists import names that, when installed, would be provided by the project, but not exclusively.', 'type': 'array', 'items': {'type': 'string', 'format': 'import-name'}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies', 'import-names', 'import-namespaces']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, rule='type')
+    try:
+        try:
+            data_is_dict = isinstance(data, dict)
+            if data_is_dict:
+                data__missing_keys = set(['dynamic']) - data.keys()
+                if data__missing_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, rule='required')
+                data_keys = set(data.keys())
+                if "dynamic" in data_keys:
+                    data_keys.remove("dynamic")
+                    data__dynamic = data["dynamic"]
+                    data__dynamic_is_list = isinstance(data__dynamic, (list, tuple))
+                    if data__dynamic_is_list:
+                        data__dynamic_contains = False
+                        for data__dynamic_key in data__dynamic:
+                            try:
+                                if data__dynamic_key != "version":
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must be same as const definition: version", value=data__dynamic_key, name="" + (name_prefix or "data") + ".dynamic", definition={'const': 'version'}, rule='const')
+                                data__dynamic_contains = True
+                                break
+                            except JsonSchemaValueException: pass
+                        if not data__dynamic_contains:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must contain one of contains definition", value=data__dynamic, name="" + (name_prefix or "data") + ".dynamic", definition={'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}, rule='contains')
+        except JsonSchemaValueException: pass
+        else:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must NOT match a disallowed definition", value=data, name="" + (name_prefix or "data") + "", definition={'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, rule='not')
+    except JsonSchemaValueException:
+        pass
+    else:
+        data_is_dict = isinstance(data, dict)
+        if data_is_dict:
+            data__missing_keys = set(['version']) - data.keys()
+            if data__missing_keys:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, rule='required')
+    try:
+        data_is_dict = isinstance(data, dict)
+        if data_is_dict:
+            data__missing_keys = set(['license-files']) - data.keys()
+            if data__missing_keys:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'required': ['license-files']}, rule='required')
+    except JsonSchemaValueException:
+        pass
+    else:
+        data_is_dict = isinstance(data, dict)
+        if data_is_dict:
+            data_keys = set(data.keys())
+            if "license" in data_keys:
+                data_keys.remove("license")
+                data__license = data["license"]
+                if not isinstance(data__license, (str)):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be string", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'string'}, rule='type')
     data_is_dict = isinstance(data, dict)
     if data_is_dict:
-        data_len = len(data)
-        if not all(prop in data for prop in ['name']):
-            raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain ['name'] properties", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-project-metadata/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'authors': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'gui-scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, rule='required')
+        data__missing_keys = set(['name']) - data.keys()
+        if data__missing_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'gui-scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, 'import-names': {'description': 'Lists import names which a project, when installed, would exclusively provide.', 'type': 'array', 'items': {'type': 'string', 'format': 'import-name'}}, 'import-namespaces': {'description': 'Lists import names that, when installed, would be provided by the project, but not exclusively.', 'type': 'array', 'items': {'type': 'string', 'format': 'import-name'}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies', 'import-names', 'import-namespaces']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, rule='required')
         data_keys = set(data.keys())
         if "name" in data_keys:
             data_keys.remove("name")
@@ -697,65 +1059,65 @@ def validate_https___packaging_python_org_en_latest_specifications_declaring_pro
         if "readme" in data_keys:
             data_keys.remove("readme")
             data__readme = data["readme"]
-            data__readme_one_of_count9 = 0
-            if data__readme_one_of_count9 < 2:
+            data__readme_one_of_count12 = 0
+            if data__readme_one_of_count12 < 2:
                 try:
                     if not isinstance(data__readme, (str)):
                         raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must be string", value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, rule='type')
-                    data__readme_one_of_count9 += 1
+                    data__readme_one_of_count12 += 1
                 except JsonSchemaValueException: pass
-            if data__readme_one_of_count9 < 2:
+            if data__readme_one_of_count12 < 2:
                 try:
                     if not isinstance(data__readme, (dict)):
                         raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must be object", value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}, rule='type')
-                    data__readme_any_of_count10 = 0
-                    if not data__readme_any_of_count10:
+                    data__readme_any_of_count13 = 0
+                    if not data__readme_any_of_count13:
                         try:
                             data__readme_is_dict = isinstance(data__readme, dict)
                             if data__readme_is_dict:
-                                data__readme_len = len(data__readme)
-                                if not all(prop in data__readme for prop in ['file']):
-                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must contain ['file'] properties", value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, rule='required')
+                                data__readme__missing_keys = set(['file']) - data__readme.keys()
+                                if data__readme__missing_keys:
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must contain " + (str(sorted(data__readme__missing_keys)) + " properties"), value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, rule='required')
                                 data__readme_keys = set(data__readme.keys())
                                 if "file" in data__readme_keys:
                                     data__readme_keys.remove("file")
                                     data__readme__file = data__readme["file"]
                                     if not isinstance(data__readme__file, (str)):
                                         raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme.file must be string", value=data__readme__file, name="" + (name_prefix or "data") + ".readme.file", definition={'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}, rule='type')
-                            data__readme_any_of_count10 += 1
+                            data__readme_any_of_count13 += 1
                         except JsonSchemaValueException: pass
-                    if not data__readme_any_of_count10:
+                    if not data__readme_any_of_count13:
                         try:
                             data__readme_is_dict = isinstance(data__readme, dict)
                             if data__readme_is_dict:
-                                data__readme_len = len(data__readme)
-                                if not all(prop in data__readme for prop in ['text']):
-                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must contain ['text'] properties", value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}, rule='required')
+                                data__readme__missing_keys = set(['text']) - data__readme.keys()
+                                if data__readme__missing_keys:
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must contain " + (str(sorted(data__readme__missing_keys)) + " properties"), value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}, rule='required')
                                 data__readme_keys = set(data__readme.keys())
                                 if "text" in data__readme_keys:
                                     data__readme_keys.remove("text")
                                     data__readme__text = data__readme["text"]
                                     if not isinstance(data__readme__text, (str)):
                                         raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme.text must be string", value=data__readme__text, name="" + (name_prefix or "data") + ".readme.text", definition={'type': 'string', 'description': 'Full text describing the project.'}, rule='type')
-                            data__readme_any_of_count10 += 1
+                            data__readme_any_of_count13 += 1
                         except JsonSchemaValueException: pass
-                    if not data__readme_any_of_count10:
+                    if not data__readme_any_of_count13:
                         raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme cannot be validated by any definition", value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, rule='anyOf')
                     data__readme_is_dict = isinstance(data__readme, dict)
                     if data__readme_is_dict:
-                        data__readme_len = len(data__readme)
-                        if not all(prop in data__readme for prop in ['content-type']):
-                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must contain ['content-type'] properties", value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}, rule='required')
+                        data__readme__missing_keys = set(['content-type']) - data__readme.keys()
+                        if data__readme__missing_keys:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must contain " + (str(sorted(data__readme__missing_keys)) + " properties"), value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}, rule='required')
                         data__readme_keys = set(data__readme.keys())
                         if "content-type" in data__readme_keys:
                             data__readme_keys.remove("content-type")
                             data__readme__contenttype = data__readme["content-type"]
                             if not isinstance(data__readme__contenttype, (str)):
                                 raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme.content-type must be string", value=data__readme__contenttype, name="" + (name_prefix or "data") + ".readme.content-type", definition={'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}, rule='type')
-                    data__readme_one_of_count9 += 1
+                    data__readme_one_of_count12 += 1
                 except JsonSchemaValueException: pass
-            if data__readme_one_of_count9 != 1:
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must be valid exactly by one definition" + (" (" + str(data__readme_one_of_count9) + " matches found)"), value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, rule='oneOf')
+            if data__readme_one_of_count12 != 1:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must be valid exactly by one definition" + (" (" + str(data__readme_one_of_count12) + " matches found)"), value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, rule='oneOf')
         if "requires-python" in data_keys:
             data_keys.remove("requires-python")
             data__requirespython = data["requires-python"]
@@ -767,59 +1129,83 @@ def validate_https___packaging_python_org_en_latest_specifications_declaring_pro
         if "license" in data_keys:
             data_keys.remove("license")
             data__license = data["license"]
-            data__license_one_of_count11 = 0
-            if data__license_one_of_count11 < 2:
+            data__license_one_of_count14 = 0
+            if data__license_one_of_count14 < 2:
+                try:
+                    if not isinstance(data__license, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be string", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, rule='type')
+                    if isinstance(data__license, str):
+                        if not custom_formats["SPDX"](data__license):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be SPDX", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, rule='format')
+                    data__license_one_of_count14 += 1
+                except JsonSchemaValueException: pass
+            if data__license_one_of_count14 < 2:
                 try:
+                    if not isinstance(data__license, (dict)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be object", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, rule='type')
                     data__license_is_dict = isinstance(data__license, dict)
                     if data__license_is_dict:
-                        data__license_len = len(data__license)
-                        if not all(prop in data__license for prop in ['file']):
-                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must contain ['file'] properties", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, rule='required')
+                        data__license__missing_keys = set(['file']) - data__license.keys()
+                        if data__license__missing_keys:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must contain " + (str(sorted(data__license__missing_keys)) + " properties"), value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, rule='required')
                         data__license_keys = set(data__license.keys())
                         if "file" in data__license_keys:
                             data__license_keys.remove("file")
                             data__license__file = data__license["file"]
                             if not isinstance(data__license__file, (str)):
                                 raise JsonSchemaValueException("" + (name_prefix or "data") + ".license.file must be string", value=data__license__file, name="" + (name_prefix or "data") + ".license.file", definition={'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}, rule='type')
-                    data__license_one_of_count11 += 1
+                    data__license_one_of_count14 += 1
                 except JsonSchemaValueException: pass
-            if data__license_one_of_count11 < 2:
+            if data__license_one_of_count14 < 2:
                 try:
+                    if not isinstance(data__license, (dict)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be object", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}, rule='type')
                     data__license_is_dict = isinstance(data__license, dict)
                     if data__license_is_dict:
-                        data__license_len = len(data__license)
-                        if not all(prop in data__license for prop in ['text']):
-                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must contain ['text'] properties", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}, rule='required')
+                        data__license__missing_keys = set(['text']) - data__license.keys()
+                        if data__license__missing_keys:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must contain " + (str(sorted(data__license__missing_keys)) + " properties"), value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}, rule='required')
                         data__license_keys = set(data__license.keys())
                         if "text" in data__license_keys:
                             data__license_keys.remove("text")
                             data__license__text = data__license["text"]
                             if not isinstance(data__license__text, (str)):
                                 raise JsonSchemaValueException("" + (name_prefix or "data") + ".license.text must be string", value=data__license__text, name="" + (name_prefix or "data") + ".license.text", definition={'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}, rule='type')
-                    data__license_one_of_count11 += 1
+                    data__license_one_of_count14 += 1
                 except JsonSchemaValueException: pass
-            if data__license_one_of_count11 != 1:
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be valid exactly by one definition" + (" (" + str(data__license_one_of_count11) + " matches found)"), value=data__license, name="" + (name_prefix or "data") + ".license", definition={'description': '`Project license `_.', 'oneOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, rule='oneOf')
+            if data__license_one_of_count14 != 1:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be valid exactly by one definition" + (" (" + str(data__license_one_of_count14) + " matches found)"), value=data__license, name="" + (name_prefix or "data") + ".license", definition={'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, rule='oneOf')
+        if "license-files" in data_keys:
+            data_keys.remove("license-files")
+            data__licensefiles = data["license-files"]
+            if not isinstance(data__licensefiles, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".license-files must be array", value=data__licensefiles, name="" + (name_prefix or "data") + ".license-files", definition={'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__licensefiles_is_list = isinstance(data__licensefiles, (list, tuple))
+            if data__licensefiles_is_list:
+                data__licensefiles_len = len(data__licensefiles)
+                for data__licensefiles_x, data__licensefiles_item in enumerate(data__licensefiles):
+                    if not isinstance(data__licensefiles_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".license-files[{data__licensefiles_x}]".format(**locals()) + " must be string", value=data__licensefiles_item, name="" + (name_prefix or "data") + ".license-files[{data__licensefiles_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
         if "authors" in data_keys:
             data_keys.remove("authors")
             data__authors = data["authors"]
             if not isinstance(data__authors, (list, tuple)):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".authors must be array", value=data__authors, name="" + (name_prefix or "data") + ".authors", definition={'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, rule='type')
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".authors must be array", value=data__authors, name="" + (name_prefix or "data") + ".authors", definition={'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, rule='type')
             data__authors_is_list = isinstance(data__authors, (list, tuple))
             if data__authors_is_list:
                 data__authors_len = len(data__authors)
                 for data__authors_x, data__authors_item in enumerate(data__authors):
-                    validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_author(data__authors_item, custom_formats, (name_prefix or "data") + ".authors[{data__authors_x}]".format(**locals()))
+                    validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_author(data__authors_item, custom_formats, (name_prefix or "data") + ".authors[{data__authors_x}]".format(**locals()))
         if "maintainers" in data_keys:
             data_keys.remove("maintainers")
             data__maintainers = data["maintainers"]
             if not isinstance(data__maintainers, (list, tuple)):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".maintainers must be array", value=data__maintainers, name="" + (name_prefix or "data") + ".maintainers", definition={'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, rule='type')
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".maintainers must be array", value=data__maintainers, name="" + (name_prefix or "data") + ".maintainers", definition={'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, rule='type')
             data__maintainers_is_list = isinstance(data__maintainers, (list, tuple))
             if data__maintainers_is_list:
                 data__maintainers_len = len(data__maintainers)
                 for data__maintainers_x, data__maintainers_item in enumerate(data__maintainers):
-                    validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_author(data__maintainers_item, custom_formats, (name_prefix or "data") + ".maintainers[{data__maintainers_x}]".format(**locals()))
+                    validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_author(data__maintainers_item, custom_formats, (name_prefix or "data") + ".maintainers[{data__maintainers_x}]".format(**locals()))
         if "keywords" in data_keys:
             data_keys.remove("keywords")
             data__keywords = data["keywords"]
@@ -867,11 +1253,11 @@ def validate_https___packaging_python_org_en_latest_specifications_declaring_pro
         if "scripts" in data_keys:
             data_keys.remove("scripts")
             data__scripts = data["scripts"]
-            validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_entry_point_group(data__scripts, custom_formats, (name_prefix or "data") + ".scripts")
+            validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_entry_point_group(data__scripts, custom_formats, (name_prefix or "data") + ".scripts")
         if "gui-scripts" in data_keys:
             data_keys.remove("gui-scripts")
             data__guiscripts = data["gui-scripts"]
-            validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_entry_point_group(data__guiscripts, custom_formats, (name_prefix or "data") + ".gui-scripts")
+            validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_entry_point_group(data__guiscripts, custom_formats, (name_prefix or "data") + ".gui-scripts")
         if "entry-points" in data_keys:
             data_keys.remove("entry-points")
             data__entrypoints = data["entry-points"]
@@ -882,7 +1268,7 @@ def validate_https___packaging_python_org_en_latest_specifications_declaring_pro
                     if REGEX_PATTERNS['^.+$'].search(data__entrypoints_key):
                         if data__entrypoints_key in data__entrypoints_keys:
                             data__entrypoints_keys.remove(data__entrypoints_key)
-                        validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_entry_point_group(data__entrypoints_val, custom_formats, (name_prefix or "data") + ".entry-points.{data__entrypoints_key}".format(**locals()))
+                        validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_entry_point_group(data__entrypoints_val, custom_formats, (name_prefix or "data") + ".entry-points.{data__entrypoints_key}".format(**locals()))
                 if data__entrypoints_keys:
                     raise JsonSchemaValueException("" + (name_prefix or "data") + ".entry-points must not contain "+str(data__entrypoints_keys)+" properties", value=data__entrypoints, name="" + (name_prefix or "data") + ".entry-points", definition={'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, rule='additionalProperties')
                 data__entrypoints_len = len(data__entrypoints)
@@ -906,7 +1292,7 @@ def validate_https___packaging_python_org_en_latest_specifications_declaring_pro
             if data__dependencies_is_list:
                 data__dependencies_len = len(data__dependencies)
                 for data__dependencies_x, data__dependencies_item in enumerate(data__dependencies):
-                    validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_dependency(data__dependencies_item, custom_formats, (name_prefix or "data") + ".dependencies[{data__dependencies_x}]".format(**locals()))
+                    validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_dependency(data__dependencies_item, custom_formats, (name_prefix or "data") + ".dependencies[{data__dependencies_x}]".format(**locals()))
         if "optional-dependencies" in data_keys:
             data_keys.remove("optional-dependencies")
             data__optionaldependencies = data["optional-dependencies"]
@@ -925,7 +1311,7 @@ def validate_https___packaging_python_org_en_latest_specifications_declaring_pro
                         if data__optionaldependencies_val_is_list:
                             data__optionaldependencies_val_len = len(data__optionaldependencies_val)
                             for data__optionaldependencies_val_x, data__optionaldependencies_val_item in enumerate(data__optionaldependencies_val):
-                                validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_dependency(data__optionaldependencies_val_item, custom_formats, (name_prefix or "data") + ".optional-dependencies.{data__optionaldependencies_key}[{data__optionaldependencies_val_x}]".format(**locals()))
+                                validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_dependency(data__optionaldependencies_val_item, custom_formats, (name_prefix or "data") + ".optional-dependencies.{data__optionaldependencies_key}[{data__optionaldependencies_val_x}]".format(**locals()))
                 if data__optionaldependencies_keys:
                     raise JsonSchemaValueException("" + (name_prefix or "data") + ".optional-dependencies must not contain "+str(data__optionaldependencies_keys)+" properties", value=data__optionaldependencies, name="" + (name_prefix or "data") + ".optional-dependencies", definition={'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='additionalProperties')
                 data__optionaldependencies_len = len(data__optionaldependencies)
@@ -940,56 +1326,50 @@ def validate_https___packaging_python_org_en_latest_specifications_declaring_pro
                             data__optionaldependencies_property_names = False
                     if not data__optionaldependencies_property_names:
                         raise JsonSchemaValueException("" + (name_prefix or "data") + ".optional-dependencies must be named by propertyName definition", value=data__optionaldependencies, name="" + (name_prefix or "data") + ".optional-dependencies", definition={'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='propertyNames')
+        if "import-names" in data_keys:
+            data_keys.remove("import-names")
+            data__importnames = data["import-names"]
+            if not isinstance(data__importnames, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".import-names must be array", value=data__importnames, name="" + (name_prefix or "data") + ".import-names", definition={'description': 'Lists import names which a project, when installed, would exclusively provide.', 'type': 'array', 'items': {'type': 'string', 'format': 'import-name'}}, rule='type')
+            data__importnames_is_list = isinstance(data__importnames, (list, tuple))
+            if data__importnames_is_list:
+                data__importnames_len = len(data__importnames)
+                for data__importnames_x, data__importnames_item in enumerate(data__importnames):
+                    if not isinstance(data__importnames_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".import-names[{data__importnames_x}]".format(**locals()) + " must be string", value=data__importnames_item, name="" + (name_prefix or "data") + ".import-names[{data__importnames_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'import-name'}, rule='type')
+                    if isinstance(data__importnames_item, str):
+                        if not custom_formats["import-name"](data__importnames_item):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".import-names[{data__importnames_x}]".format(**locals()) + " must be import-name", value=data__importnames_item, name="" + (name_prefix or "data") + ".import-names[{data__importnames_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'import-name'}, rule='format')
+        if "import-namespaces" in data_keys:
+            data_keys.remove("import-namespaces")
+            data__importnamespaces = data["import-namespaces"]
+            if not isinstance(data__importnamespaces, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".import-namespaces must be array", value=data__importnamespaces, name="" + (name_prefix or "data") + ".import-namespaces", definition={'description': 'Lists import names that, when installed, would be provided by the project, but not exclusively.', 'type': 'array', 'items': {'type': 'string', 'format': 'import-name'}}, rule='type')
+            data__importnamespaces_is_list = isinstance(data__importnamespaces, (list, tuple))
+            if data__importnamespaces_is_list:
+                data__importnamespaces_len = len(data__importnamespaces)
+                for data__importnamespaces_x, data__importnamespaces_item in enumerate(data__importnamespaces):
+                    if not isinstance(data__importnamespaces_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".import-namespaces[{data__importnamespaces_x}]".format(**locals()) + " must be string", value=data__importnamespaces_item, name="" + (name_prefix or "data") + ".import-namespaces[{data__importnamespaces_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'import-name'}, rule='type')
+                    if isinstance(data__importnamespaces_item, str):
+                        if not custom_formats["import-name"](data__importnamespaces_item):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".import-namespaces[{data__importnamespaces_x}]".format(**locals()) + " must be import-name", value=data__importnamespaces_item, name="" + (name_prefix or "data") + ".import-namespaces[{data__importnamespaces_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'import-name'}, rule='format')
         if "dynamic" in data_keys:
             data_keys.remove("dynamic")
             data__dynamic = data["dynamic"]
             if not isinstance(data__dynamic, (list, tuple)):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must be array", value=data__dynamic, name="" + (name_prefix or "data") + ".dynamic", definition={'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}, rule='type')
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must be array", value=data__dynamic, name="" + (name_prefix or "data") + ".dynamic", definition={'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies', 'import-names', 'import-namespaces']}}, rule='type')
             data__dynamic_is_list = isinstance(data__dynamic, (list, tuple))
             if data__dynamic_is_list:
                 data__dynamic_len = len(data__dynamic)
                 for data__dynamic_x, data__dynamic_item in enumerate(data__dynamic):
-                    if data__dynamic_item not in ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']:
-                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic[{data__dynamic_x}]".format(**locals()) + " must be one of ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']", value=data__dynamic_item, name="" + (name_prefix or "data") + ".dynamic[{data__dynamic_x}]".format(**locals()) + "", definition={'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}, rule='enum')
+                    if data__dynamic_item not in ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies', 'import-names', 'import-namespaces']:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic[{data__dynamic_x}]".format(**locals()) + " must be one of ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies', 'import-names', 'import-namespaces']", value=data__dynamic_item, name="" + (name_prefix or "data") + ".dynamic[{data__dynamic_x}]".format(**locals()) + "", definition={'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies', 'import-names', 'import-namespaces']}, rule='enum')
         if data_keys:
-            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-project-metadata/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'authors': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'gui-scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, rule='additionalProperties')
-    try:
-        try:
-            data_is_dict = isinstance(data, dict)
-            if data_is_dict:
-                data_len = len(data)
-                if not all(prop in data for prop in ['dynamic']):
-                    raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain ['dynamic'] properties", value=data, name="" + (name_prefix or "data") + "", definition={'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, rule='required')
-                data_keys = set(data.keys())
-                if "dynamic" in data_keys:
-                    data_keys.remove("dynamic")
-                    data__dynamic = data["dynamic"]
-                    data__dynamic_is_list = isinstance(data__dynamic, (list, tuple))
-                    if data__dynamic_is_list:
-                        data__dynamic_contains = False
-                        for data__dynamic_key in data__dynamic:
-                            try:
-                                if data__dynamic_key != "version":
-                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must be same as const definition: version", value=data__dynamic_key, name="" + (name_prefix or "data") + ".dynamic", definition={'const': 'version'}, rule='const')
-                                data__dynamic_contains = True
-                                break
-                            except JsonSchemaValueException: pass
-                        if not data__dynamic_contains:
-                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must contain one of contains definition", value=data__dynamic, name="" + (name_prefix or "data") + ".dynamic", definition={'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}, rule='contains')
-        except JsonSchemaValueException: pass
-        else:
-            raise JsonSchemaValueException("" + (name_prefix or "data") + " must NOT match a disallowed definition", value=data, name="" + (name_prefix or "data") + "", definition={'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, rule='not')
-    except JsonSchemaValueException:
-        pass
-    else:
-        data_is_dict = isinstance(data, dict)
-        if data_is_dict:
-            data_len = len(data)
-            if not all(prop in data for prop in ['version']):
-                raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain ['version'] properties", value=data, name="" + (name_prefix or "data") + "", definition={'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, rule='required')
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'gui-scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, 'import-names': {'description': 'Lists import names which a project, when installed, would exclusively provide.', 'type': 'array', 'items': {'type': 'string', 'format': 'import-name'}}, 'import-namespaces': {'description': 'Lists import names that, when installed, would be provided by the project, but not exclusively.', 'type': 'array', 'items': {'type': 'string', 'format': 'import-name'}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies', 'import-names', 'import-namespaces']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, rule='additionalProperties')
     return data
 
-def validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_dependency(data, custom_formats={}, name_prefix=None):
+def validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_dependency(data, custom_formats={}, name_prefix=None):
     if not isinstance(data, (str)):
         raise JsonSchemaValueException("" + (name_prefix or "data") + " must be string", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}, rule='type')
     if isinstance(data, str):
@@ -997,7 +1377,7 @@ def validate_https___packaging_python_org_en_latest_specifications_declaring_pro
             raise JsonSchemaValueException("" + (name_prefix or "data") + " must be pep508", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}, rule='format')
     return data
 
-def validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_entry_point_group(data, custom_formats={}, name_prefix=None):
+def validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_entry_point_group(data, custom_formats={}, name_prefix=None):
     if not isinstance(data, (dict)):
         raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, rule='type')
     data_is_dict = isinstance(data, dict)
@@ -1028,9 +1408,30 @@ def validate_https___packaging_python_org_en_latest_specifications_declaring_pro
                 raise JsonSchemaValueException("" + (name_prefix or "data") + " must be named by propertyName definition", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, rule='propertyNames')
     return data
 
-def validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_author(data, custom_formats={}, name_prefix=None):
+def validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_author(data, custom_formats={}, name_prefix=None):
     if not isinstance(data, (dict)):
-        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, rule='type')
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, rule='type')
+    data_any_of_count15 = 0
+    if not data_any_of_count15:
+        try:
+            data_is_dict = isinstance(data, dict)
+            if data_is_dict:
+                data__missing_keys = set(['name']) - data.keys()
+                if data__missing_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'required': ['name']}, rule='required')
+            data_any_of_count15 += 1
+        except JsonSchemaValueException: pass
+    if not data_any_of_count15:
+        try:
+            data_is_dict = isinstance(data, dict)
+            if data_is_dict:
+                data__missing_keys = set(['email']) - data.keys()
+                if data__missing_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'required': ['email']}, rule='required')
+            data_any_of_count15 += 1
+        except JsonSchemaValueException: pass
+    if not data_any_of_count15:
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " cannot be validated by any definition", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, rule='anyOf')
     data_is_dict = isinstance(data, dict)
     if data_is_dict:
         data_keys = set(data.keys())
@@ -1048,5 +1449,5 @@ def validate_https___packaging_python_org_en_latest_specifications_declaring_pro
                 if not REGEX_PATTERNS["idn-email_re_pattern"].match(data__email):
                     raise JsonSchemaValueException("" + (name_prefix or "data") + ".email must be idn-email", value=data__email, name="" + (name_prefix or "data") + ".email", definition={'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}, rule='format')
         if data_keys:
-            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, rule='additionalProperties')
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}, 'anyOf': [{'required': ['name']}, {'required': ['email']}]}, rule='additionalProperties')
     return data
diff --git a/setuptools/config/_validate_pyproject/formats.py b/setuptools/config/_validate_pyproject/formats.py
index e73961661d..fe958cc52a 100644
--- a/setuptools/config/_validate_pyproject/formats.py
+++ b/setuptools/config/_validate_pyproject/formats.py
@@ -1,3 +1,15 @@
+"""
+The functions in this module are used to validate schemas with the
+`format JSON Schema keyword
+`_.
+
+The correspondence is given by replacing the ``_`` character in the name of the
+function with a ``-`` to obtain the format name and vice versa.
+"""
+
+from __future__ import annotations
+
+import keyword
 import logging
 import os
 import re
@@ -6,6 +18,8 @@
 from itertools import chain as _chain
 
 if typing.TYPE_CHECKING:
+    import builtins
+
     from typing_extensions import Literal
 
 _logger = logging.getLogger(__name__)
@@ -20,7 +34,7 @@
         (?P[0-9]+(?:\.[0-9]+)*)                  # release segment
         (?P
                                          # pre-release
             [-_\.]?
-            (?P(a|b|c|rc|alpha|beta|pre|preview))
+            (?Palpha|a|beta|b|preview|pre|c|rc)
             [-_\.]?
             (?P[0-9]+)?
         )?
@@ -44,10 +58,15 @@
     (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
 """
 
-VERSION_REGEX = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.X | re.I)
+VERSION_REGEX = re.compile(
+    r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE
+)
 
 
 def pep440(version: str) -> bool:
+    """See :ref:`PyPA's version specification `
+    (initially introduced in :pep:`440`).
+    """
     return VERSION_REGEX.match(version) is not None
 
 
@@ -55,10 +74,13 @@ def pep440(version: str) -> bool:
 # PEP 508
 
 PEP508_IDENTIFIER_PATTERN = r"([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])"
-PEP508_IDENTIFIER_REGEX = re.compile(f"^{PEP508_IDENTIFIER_PATTERN}$", re.I)
+PEP508_IDENTIFIER_REGEX = re.compile(f"^{PEP508_IDENTIFIER_PATTERN}$", re.IGNORECASE)
 
 
 def pep508_identifier(name: str) -> bool:
+    """See :ref:`PyPA's name specification `
+    (initially introduced in :pep:`508#names`).
+    """
     return PEP508_IDENTIFIER_REGEX.match(name) is not None
 
 
@@ -67,14 +89,19 @@ def pep508_identifier(name: str) -> bool:
         from packaging import requirements as _req
     except ImportError:  # pragma: no cover
         # let's try setuptools vendored version
-        from setuptools._vendor.packaging import requirements as _req  # type: ignore
+        from setuptools._vendor.packaging import (  # type: ignore[no-redef]
+            requirements as _req,
+        )
 
     def pep508(value: str) -> bool:
+        """See :ref:`PyPA's dependency specifiers `
+        (initially introduced in :pep:`508`).
+        """
         try:
             _req.Requirement(value)
-            return True
         except _req.InvalidRequirement:
             return False
+        return True
 
 except ImportError:  # pragma: no cover
     _logger.warning(
@@ -83,12 +110,15 @@ def pep508(value: str) -> bool:
         "To enforce validation, please install `packaging`."
     )
 
-    def pep508(value: str) -> bool:
+    def pep508(value: str) -> bool:  # noqa: ARG001
         return True
 
 
 def pep508_versionspec(value: str) -> bool:
-    """Expression that can be used to specify/lock versions (including ranges)"""
+    """Expression that can be used to specify/lock versions (including ranges)
+    See ``versionspec`` in :ref:`PyPA's dependency specifiers
+    ` (initially introduced in :pep:`508`).
+    """
     if any(c in value for c in (";", "]", "@")):
         # In PEP 508:
         # conditional markers, extras and URL specs are not included in the
@@ -104,6 +134,11 @@ def pep508_versionspec(value: str) -> bool:
 
 
 def pep517_backend_reference(value: str) -> bool:
+    """See PyPA's specification for defining build-backend references
+    introduced in :pep:`517#source-trees`.
+
+    This is similar to an entry-point reference (e.g., ``package.module:object``).
+    """
     module, _, obj = value.partition(":")
     identifiers = (i.strip() for i in _chain(module.split("."), obj.split(".")))
     return all(python_identifier(i) for i in identifiers if i)
@@ -120,10 +155,10 @@ def _download_classifiers() -> str:
 
     url = "https://pypi.org/pypi?:action=list_classifiers"
     context = ssl.create_default_context()
-    with urlopen(url, context=context) as response:
+    with urlopen(url, context=context) as response:  # noqa: S310 (audit URLs)
         headers = Message()
         headers["content_type"] = response.getheader("content-type", "text/plain")
-        return response.read().decode(headers.get_param("charset", "utf-8"))
+        return response.read().decode(headers.get_param("charset", "utf-8"))  # type: ignore[no-any-return]
 
 
 class _TroveClassifier:
@@ -134,16 +169,19 @@ class _TroveClassifier:
     option (classifiers will be validated anyway during the upload to PyPI).
     """
 
-    downloaded: typing.Union[None, "Literal[False]", typing.Set[str]]
+    downloaded: None | Literal[False] | set[str]
+    """
+    None => not cached yet
+    False => unavailable
+    set => cached values
+    """
 
-    def __init__(self):
+    def __init__(self) -> None:
         self.downloaded = None
         self._skip_download = False
-        # None => not cached yet
-        # False => cache not available
         self.__name__ = "trove_classifier"  # Emulate a public function
 
-    def _disable_download(self):
+    def _disable_download(self) -> None:
         # This is a private API. Only setuptools has the consent of using it.
         self._skip_download = True
 
@@ -168,7 +206,7 @@ def __call__(self, value: str) -> bool:
             _logger.debug(msg)
             try:
                 self.downloaded = set(_download_classifiers().splitlines())
-            except Exception:
+            except Exception:  # noqa: BLE001
                 self.downloaded = False
                 _logger.debug("Problem with download, skipping validation")
                 return True
@@ -180,6 +218,7 @@ def __call__(self, value: str) -> bool:
     from trove_classifiers import classifiers as _trove_classifiers
 
     def trove_classifier(value: str) -> bool:
+        """See https://pypi.org/classifiers/"""
         return value in _trove_classifiers or value.lower().startswith("private ::")
 
 except ImportError:  # pragma: no cover
@@ -191,6 +230,10 @@ def trove_classifier(value: str) -> bool:
 
 
 def pep561_stub_name(value: str) -> bool:
+    """Name of a directory containing type stubs.
+    It must follow the name scheme ``-stubs`` as defined in
+    :pep:`561#stub-only-packages`.
+    """
     top, *children = value.split(".")
     if not top.endswith("-stubs"):
         return False
@@ -202,6 +245,10 @@ def pep561_stub_name(value: str) -> bool:
 
 
 def url(value: str) -> bool:
+    """Valid URL (validation uses :obj:`urllib.parse`).
+    For maximum compatibility please make sure to include a ``scheme`` prefix
+    in your URL (e.g. ``http://``).
+    """
     from urllib.parse import urlparse
 
     try:
@@ -212,42 +259,79 @@ def url(value: str) -> bool:
                 "`scheme` prefix in your URL (e.g. 'http://'). "
                 f"Given value: {value}"
             )
-            if not (value.startswith("/") or value.startswith("\\") or "@" in value):
+            if not (value.startswith(("/", "\\")) or "@" in value):
                 parts = urlparse(f"http://{value}")
 
         return bool(parts.scheme and parts.netloc)
-    except Exception:
+    except Exception:  # noqa: BLE001
         return False
 
 
 # https://packaging.python.org/specifications/entry-points/
 ENTRYPOINT_PATTERN = r"[^\[\s=]([^=]*[^\s=])?"
-ENTRYPOINT_REGEX = re.compile(f"^{ENTRYPOINT_PATTERN}$", re.I)
+ENTRYPOINT_REGEX = re.compile(f"^{ENTRYPOINT_PATTERN}$", re.IGNORECASE)
 RECOMMEDED_ENTRYPOINT_PATTERN = r"[\w.-]+"
-RECOMMEDED_ENTRYPOINT_REGEX = re.compile(f"^{RECOMMEDED_ENTRYPOINT_PATTERN}$", re.I)
+RECOMMEDED_ENTRYPOINT_REGEX = re.compile(
+    f"^{RECOMMEDED_ENTRYPOINT_PATTERN}$", re.IGNORECASE
+)
 ENTRYPOINT_GROUP_PATTERN = r"\w+(\.\w+)*"
-ENTRYPOINT_GROUP_REGEX = re.compile(f"^{ENTRYPOINT_GROUP_PATTERN}$", re.I)
+ENTRYPOINT_GROUP_REGEX = re.compile(f"^{ENTRYPOINT_GROUP_PATTERN}$", re.IGNORECASE)
 
 
 def python_identifier(value: str) -> bool:
+    """Can be used as identifier in Python.
+    (Validation uses :obj:`str.isidentifier`).
+    """
     return value.isidentifier()
 
 
 def python_qualified_identifier(value: str) -> bool:
+    """
+    Python "dotted identifier", i.e. a sequence of :obj:`python_identifier`
+    concatenated with ``"."`` (e.g.: ``package.module.submodule``).
+    """
     if value.startswith(".") or value.endswith("."):
         return False
     return all(python_identifier(m) for m in value.split("."))
 
 
 def python_module_name(value: str) -> bool:
+    """Module name that can be used in an ``import``-statement in Python.
+    See :obj:`python_qualified_identifier`.
+    """
     return python_qualified_identifier(value)
 
 
+def python_module_name_relaxed(value: str) -> bool:
+    """Similar to :obj:`python_module_name`, but relaxed to also accept
+    dash characters (``-``) and cover special cases like ``pip-run``.
+
+    It is recommended, however, that beginners avoid dash characters,
+    as they require advanced knowledge about Python internals.
+
+    The following are disallowed:
+
+    * names starting/ending in dashes,
+    * names ending in ``-stubs`` (potentially collide with :obj:`pep561_stub_name`).
+    """
+    if value.startswith("-") or value.endswith("-"):
+        return False
+    if value.endswith("-stubs"):
+        return False  # Avoid collision with PEP 561
+    return python_module_name(value.replace("-", "_"))
+
+
 def python_entrypoint_group(value: str) -> bool:
+    """See ``Data model > group`` in the :ref:`PyPA's entry-points specification
+    `.
+    """
     return ENTRYPOINT_GROUP_REGEX.match(value) is not None
 
 
 def python_entrypoint_name(value: str) -> bool:
+    """See ``Data model > name`` in the :ref:`PyPA's entry-points specification
+    `.
+    """
     if not ENTRYPOINT_REGEX.match(value):
         return False
     if not RECOMMEDED_ENTRYPOINT_REGEX.match(value):
@@ -258,6 +342,13 @@ def python_entrypoint_name(value: str) -> bool:
 
 
 def python_entrypoint_reference(value: str) -> bool:
+    """Reference to a Python object using in the format::
+
+        importable.module:object.attr
+
+    See ``Data model >object reference`` in the :ref:`PyPA's entry-points specification
+    `.
+    """
     module, _, rest = value.partition(":")
     if "[" in rest:
         obj, _, extras_ = rest.partition("[")
@@ -271,5 +362,103 @@ def python_entrypoint_reference(value: str) -> bool:
         obj = rest
 
     module_parts = module.split(".")
-    identifiers = _chain(module_parts, obj.split(".")) if rest else module_parts
+    identifiers = _chain(module_parts, obj.split(".")) if rest else iter(module_parts)
     return all(python_identifier(i.strip()) for i in identifiers)
+
+
+def uint8(value: builtins.int) -> bool:
+    r"""Unsigned 8-bit integer (:math:`0 \leq x < 2^8`)"""
+    return 0 <= value < 2**8
+
+
+def uint16(value: builtins.int) -> bool:
+    r"""Unsigned 16-bit integer (:math:`0 \leq x < 2^{16}`)"""
+    return 0 <= value < 2**16
+
+
+def uint32(value: builtins.int) -> bool:
+    r"""Unsigned 32-bit integer (:math:`0 \leq x < 2^{32}`)"""
+    return 0 <= value < 2**32
+
+
+def uint64(value: builtins.int) -> bool:
+    r"""Unsigned 64-bit integer (:math:`0 \leq x < 2^{64}`)"""
+    return 0 <= value < 2**64
+
+
+def uint(value: builtins.int) -> bool:
+    r"""Signed 64-bit integer (:math:`0 \leq x < 2^{64}`)"""
+    return 0 <= value < 2**64
+
+
+def int8(value: builtins.int) -> bool:
+    r"""Signed 8-bit integer (:math:`-2^{7} \leq x < 2^{7}`)"""
+    return -(2**7) <= value < 2**7
+
+
+def int16(value: builtins.int) -> bool:
+    r"""Signed 16-bit integer (:math:`-2^{15} \leq x < 2^{15}`)"""
+    return -(2**15) <= value < 2**15
+
+
+def int32(value: builtins.int) -> bool:
+    r"""Signed 32-bit integer (:math:`-2^{31} \leq x < 2^{31}`)"""
+    return -(2**31) <= value < 2**31
+
+
+def int64(value: builtins.int) -> bool:
+    r"""Signed 64-bit integer (:math:`-2^{63} \leq x < 2^{63}`)"""
+    return -(2**63) <= value < 2**63
+
+
+def int(value: builtins.int) -> bool:
+    r"""Signed 64-bit integer (:math:`-2^{63} \leq x < 2^{63}`)"""
+    return -(2**63) <= value < 2**63
+
+
+try:
+    from packaging import licenses as _licenses
+
+    def SPDX(value: str) -> bool:
+        """See :ref:`PyPA's License-Expression specification
+        ` (added in :pep:`639`).
+        """
+        try:
+            _licenses.canonicalize_license_expression(value)
+        except _licenses.InvalidLicenseExpression:
+            return False
+        return True
+
+except ImportError:  # pragma: no cover
+    _logger.warning(
+        "Could not find an up-to-date installation of `packaging`. "
+        "License expressions might not be validated. "
+        "To enforce validation, please install `packaging>=24.2`."
+    )
+
+    def SPDX(value: str) -> bool:  # noqa: ARG001
+        return True
+
+
+VALID_IMPORT_NAME = re.compile(
+    r"""
+    ^                                  # start of string
+        [A-Za-z_][A-Za-z_0-9]+         # a valid Python identifier
+        (?:\.[A-Za-z_][A-Za-z_0-9]*)*  # optionally followed by .identifier's
+    (?:\s*;\s*private)?                # optionally followed by ; private
+    $                                  # end of string
+    """,
+    re.VERBOSE,
+)
+
+
+def import_name(value: str) -> bool:
+    """This is a valid import name. It has to be series of python identifiers
+    (not keywords), separated by dots, optionally followed by a semicolon and
+    the keyword "private".
+    """
+    if VALID_IMPORT_NAME.match(value) is None:
+        return False
+
+    idents, _, _ = value.partition(";")
+    return all(not keyword.iskeyword(ident) for ident in idents.rstrip().split("."))
diff --git a/setuptools/config/distutils.schema.json b/setuptools/config/distutils.schema.json
new file mode 100644
index 0000000000..93cd2e868a
--- /dev/null
+++ b/setuptools/config/distutils.schema.json
@@ -0,0 +1,26 @@
+{
+  "$schema": "http://json-schema.org/draft-07/schema#",
+
+  "$id": "https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html",
+  "title": "``tool.distutils`` table",
+  "$$description": [
+    "**EXPERIMENTAL** (NOT OFFICIALLY SUPPORTED): Use ``tool.distutils``",
+    "subtables to configure arguments for ``distutils`` commands.",
+    "Originally, ``distutils`` allowed developers to configure arguments for",
+    "``setup.py`` commands via `distutils configuration files",
+    "`_.",
+    "See also `the old Python docs _`."
+  ],
+
+  "type": "object",
+  "properties": {
+    "global": {
+      "type": "object",
+      "description": "Global options applied to all ``distutils`` commands"
+    }
+  },
+  "patternProperties": {
+    ".+": {"type": "object"}
+  },
+  "$comment": "TODO: Is there a practical way of making this schema more specific?"
+}
diff --git a/setuptools/config/expand.py b/setuptools/config/expand.py
index 518f5ac260..fd29ddd6db 100644
--- a/setuptools/config/expand.py
+++ b/setuptools/config/expand.py
@@ -17,65 +17,55 @@
 
 **PRIVATE MODULE**: API reserved for setuptools internal usage only.
 """
+
+from __future__ import annotations
+
 import ast
 import importlib
-import io
 import os
 import pathlib
 import sys
-from glob import iglob
+from collections.abc import Callable, Iterable, Iterator, Mapping
 from configparser import ConfigParser
-from importlib.machinery import ModuleSpec
+from glob import iglob
+from importlib.machinery import ModuleSpec, all_suffixes
 from itertools import chain
-from typing import (
-    TYPE_CHECKING,
-    Callable,
-    Dict,
-    Iterable,
-    Iterator,
-    List,
-    Mapping,
-    Optional,
-    Tuple,
-    TypeVar,
-    Union,
-    cast,
-)
 from pathlib import Path
-from types import ModuleType
+from types import ModuleType, TracebackType
+from typing import TYPE_CHECKING, Any, TypeVar
 
-from distutils.errors import DistutilsOptionError
-
-from .._path import same_path as _same_path
+from .. import _static
+from .._path import StrPath, same_path as _same_path
+from ..discovery import find_package_path
 from ..warnings import SetuptoolsWarning
 
+from distutils.errors import DistutilsOptionError
+
 if TYPE_CHECKING:
-    from setuptools.dist import Distribution  # noqa
-    from setuptools.discovery import ConfigDiscovery  # noqa
-    from distutils.dist import DistributionMetadata  # noqa
+    from typing_extensions import Self
+
+    from setuptools.dist import Distribution
 
-chain_iter = chain.from_iterable
-_Path = Union[str, os.PathLike]
 _K = TypeVar("_K")
-_V = TypeVar("_V", covariant=True)
+_V_co = TypeVar("_V_co", covariant=True)
 
 
 class StaticModule:
     """Proxy to a module object that avoids executing arbitrary code."""
 
-    def __init__(self, name: str, spec: ModuleSpec):
-        module = ast.parse(pathlib.Path(spec.origin).read_bytes())
+    def __init__(self, name: str, spec: ModuleSpec) -> None:
+        module = ast.parse(pathlib.Path(spec.origin).read_bytes())  # type: ignore[arg-type] # Let it raise an error on None
         vars(self).update(locals())
         del self.self
 
-    def _find_assignments(self) -> Iterator[Tuple[ast.AST, ast.AST]]:
+    def _find_assignments(self) -> Iterator[tuple[ast.AST, ast.AST]]:
         for statement in self.module.body:
             if isinstance(statement, ast.Assign):
                 yield from ((target, statement.value) for target in statement.targets)
             elif isinstance(statement, ast.AnnAssign) and statement.value:
                 yield (statement.target, statement.value)
 
-    def __getattr__(self, attr):
+    def __getattr__(self, attr: str) -> Any:
         """Attempt to load an attribute "statically", via :func:`ast.literal_eval`."""
         try:
             return next(
@@ -88,8 +78,8 @@ def __getattr__(self, attr):
 
 
 def glob_relative(
-    patterns: Iterable[str], root_dir: Optional[_Path] = None
-) -> List[str]:
+    patterns: Iterable[str], root_dir: StrPath | None = None
+) -> list[str]:
     """Expand the list of glob patterns, but preserving relative paths.
 
     :param list[str] patterns: List of glob patterns
@@ -120,14 +110,16 @@ def glob_relative(
     return expanded_values
 
 
-def read_files(filepaths: Union[str, bytes, Iterable[_Path]], root_dir=None) -> str:
+def read_files(
+    filepaths: StrPath | Iterable[StrPath], root_dir: StrPath | None = None
+) -> str:
     """Return the content of the files concatenated using ``\n`` as str
 
     This function is sandboxed and won't reach anything outside ``root_dir``
 
     (By default ``root_dir`` is the current directory).
     """
-    from setuptools.extern.more_itertools import always_iterable
+    from more_itertools import always_iterable
 
     root_dir = os.path.abspath(root_dir or os.getcwd())
     _filepaths = (os.path.join(root_dir, path) for path in always_iterable(filepaths))
@@ -138,7 +130,7 @@ def read_files(filepaths: Union[str, bytes, Iterable[_Path]], root_dir=None) ->
     )
 
 
-def _filter_existing_files(filepaths: Iterable[_Path]) -> Iterator[_Path]:
+def _filter_existing_files(filepaths: Iterable[StrPath]) -> Iterator[StrPath]:
     for path in filepaths:
         if os.path.isfile(path):
             yield path
@@ -146,12 +138,12 @@ def _filter_existing_files(filepaths: Iterable[_Path]) -> Iterator[_Path]:
             SetuptoolsWarning.emit(f"File {path!r} cannot be found")
 
 
-def _read_file(filepath: Union[bytes, _Path]) -> str:
-    with io.open(filepath, encoding='utf-8') as f:
+def _read_file(filepath: bytes | StrPath) -> str:
+    with open(filepath, encoding='utf-8') as f:
         return f.read()
 
 
-def _assert_local(filepath: _Path, root_dir: str):
+def _assert_local(filepath: StrPath, root_dir: str):
     if Path(os.path.abspath(root_dir)) not in Path(os.path.abspath(filepath)).parents:
         msg = f"Cannot access {filepath!r} (or anything outside {root_dir!r})"
         raise DistutilsOptionError(msg)
@@ -161,9 +153,9 @@ def _assert_local(filepath: _Path, root_dir: str):
 
 def read_attr(
     attr_desc: str,
-    package_dir: Optional[Mapping[str, str]] = None,
-    root_dir: Optional[_Path] = None,
-):
+    package_dir: Mapping[str, str] | None = None,
+    root_dir: StrPath | None = None,
+) -> Any:
     """Reads the value of an attribute from a module.
 
     This function will try to read the attributed statically first
@@ -186,18 +178,20 @@ def read_attr(
     attr_name = attrs_path.pop()
     module_name = '.'.join(attrs_path)
     module_name = module_name or '__init__'
-    _parent_path, path, module_name = _find_module(module_name, package_dir, root_dir)
+    path = _find_module(module_name, package_dir, root_dir)
     spec = _find_spec(module_name, path)
 
     try:
-        return getattr(StaticModule(module_name, spec), attr_name)
+        value = getattr(StaticModule(module_name, spec), attr_name)
+        # XXX: Is marking as static contents coming from modules too optimistic?
+        return _static.attempt_conversion(value)
     except Exception:
         # fallback to evaluate module
         module = _load_spec(spec, module_name)
         return getattr(module, attr_name)
 
 
-def _find_spec(module_name: str, module_path: Optional[_Path]) -> ModuleSpec:
+def _find_spec(module_name: str, module_path: StrPath | None) -> ModuleSpec:
     spec = importlib.util.spec_from_file_location(module_name, module_path)
     spec = spec or importlib.util.find_spec(module_name)
 
@@ -213,48 +207,38 @@ def _load_spec(spec: ModuleSpec, module_name: str) -> ModuleType:
         return sys.modules[name]
     module = importlib.util.module_from_spec(spec)
     sys.modules[name] = module  # cache (it also ensures `==` works on loaded items)
-    spec.loader.exec_module(module)  # type: ignore
+    assert spec.loader is not None
+    spec.loader.exec_module(module)
     return module
 
 
 def _find_module(
-    module_name: str, package_dir: Optional[Mapping[str, str]], root_dir: _Path
-) -> Tuple[_Path, Optional[str], str]:
-    """Given a module (that could normally be imported by ``module_name``
-    after the build is complete), find the path to the parent directory where
-    it is contained and the canonical name that could be used to import it
-    considering the ``package_dir`` in the build configuration and ``root_dir``
+    module_name: str, package_dir: Mapping[str, str] | None, root_dir: StrPath
+) -> str | None:
+    """Find the path to the module named ``module_name``,
+    considering the ``package_dir`` in the build configuration and ``root_dir``.
+
+    >>> tmp = getfixture('tmpdir')
+    >>> _ = tmp.ensure("a/b/c.py")
+    >>> _ = tmp.ensure("a/b/d/__init__.py")
+    >>> r = lambda x: x.replace(str(tmp), "tmp").replace(os.sep, "/")
+    >>> r(_find_module("a.b.c", None, tmp))
+    'tmp/a/b/c.py'
+    >>> r(_find_module("f.g.h", {"": "1", "f": "2", "f.g": "3", "f.g.h": "a/b/d"}, tmp))
+    'tmp/a/b/d/__init__.py'
     """
-    parent_path = root_dir
-    module_parts = module_name.split('.')
-    if package_dir:
-        if module_parts[0] in package_dir:
-            # A custom path was specified for the module we want to import
-            custom_path = package_dir[module_parts[0]]
-            parts = custom_path.rsplit('/', 1)
-            if len(parts) > 1:
-                parent_path = os.path.join(root_dir, parts[0])
-                parent_module = parts[1]
-            else:
-                parent_module = custom_path
-            module_name = ".".join([parent_module, *module_parts[1:]])
-        elif '' in package_dir:
-            # A custom parent directory was specified for all root modules
-            parent_path = os.path.join(root_dir, package_dir[''])
-
-    path_start = os.path.join(parent_path, *module_name.split("."))
-    candidates = chain(
-        (f"{path_start}.py", os.path.join(path_start, "__init__.py")),
-        iglob(f"{path_start}.*"),
+    path_start = find_package_path(module_name, package_dir or {}, root_dir)
+    candidates = chain.from_iterable(
+        (f"{path_start}{ext}", os.path.join(path_start, f"__init__{ext}"))
+        for ext in all_suffixes()
     )
-    module_path = next((x for x in candidates if os.path.isfile(x)), None)
-    return parent_path, module_path, module_name
+    return next((x for x in candidates if os.path.isfile(x)), None)
 
 
 def resolve_class(
     qualified_class_name: str,
-    package_dir: Optional[Mapping[str, str]] = None,
-    root_dir: Optional[_Path] = None,
+    package_dir: Mapping[str, str] | None = None,
+    root_dir: StrPath | None = None,
 ) -> Callable:
     """Given a qualified class name, return the associated class object"""
     root_dir = root_dir or os.getcwd()
@@ -262,16 +246,16 @@ def resolve_class(
     class_name = qualified_class_name[idx + 1 :]
     pkg_name = qualified_class_name[:idx]
 
-    _parent_path, path, module_name = _find_module(pkg_name, package_dir, root_dir)
-    module = _load_spec(_find_spec(module_name, path), module_name)
+    path = _find_module(pkg_name, package_dir, root_dir)
+    module = _load_spec(_find_spec(pkg_name, path), pkg_name)
     return getattr(module, class_name)
 
 
 def cmdclass(
-    values: Dict[str, str],
-    package_dir: Optional[Mapping[str, str]] = None,
-    root_dir: Optional[_Path] = None,
-) -> Dict[str, Callable]:
+    values: dict[str, str],
+    package_dir: Mapping[str, str] | None = None,
+    root_dir: StrPath | None = None,
+) -> dict[str, Callable]:
     """Given a dictionary mapping command names to strings for qualified class
     names, apply :func:`resolve_class` to the dict values.
     """
@@ -281,10 +265,10 @@ def cmdclass(
 def find_packages(
     *,
     namespaces=True,
-    fill_package_dir: Optional[Dict[str, str]] = None,
-    root_dir: Optional[_Path] = None,
+    fill_package_dir: dict[str, str] | None = None,
+    root_dir: StrPath | None = None,
     **kwargs,
-) -> List[str]:
+) -> list[str]:
     """Works similarly to :func:`setuptools.find_packages`, but with all
     arguments given as keyword arguments. Moreover, ``where`` can be given
     as a list (the results will be simply concatenated).
@@ -302,17 +286,19 @@ def find_packages(
 
     :rtype: list
     """
+    from more_itertools import always_iterable, unique_everseen
+
     from setuptools.discovery import construct_package_dir
-    from setuptools.extern.more_itertools import unique_everseen, always_iterable
 
-    if namespaces:
-        from setuptools.discovery import PEP420PackageFinder as PackageFinder
+    # check "not namespaces" first due to python/mypy#6232
+    if not namespaces:
+        from setuptools.discovery import PackageFinder
     else:
-        from setuptools.discovery import PackageFinder  # type: ignore
+        from setuptools.discovery import PEP420PackageFinder as PackageFinder
 
     root_dir = root_dir or os.curdir
     where = kwargs.pop('where', ['.'])
-    packages: List[str] = []
+    packages: list[str] = []
     fill_package_dir = {} if fill_package_dir is None else fill_package_dir
     search = list(unique_everseen(always_iterable(where)))
 
@@ -331,27 +317,22 @@ def find_packages(
     return packages
 
 
-def _nest_path(parent: _Path, path: _Path) -> str:
+def _nest_path(parent: StrPath, path: StrPath) -> str:
     path = parent if path in {".", ""} else os.path.join(parent, path)
     return os.path.normpath(path)
 
 
-def version(value: Union[Callable, Iterable[Union[str, int]], str]) -> str:
+def version(value: Callable | Iterable[str | int] | str) -> str:
     """When getting the version directly from an attribute,
     it should be normalised to string.
     """
-    if callable(value):
-        value = value()
-
-    value = cast(Iterable[Union[str, int]], value)
-
-    if not isinstance(value, str):
-        if hasattr(value, '__iter__'):
-            value = '.'.join(map(str, value))
-        else:
-            value = '%s' % value
+    _value = value() if callable(value) else value
 
-    return value
+    if isinstance(_value, str):
+        return _value
+    if hasattr(_value, '__iter__'):
+        return '.'.join(map(str, _value))
+    return f'{_value}'
 
 
 def canonic_package_data(package_data: dict) -> dict:
@@ -361,8 +342,8 @@ def canonic_package_data(package_data: dict) -> dict:
 
 
 def canonic_data_files(
-    data_files: Union[list, dict], root_dir: Optional[_Path] = None
-) -> List[Tuple[str, List[str]]]:
+    data_files: list | dict, root_dir: StrPath | None = None
+) -> list[tuple[str, list[str]]]:
     """For compatibility with ``setup.py``, ``data_files`` should be a list
     of pairs instead of a dict.
 
@@ -377,14 +358,17 @@ def canonic_data_files(
     ]
 
 
-def entry_points(text: str, text_source="entry-points") -> Dict[str, dict]:
+def entry_points(
+    text: str, text_source: str = "entry-points"
+) -> dict[str, dict[str, str]]:
     """Given the contents of entry-points file,
     process it into a 2-level dictionary (``dict[str, dict[str, str]]``).
     The first level keys are entry-point groups, the second level keys are
     entry-point names, and the second level values are references to objects
     (that correspond to the entry-point value).
     """
-    parser = ConfigParser(default_section=None, delimiters=("=",))  # type: ignore
+    # Using undocumented behaviour, see python/typeshed#12700
+    parser = ConfigParser(default_section=None, delimiters=("=",))  # type: ignore[call-overload]
     parser.optionxform = str  # case sensitive
     parser.read_string(text, text_source)
     groups = {k: dict(v.items()) for k, v in parser.items()}
@@ -402,20 +386,25 @@ class EnsurePackagesDiscovered:
     and those might not have been processed yet.
     """
 
-    def __init__(self, distribution: "Distribution"):
+    def __init__(self, distribution: Distribution) -> None:
         self._dist = distribution
         self._called = False
 
-    def __call__(self):
+    def __call__(self) -> None:
         """Trigger the automatic package discovery, if it is still necessary."""
         if not self._called:
             self._called = True
             self._dist.set_defaults(name=False)  # Skip name, we can still be parsing
 
-    def __enter__(self):
+    def __enter__(self) -> Self:
         return self
 
-    def __exit__(self, _exc_type, _exc_value, _traceback):
+    def __exit__(
+        self,
+        exc_type: type[BaseException] | None,
+        exc_value: BaseException | None,
+        traceback: TracebackType | None,
+    ) -> None:
         if self._called:
             self._dist.set_defaults.analyse_name()  # Now we can set a default name
 
@@ -430,7 +419,7 @@ def package_dir(self) -> Mapping[str, str]:
         return LazyMappingProxy(self._get_package_dir)
 
 
-class LazyMappingProxy(Mapping[_K, _V]):
+class LazyMappingProxy(Mapping[_K, _V_co]):
     """Mapping proxy that delays resolving the target object, until really needed.
 
     >>> def obtain_mapping():
@@ -444,16 +433,16 @@ class LazyMappingProxy(Mapping[_K, _V]):
     'other value'
     """
 
-    def __init__(self, obtain_mapping_value: Callable[[], Mapping[_K, _V]]):
+    def __init__(self, obtain_mapping_value: Callable[[], Mapping[_K, _V_co]]) -> None:
         self._obtain = obtain_mapping_value
-        self._value: Optional[Mapping[_K, _V]] = None
+        self._value: Mapping[_K, _V_co] | None = None
 
-    def _target(self) -> Mapping[_K, _V]:
+    def _target(self) -> Mapping[_K, _V_co]:
         if self._value is None:
             self._value = self._obtain()
         return self._value
 
-    def __getitem__(self, key: _K) -> _V:
+    def __getitem__(self, key: _K) -> _V_co:
         return self._target()[key]
 
     def __len__(self) -> int:
diff --git a/setuptools/config/pyprojecttoml.py b/setuptools/config/pyprojecttoml.py
index 93dbd9f559..9e2b16c2e5 100644
--- a/setuptools/config/pyprojecttoml.py
+++ b/setuptools/config/pyprojecttoml.py
@@ -8,39 +8,45 @@
 For simple scenarios, you can also try parsing the file directly
 with the help of ``tomllib`` or ``tomli``.
 """
+
+from __future__ import annotations
+
 import logging
 import os
+from collections.abc import Callable, Mapping
 from contextlib import contextmanager
 from functools import partial
-from typing import TYPE_CHECKING, Callable, Dict, Mapping, Optional, Set, Union
+from types import TracebackType
+from typing import TYPE_CHECKING, Any
 
-from ..errors import FileError, OptionError
+from .._path import StrPath
+from ..errors import FileError, InvalidConfigError
 from ..warnings import SetuptoolsWarning
 from . import expand as _expand
-from ._apply_pyprojecttoml import _PREVIOUSLY_DEFINED, _WouldIgnoreField
-from ._apply_pyprojecttoml import apply as _apply
+from ._apply_pyprojecttoml import _PREVIOUSLY_DEFINED, _MissingDynamic, apply as _apply
 
 if TYPE_CHECKING:
-    from setuptools.dist import Distribution  # noqa
+    from typing_extensions import Self
+
+    from setuptools.dist import Distribution
 
-_Path = Union[str, os.PathLike]
 _logger = logging.getLogger(__name__)
 
 
-def load_file(filepath: _Path) -> dict:
-    from setuptools.extern import tomli  # type: ignore
+def load_file(filepath: StrPath) -> dict:
+    from ..compat.py310 import tomllib
 
     with open(filepath, "rb") as file:
-        return tomli.load(file)
+        return tomllib.load(file)
 
 
-def validate(config: dict, filepath: _Path) -> bool:
+def validate(config: dict, filepath: StrPath) -> bool:
     from . import _validate_pyproject as validator
 
     trove_classifier = validator.FORMAT_FUNCTIONS.get("trove-classifier")
     if hasattr(trove_classifier, "_disable_download"):
-        # Improve reproducibility by default. See issue 31 for validate-pyproject.
-        trove_classifier._disable_download()  # type: ignore
+        # Improve reproducibility by default. See abravalheri/validate-pyproject#31
+        trove_classifier._disable_download()  # type: ignore[union-attr]
 
     try:
         return validator.validate(config)
@@ -56,10 +62,10 @@ def validate(config: dict, filepath: _Path) -> bool:
 
 
 def apply_configuration(
-    dist: "Distribution",
-    filepath: _Path,
-    ignore_option_errors=False,
-) -> "Distribution":
+    dist: Distribution,
+    filepath: StrPath,
+    ignore_option_errors: bool = False,
+) -> Distribution:
     """Apply the configuration from a ``pyproject.toml`` file into an existing
     distribution object.
     """
@@ -68,11 +74,11 @@ def apply_configuration(
 
 
 def read_configuration(
-    filepath: _Path,
-    expand=True,
-    ignore_option_errors=False,
-    dist: Optional["Distribution"] = None,
-):
+    filepath: StrPath,
+    expand: bool = True,
+    ignore_option_errors: bool = False,
+    dist: Distribution | None = None,
+) -> dict[str, Any]:
     """Read given configuration file and returns options from it as a dict.
 
     :param str|unicode filepath: Path to configuration file in the ``pyproject.toml``
@@ -106,6 +112,10 @@ def read_configuration(
     if not asdict or not (project_table or setuptools_table):
         return {}  # User is not using pyproject to configure setuptools
 
+    if "setuptools" in asdict.get("tools", {}):
+        # let the user know they probably have a typo in their metadata
+        _ToolsTypoInMetadata.emit()
+
     if "distutils" in tool_table:
         _ExperimentalConfiguration.emit(subject="[tool.distutils]")
 
@@ -113,7 +123,7 @@ def read_configuration(
     # the default would be an improvement.
     # `ini2toml` backfills include_package_data=False when nothing is explicitly given,
     # therefore setting a default here is backwards compatible.
-    if dist and getattr(dist, "include_package_data", None) is not None:
+    if dist and dist.include_package_data is not None:
         setuptools_table.setdefault("include-package-data", dist.include_package_data)
     else:
         setuptools_table.setdefault("include-package-data", True)
@@ -121,6 +131,18 @@ def read_configuration(
     asdict["tool"] = tool_table
     tool_table["setuptools"] = setuptools_table
 
+    if "ext-modules" in setuptools_table:
+        _ExperimentalConfiguration.emit(subject="[tool.setuptools.ext-modules]")
+
+    fields = ("import-names", "import-namespaces")
+    places = (project_table, project_table.get("dynamic", []))
+    if any(field in place for field in fields for place in places):
+        raise NotImplementedError(
+            "Setuptools does not support `import-names` and `import-namespaces`"
+            " in `pyproject.toml` yet. If your are interested in this feature, "
+            " please consider submitting a contribution via pull requests."
+        )
+
     with _ignore_errors(ignore_option_errors):
         # Don't complain about unrelated errors (e.g. tools not using the "tool" table)
         subset = {"project": project_table, "tool": {"setuptools": setuptools_table}}
@@ -135,9 +157,9 @@ def read_configuration(
 
 def expand_configuration(
     config: dict,
-    root_dir: Optional[_Path] = None,
+    root_dir: StrPath | None = None,
     ignore_option_errors: bool = False,
-    dist: Optional["Distribution"] = None,
+    dist: Distribution | None = None,
 ) -> dict:
     """Given a configuration with unresolved fields (e.g. dynamic, cmdclass, ...)
     find their final values.
@@ -160,10 +182,10 @@ class _ConfigExpander:
     def __init__(
         self,
         config: dict,
-        root_dir: Optional[_Path] = None,
+        root_dir: StrPath | None = None,
         ignore_option_errors: bool = False,
-        dist: Optional["Distribution"] = None,
-    ):
+        dist: Distribution | None = None,
+    ) -> None:
         self.config = config
         self.root_dir = root_dir or os.getcwd()
         self.project_cfg = config.get("project", {})
@@ -172,9 +194,9 @@ def __init__(
         self.dynamic_cfg = self.setuptools_cfg.get("dynamic", {})
         self.ignore_option_errors = ignore_option_errors
         self._dist = dist
-        self._referenced_files: Set[str] = set()
+        self._referenced_files = set[str]()
 
-    def _ensure_dist(self) -> "Distribution":
+    def _ensure_dist(self) -> Distribution:
         from setuptools.dist import Distribution
 
         attrs = {"src_root": self.root_dir, "name": self.project_cfg.get("name", None)}
@@ -227,7 +249,7 @@ def _expand_cmdclass(self, package_dir: Mapping[str, str]):
         cmdclass = partial(_expand.cmdclass, package_dir=package_dir, root_dir=root_dir)
         self._process_field(self.setuptools_cfg, "cmdclass", cmdclass)
 
-    def _expand_all_dynamic(self, dist: "Distribution", package_dir: Mapping[str, str]):
+    def _expand_all_dynamic(self, dist: Distribution, package_dir: Mapping[str, str]):
         special = (  # need special handling
             "version",
             "readme",
@@ -257,7 +279,7 @@ def _expand_all_dynamic(self, dist: "Distribution", package_dir: Mapping[str, st
         updates = {k: v for k, v in obtained_dynamic.items() if v is not None}
         self.project_cfg.update(updates)
 
-    def _ensure_previously_set(self, dist: "Distribution", field: str):
+    def _ensure_previously_set(self, dist: Distribution, field: str):
         previous = _PREVIOUSLY_DEFINED[field](dist)
         if previous is None and not self.ignore_option_errors:
             msg = (
@@ -265,12 +287,12 @@ def _ensure_previously_set(self, dist: "Distribution", field: str):
                 "Some dynamic fields need to be specified via `tool.setuptools.dynamic`"
                 "\nothers must be specified via the equivalent attribute in `setup.py`."
             )
-            raise OptionError(msg)
+            raise InvalidConfigError(msg)
 
     def _expand_directive(
         self, specifier: str, directive, package_dir: Mapping[str, str]
     ):
-        from setuptools.extern.more_itertools import always_iterable  # type: ignore
+        from more_itertools import always_iterable
 
         with _ignore_errors(self.ignore_option_errors):
             root_dir = self.root_dir
@@ -282,7 +304,7 @@ def _expand_directive(
             raise ValueError(f"invalid `{specifier}`: {directive!r}")
         return None
 
-    def _obtain(self, dist: "Distribution", field: str, package_dir: Mapping[str, str]):
+    def _obtain(self, dist: Distribution, field: str, package_dir: Mapping[str, str]):
         if field in self.dynamic_cfg:
             return self._expand_directive(
                 f"tool.setuptools.dynamic.{field}",
@@ -292,29 +314,33 @@ def _obtain(self, dist: "Distribution", field: str, package_dir: Mapping[str, st
         self._ensure_previously_set(dist, field)
         return None
 
-    def _obtain_version(self, dist: "Distribution", package_dir: Mapping[str, str]):
+    def _obtain_version(self, dist: Distribution, package_dir: Mapping[str, str]):
         # Since plugins can set version, let's silently skip if it cannot be obtained
         if "version" in self.dynamic and "version" in self.dynamic_cfg:
-            return _expand.version(self._obtain(dist, "version", package_dir))
+            return _expand.version(
+                # We already do an early check for the presence of "version"
+                self._obtain(dist, "version", package_dir)  # pyright: ignore[reportArgumentType]
+            )
         return None
 
-    def _obtain_readme(self, dist: "Distribution") -> Optional[Dict[str, str]]:
+    def _obtain_readme(self, dist: Distribution) -> dict[str, str] | None:
         if "readme" not in self.dynamic:
             return None
 
         dynamic_cfg = self.dynamic_cfg
         if "readme" in dynamic_cfg:
             return {
+                # We already do an early check for the presence of "readme"
                 "text": self._obtain(dist, "readme", {}),
                 "content-type": dynamic_cfg["readme"].get("content-type", "text/x-rst"),
-            }
+            }  # pyright: ignore[reportReturnType]
 
         self._ensure_previously_set(dist, "readme")
         return None
 
     def _obtain_entry_points(
-        self, dist: "Distribution", package_dir: Mapping[str, str]
-    ) -> Optional[Dict[str, dict]]:
+        self, dist: Distribution, package_dir: Mapping[str, str]
+    ) -> dict[str, dict[str, Any]] | None:
         fields = ("entry-points", "scripts", "gui-scripts")
         if not any(field in self.dynamic for field in fields):
             return None
@@ -324,15 +350,14 @@ def _obtain_entry_points(
             return None
 
         groups = _expand.entry_points(text)
-        expanded = {"entry-points": groups}
+        # Any is str | dict[str, str], but causes variance issues
+        expanded: dict[str, dict[str, Any]] = {"entry-points": groups}
 
         def _set_scripts(field: str, group: str):
             if group in groups:
                 value = groups.pop(group)
                 if field not in self.dynamic:
-                    _WouldIgnoreField.emit(field=field, value=value)
-                # TODO: Don't set field when support for pyproject.toml stabilizes
-                #       instead raise an error as specified in PEP 621
+                    raise InvalidConfigError(_MissingDynamic.details(field, value))
                 expanded[field] = value
 
         _set_scripts("scripts", "console_scripts")
@@ -340,21 +365,21 @@ def _set_scripts(field: str, group: str):
 
         return expanded
 
-    def _obtain_classifiers(self, dist: "Distribution"):
+    def _obtain_classifiers(self, dist: Distribution):
         if "classifiers" in self.dynamic:
             value = self._obtain(dist, "classifiers", {})
             if value:
                 return value.splitlines()
         return None
 
-    def _obtain_dependencies(self, dist: "Distribution"):
+    def _obtain_dependencies(self, dist: Distribution):
         if "dependencies" in self.dynamic:
             value = self._obtain(dist, "dependencies", {})
             if value:
                 return _parse_requirements_list(value)
         return None
 
-    def _obtain_optional_dependencies(self, dist: "Distribution"):
+    def _obtain_optional_dependencies(self, dist: Distribution):
         if "optional-dependencies" not in self.dynamic:
             return None
         if "optional-dependencies" in self.dynamic_cfg:
@@ -396,18 +421,18 @@ def _ignore_errors(ignore_option_errors: bool):
 
 class _EnsurePackagesDiscovered(_expand.EnsurePackagesDiscovered):
     def __init__(
-        self, distribution: "Distribution", project_cfg: dict, setuptools_cfg: dict
-    ):
+        self, distribution: Distribution, project_cfg: dict, setuptools_cfg: dict
+    ) -> None:
         super().__init__(distribution)
         self._project_cfg = project_cfg
         self._setuptools_cfg = setuptools_cfg
 
-    def __enter__(self):
+    def __enter__(self) -> Self:
         """When entering the context, the values of ``packages``, ``py_modules`` and
         ``package_dir`` that are missing in ``dist`` are copied from ``setuptools_cfg``.
         """
         dist, cfg = self._dist, self._setuptools_cfg
-        package_dir: Dict[str, str] = cfg.setdefault("package-dir", {})
+        package_dir: dict[str, str] = cfg.setdefault("package-dir", {})
         package_dir.update(dist.package_dir or {})
         dist.package_dir = package_dir  # needs to be the same object
 
@@ -424,7 +449,12 @@ def __enter__(self):
 
         return super().__enter__()
 
-    def __exit__(self, exc_type, exc_value, traceback):
+    def __exit__(
+        self,
+        exc_type: type[BaseException] | None,
+        exc_value: BaseException | None,
+        traceback: TracebackType | None,
+    ) -> None:
         """When exiting the context, if values of ``packages``, ``py_modules`` and
         ``package_dir`` are missing in ``setuptools_cfg``, copy from ``dist``.
         """
@@ -439,3 +469,9 @@ class _ExperimentalConfiguration(SetuptoolsWarning):
         "`{subject}` in `pyproject.toml` is still *experimental* "
         "and likely to change in future releases."
     )
+
+
+class _ToolsTypoInMetadata(SetuptoolsWarning):
+    _SUMMARY = (
+        "Ignoring [tools.setuptools] in pyproject.toml, did you mean [tool.setuptools]?"
+    )
diff --git a/setuptools/config/setupcfg.py b/setuptools/config/setupcfg.py
index bb35559069..96aeb9a3c5 100644
--- a/setuptools/config/setupcfg.py
+++ b/setuptools/config/setupcfg.py
@@ -8,53 +8,48 @@
 For simple scenarios, you can also try parsing the file directly
 with the help of ``configparser``.
 """
+
+from __future__ import annotations
+
 import contextlib
 import functools
 import os
+from abc import abstractmethod
 from collections import defaultdict
-from functools import partial
-from functools import wraps
-from typing import (
-    TYPE_CHECKING,
-    Callable,
-    Any,
-    Dict,
-    Generic,
-    Iterable,
-    List,
-    Optional,
-    Set,
-    Tuple,
-    TypeVar,
-    Union,
-)
+from collections.abc import Callable, Iterable, Iterator
+from functools import partial, wraps
+from typing import TYPE_CHECKING, Any, ClassVar, Generic, TypeVar, cast
+
+from packaging.markers import default_environment as marker_env
+from packaging.requirements import InvalidRequirement, Requirement
+from packaging.version import InvalidVersion, Version
 
+from .. import _static
+from .._path import StrPath
 from ..errors import FileError, OptionError
-from ..extern.packaging.markers import default_environment as marker_env
-from ..extern.packaging.requirements import InvalidRequirement, Requirement
-from ..extern.packaging.specifiers import SpecifierSet
-from ..extern.packaging.version import InvalidVersion, Version
 from ..warnings import SetuptoolsDeprecationWarning
 from . import expand
 
 if TYPE_CHECKING:
-    from distutils.dist import DistributionMetadata  # noqa
+    from typing import TypeAlias
+
+    from setuptools.dist import Distribution
 
-    from setuptools.dist import Distribution  # noqa
+    from distutils.dist import DistributionMetadata
 
-_Path = Union[str, os.PathLike]
-SingleCommandOptions = Dict["str", Tuple["str", Any]]
+SingleCommandOptions: TypeAlias = dict[str, tuple[str, Any]]
 """Dict that associate the name of the options of a particular command to a
 tuple. The first element of the tuple indicates the origin of the option value
 (e.g. the name of the configuration file where it was read from),
 while the second element of the tuple is the option value itself
 """
-AllCommandOptions = Dict["str", SingleCommandOptions]  # cmd name => its options
-Target = TypeVar("Target", bound=Union["Distribution", "DistributionMetadata"])
+AllCommandOptions: TypeAlias = dict[str, SingleCommandOptions]
+"""cmd name => its options"""
+Target = TypeVar("Target", "Distribution", "DistributionMetadata")
 
 
 def read_configuration(
-    filepath: _Path, find_others=False, ignore_option_errors=False
+    filepath: StrPath, find_others: bool = False, ignore_option_errors: bool = False
 ) -> dict:
     """Read given configuration file and returns options from it as a dict.
 
@@ -79,7 +74,7 @@ def read_configuration(
     return configuration_to_dict(handlers)
 
 
-def apply_configuration(dist: "Distribution", filepath: _Path) -> "Distribution":
+def apply_configuration(dist: Distribution, filepath: StrPath) -> Distribution:
     """Apply the configuration from a ``setup.cfg`` file into an existing
     distribution object.
     """
@@ -89,11 +84,11 @@ def apply_configuration(dist: "Distribution", filepath: _Path) -> "Distribution"
 
 
 def _apply(
-    dist: "Distribution",
-    filepath: _Path,
-    other_files: Iterable[_Path] = (),
+    dist: Distribution,
+    filepath: StrPath,
+    other_files: Iterable[StrPath] = (),
     ignore_option_errors: bool = False,
-) -> Tuple["ConfigHandler", ...]:
+) -> tuple[ConfigMetadataHandler, ConfigOptionsHandler]:
     """Read configuration from ``filepath`` and applies to the ``dist`` object."""
     from setuptools.dist import _Distribution
 
@@ -107,7 +102,8 @@ def _apply(
     filenames = [*other_files, filepath]
 
     try:
-        _Distribution.parse_config_files(dist, filenames=filenames)
+        # TODO: Temporary cast until mypy 1.12 is released with upstream fixes from typeshed
+        _Distribution.parse_config_files(dist, filenames=cast(list[str], filenames))
         handlers = parse_configuration(
             dist, dist.command_options, ignore_option_errors=ignore_option_errors
         )
@@ -118,7 +114,7 @@ def _apply(
     return handlers
 
 
-def _get_option(target_obj: Target, key: str):
+def _get_option(target_obj: Distribution | DistributionMetadata, key: str):
     """
     Given a target object and option key, get that option from
     the target object, either through a get_{key} method or
@@ -130,10 +126,14 @@ def _get_option(target_obj: Target, key: str):
     return getter()
 
 
-def configuration_to_dict(handlers: Tuple["ConfigHandler", ...]) -> dict:
+def configuration_to_dict(
+    handlers: Iterable[
+        ConfigHandler[Distribution] | ConfigHandler[DistributionMetadata]
+    ],
+) -> dict:
     """Returns configuration data gathered by given handlers as a dict.
 
-    :param list[ConfigHandler] handlers: Handlers list,
+    :param Iterable[ConfigHandler] handlers: Handlers list,
         usually from parse_configuration()
 
     :rtype: dict
@@ -149,10 +149,10 @@ def configuration_to_dict(handlers: Tuple["ConfigHandler", ...]) -> dict:
 
 
 def parse_configuration(
-    distribution: "Distribution",
+    distribution: Distribution,
     command_options: AllCommandOptions,
-    ignore_option_errors=False,
-) -> Tuple["ConfigMetadataHandler", "ConfigOptionsHandler"]:
+    ignore_option_errors: bool = False,
+) -> tuple[ConfigMetadataHandler, ConfigOptionsHandler]:
     """Performs additional parsing of configuration options
     for a distribution.
 
@@ -235,7 +235,7 @@ class ConfigHandler(Generic[Target]):
 
     """
 
-    aliases: Dict[str, str] = {}
+    aliases: ClassVar[dict[str, str]] = {}
     """Options aliases.
     For compatibility with various packages. E.g.: d2to1 and pbr.
     Note: `-` in keys is replaced with `_` by config parser.
@@ -248,33 +248,36 @@ def __init__(
         options: AllCommandOptions,
         ignore_option_errors,
         ensure_discovered: expand.EnsurePackagesDiscovered,
-    ):
+    ) -> None:
         self.ignore_option_errors = ignore_option_errors
-        self.target_obj = target_obj
+        self.target_obj: Target = target_obj
         self.sections = dict(self._section_options(options))
-        self.set_options: List[str] = []
+        self.set_options: list[str] = []
         self.ensure_discovered = ensure_discovered
-        self._referenced_files: Set[str] = set()
+        self._referenced_files = set[str]()
         """After parsing configurations, this property will enumerate
         all files referenced by the "file:" directive. Private API for setuptools only.
         """
 
     @classmethod
-    def _section_options(cls, options: AllCommandOptions):
+    def _section_options(
+        cls, options: AllCommandOptions
+    ) -> Iterator[tuple[str, SingleCommandOptions]]:
         for full_name, value in options.items():
-            pre, sep, name = full_name.partition(cls.section_prefix)
+            pre, _sep, name = full_name.partition(cls.section_prefix)
             if pre:
                 continue
             yield name.lstrip('.'), value
 
     @property
-    def parsers(self):
+    @abstractmethod
+    def parsers(self) -> dict[str, Callable]:
         """Metadata item name to parser function mapping."""
         raise NotImplementedError(
-            '%s must provide .parsers property' % self.__class__.__name__
+            f'{self.__class__.__name__} must provide .parsers property'
         )
 
-    def __setitem__(self, option_name, value):
+    def __setitem__(self, option_name, value) -> None:
         target_obj = self.target_obj
 
         # Translate alias into real name.
@@ -282,8 +285,8 @@ def __setitem__(self, option_name, value):
 
         try:
             current_value = getattr(target_obj, option_name)
-        except AttributeError:
-            raise KeyError(option_name)
+        except AttributeError as e:
+            raise KeyError(option_name) from e
 
         if current_value:
             # Already inhabited. Skipping.
@@ -295,7 +298,7 @@ def __setitem__(self, option_name, value):
             return
 
         simple_setter = functools.partial(target_obj.__setattr__, option_name)
-        setter = getattr(target_obj, 'set_%s' % option_name, simple_setter)
+        setter = getattr(target_obj, f"set_{option_name}", simple_setter)
         setter(parsed)
 
         self.set_options.append(option_name)
@@ -363,14 +366,14 @@ def parser(value):
             exclude_directive = 'file:'
             if value.startswith(exclude_directive):
                 raise ValueError(
-                    'Only strings are accepted for the {0} field, '
-                    'files are not accepted'.format(key)
+                    f'Only strings are accepted for the {key} field, '
+                    'files are not accepted'
                 )
-            return value
+            return _static.Str(value)
 
         return parser
 
-    def _parse_file(self, value, root_dir: _Path):
+    def _parse_file(self, value, root_dir: StrPath | None):
         """Represents value as a string, allowing including text
         from nearest files using `file:` directive.
 
@@ -389,14 +392,15 @@ def _parse_file(self, value, root_dir: _Path):
             return value
 
         if not value.startswith(include_directive):
-            return value
+            return _static.Str(value)
 
         spec = value[len(include_directive) :]
         filepaths = [path.strip() for path in spec.split(',')]
         self._referenced_files.update(filepaths)
-        return expand.read_files(filepaths, root_dir)
+        # XXX: Is marking as static contents coming from files too optimistic?
+        return _static.Str(expand.read_files(filepaths, root_dir))
 
-    def _parse_attr(self, value, package_dir, root_dir: _Path):
+    def _parse_attr(self, value, package_dir, root_dir: StrPath):
         """Represents value as a module attribute.
 
         Examples:
@@ -408,7 +412,7 @@ def _parse_attr(self, value, package_dir, root_dir: _Path):
         """
         attr_directive = 'attr:'
         if not value.startswith(attr_directive):
-            return value
+            return _static.Str(value)
 
         attr_desc = value.replace(attr_directive, '')
 
@@ -464,7 +468,7 @@ def _parse_section_to_dict(cls, section_options, values_parser=None):
         parser = (lambda _, v: values_parser(v)) if values_parser else (lambda _, v: v)
         return cls._parse_section_to_dict_with_key(section_options, parser)
 
-    def parse_section(self, section_options):
+    def parse_section(self, section_options) -> None:
         """Parses configuration file section.
 
         :param dict section_options:
@@ -474,7 +478,7 @@ def parse_section(self, section_options):
                 # Keep silent for a new option may appear anytime.
                 self[name] = value
 
-    def parse(self):
+    def parse(self) -> None:
         """Parses configuration file items from one
         or more related sections.
 
@@ -482,12 +486,12 @@ def parse(self):
         for section_name, section_options in self.sections.items():
             method_postfix = ''
             if section_name:  # [section.option] variant
-                method_postfix = '_%s' % section_name
+                method_postfix = f"_{section_name}"
 
-            section_parser_method: Optional[Callable] = getattr(
+            section_parser_method: Callable | None = getattr(
                 self,
                 # Dots in section names are translated into dunderscores.
-                ('parse_section%s' % method_postfix).replace('.', '__'),
+                f'parse_section{method_postfix}'.replace('.', '__'),
                 None,
             )
 
@@ -533,51 +537,43 @@ class ConfigMetadataHandler(ConfigHandler["DistributionMetadata"]):
 
     def __init__(
         self,
-        target_obj: "DistributionMetadata",
+        target_obj: DistributionMetadata,
         options: AllCommandOptions,
         ignore_option_errors: bool,
         ensure_discovered: expand.EnsurePackagesDiscovered,
-        package_dir: Optional[dict] = None,
-        root_dir: _Path = os.curdir,
-    ):
+        package_dir: dict | None = None,
+        root_dir: StrPath | None = os.curdir,
+    ) -> None:
         super().__init__(target_obj, options, ignore_option_errors, ensure_discovered)
         self.package_dir = package_dir
         self.root_dir = root_dir
 
     @property
-    def parsers(self):
+    def parsers(self) -> dict[str, Callable]:
         """Metadata item name to parser function mapping."""
-        parse_list = self._parse_list
+        parse_list_static = self._get_parser_compound(self._parse_list, _static.List)
+        parse_dict_static = self._get_parser_compound(self._parse_dict, _static.Dict)
         parse_file = partial(self._parse_file, root_dir=self.root_dir)
-        parse_dict = self._parse_dict
         exclude_files_parser = self._exclude_files_parser
 
         return {
-            'platforms': parse_list,
-            'keywords': parse_list,
-            'provides': parse_list,
-            'requires': self._deprecated_config_handler(
-                parse_list,
-                "The requires parameter is deprecated, please use "
-                "install_requires for runtime dependencies.",
-                due_date=(2023, 10, 30),
-                # Warning introduced in 27 Oct 2018
-            ),
-            'obsoletes': parse_list,
-            'classifiers': self._get_parser_compound(parse_file, parse_list),
+            'author': _static.Str,
+            'author_email': _static.Str,
+            'maintainer': _static.Str,
+            'maintainer_email': _static.Str,
+            'platforms': parse_list_static,
+            'keywords': parse_list_static,
+            'provides': parse_list_static,
+            'obsoletes': parse_list_static,
+            'classifiers': self._get_parser_compound(parse_file, parse_list_static),
             'license': exclude_files_parser('license'),
-            'license_file': self._deprecated_config_handler(
-                exclude_files_parser('license_file'),
-                "The license_file parameter is deprecated, "
-                "use license_files instead.",
-                due_date=(2023, 10, 30),
-                # Warning introduced in 23 May 2021
-            ),
-            'license_files': parse_list,
+            'license_files': parse_list_static,
             'description': parse_file,
             'long_description': parse_file,
-            'version': self._parse_version,
-            'project_urls': parse_dict,
+            'long_description_content_type': _static.Str,
+            'version': self._parse_version,  # Cannot be marked as dynamic
+            'url': _static.Str,
+            'project_urls': parse_dict_static,
         }
 
     def _parse_version(self, value):
@@ -595,11 +591,11 @@ def _parse_version(self, value):
             # accidentally include newlines and other unintended content
             try:
                 Version(version)
-            except InvalidVersion:
+            except InvalidVersion as e:
                 raise OptionError(
                     f'Version loaded from {value} does not '
                     f'comply with PEP 440: {version}'
-                )
+                ) from e
 
             return version
 
@@ -611,14 +607,14 @@ class ConfigOptionsHandler(ConfigHandler["Distribution"]):
 
     def __init__(
         self,
-        target_obj: "Distribution",
+        target_obj: Distribution,
         options: AllCommandOptions,
         ignore_option_errors: bool,
         ensure_discovered: expand.EnsurePackagesDiscovered,
-    ):
+    ) -> None:
         super().__init__(target_obj, options, ignore_option_errors, ensure_discovered)
         self.root_dir = target_obj.src_root
-        self.package_dir: Dict[str, str] = {}  # To be filled by `find_packages`
+        self.package_dir: dict[str, str] = {}  # To be filled by `find_packages`
 
     @classmethod
     def _parse_list_semicolon(cls, value):
@@ -633,20 +629,20 @@ def _parse_requirements_list(self, label: str, value: str):
         _warn_accidental_env_marker_misconfig(label, value, parsed)
         # Filter it to only include lines that are not comments. `parse_list`
         # will have stripped each line and filtered out empties.
-        return [line for line in parsed if not line.startswith("#")]
+        return _static.List(line for line in parsed if not line.startswith("#"))
+        # ^-- Use `_static.List` to mark a non-`Dynamic` Core Metadata
 
     @property
-    def parsers(self):
+    def parsers(self) -> dict[str, Callable]:
         """Metadata item name to parser function mapping."""
         parse_list = self._parse_list
         parse_bool = self._parse_bool
-        parse_dict = self._parse_dict
         parse_cmdclass = self._parse_cmdclass
 
         return {
             'zip_safe': parse_bool,
             'include_package_data': parse_bool,
-            'package_dir': parse_dict,
+            'package_dir': self._parse_dict,
             'scripts': parse_list,
             'eager_resources': parse_list,
             'dependency_links': parse_list,
@@ -656,15 +652,14 @@ def parsers(self):
                 "consider using implicit namespaces instead (PEP 420).",
                 # TODO: define due date, see setuptools.dist:check_nsp.
             ),
-            'install_requires': partial(
+            'install_requires': partial(  # Core Metadata
                 self._parse_requirements_list, "install_requires"
             ),
             'setup_requires': self._parse_list_semicolon,
-            'tests_require': self._parse_list_semicolon,
             'packages': self._parse_packages,
             'entry_points': self._parse_file_in_root,
             'py_modules': parse_list,
-            'python_requires': SpecifierSet,
+            'python_requires': _static.SpecifierSet,  # Core Metadata
             'cmdclass': parse_cmdclass,
         }
 
@@ -707,10 +702,7 @@ def parse_section_packages__find(self, section_options):
         section_data = self._parse_section_to_dict(section_options, self._parse_list)
 
         valid_keys = ['where', 'include', 'exclude']
-
-        find_kwargs = dict(
-            [(k, v) for k, v in section_data.items() if k in valid_keys and v]
-        )
+        find_kwargs = {k: v for k, v in section_data.items() if k in valid_keys and v}
 
         where = find_kwargs.get('where')
         if where is not None:
@@ -718,7 +710,7 @@ def parse_section_packages__find(self, section_options):
 
         return find_kwargs
 
-    def parse_section_entry_points(self, section_options):
+    def parse_section_entry_points(self, section_options) -> None:
         """Parses `entry_points` configuration file section.
 
         :param dict section_options:
@@ -730,21 +722,21 @@ def _parse_package_data(self, section_options):
         package_data = self._parse_section_to_dict(section_options, self._parse_list)
         return expand.canonic_package_data(package_data)
 
-    def parse_section_package_data(self, section_options):
+    def parse_section_package_data(self, section_options) -> None:
         """Parses `package_data` configuration file section.
 
         :param dict section_options:
         """
         self['package_data'] = self._parse_package_data(section_options)
 
-    def parse_section_exclude_package_data(self, section_options):
+    def parse_section_exclude_package_data(self, section_options) -> None:
         """Parses `exclude_package_data` configuration file section.
 
         :param dict section_options:
         """
         self['exclude_package_data'] = self._parse_package_data(section_options)
 
-    def parse_section_extras_require(self, section_options):
+    def parse_section_extras_require(self, section_options) -> None:  # Core Metadata
         """Parses `extras_require` configuration file section.
 
         :param dict section_options:
@@ -754,9 +746,10 @@ def parse_section_extras_require(self, section_options):
             lambda k, v: self._parse_requirements_list(f"extras_require[{k}]", v),
         )
 
-        self['extras_require'] = parsed
+        self['extras_require'] = _static.Dict(parsed)
+        # ^-- Use `_static.Dict` to mark a non-`Dynamic` Core Metadata
 
-    def parse_section_data_files(self, section_options):
+    def parse_section_data_files(self, section_options) -> None:
         """Parses `data_files` configuration file section.
 
         :param dict section_options:
diff --git a/setuptools/config/setuptools.schema.json b/setuptools/config/setuptools.schema.json
new file mode 100644
index 0000000000..6146abde60
--- /dev/null
+++ b/setuptools/config/setuptools.schema.json
@@ -0,0 +1,433 @@
+{
+  "$schema": "http://json-schema.org/draft-07/schema#",
+
+  "$id": "https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html",
+  "title": "``tool.setuptools`` table",
+  "$$description": [
+    "``setuptools``-specific configurations that can be set by users that require",
+    "customization.",
+    "These configurations are completely optional and probably can be skipped when",
+    "creating simple packages. They are equivalent to some of the `Keywords",
+    "`_",
+    "used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.",
+    "It considers only ``setuptools`` `parameters",
+    "`_",
+    "that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``",
+    "and ``setup_requires`` (incompatible with modern workflows/standards)."
+  ],
+
+  "type": "object",
+  "additionalProperties": false,
+  "properties": {
+    "platforms": {
+      "type": "array",
+      "items": {"type": "string"}
+    },
+    "provides": {
+      "$$description": [
+        "Package and virtual package names contained within this package",
+        "**(not supported by pip)**"
+      ],
+      "type": "array",
+      "items": {"type": "string", "format": "pep508-identifier"}
+    },
+    "obsoletes": {
+      "$$description": [
+        "Packages which this package renders obsolete",
+        "**(not supported by pip)**"
+      ],
+      "type": "array",
+      "items": {"type": "string", "format": "pep508-identifier"}
+    },
+    "zip-safe": {
+      "$$description": [
+        "Whether the project can be safely installed and run from a zip file.",
+        "**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and",
+        "``setup.py install`` in the context of ``eggs`` (**DEPRECATED**)."
+      ],
+      "type": "boolean"
+    },
+    "script-files": {
+      "$$description": [
+        "Legacy way of defining scripts (entry-points are preferred).",
+        "Equivalent to the ``script`` keyword in ``setup.py``",
+        "(it was renamed to avoid confusion with entry-point based ``project.scripts``",
+        "defined in :pep:`621`).",
+        "**DISCOURAGED**: generic script wrappers are tricky and may not work properly.",
+        "Whenever possible, please use ``project.scripts`` instead."
+      ],
+      "type": "array",
+      "items": {"type": "string"},
+      "$comment": "TODO: is this field deprecated/should be removed?"
+    },
+    "eager-resources": {
+      "$$description": [
+        "Resources that should be extracted together, if any of them is needed,",
+        "or if any C extensions included in the project are imported.",
+        "**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and",
+        "``setup.py install`` in the context of ``eggs`` (**DEPRECATED**)."
+      ],
+      "type": "array",
+      "items": {"type": "string"}
+    },
+    "packages": {
+      "$$description": [
+        "Packages that should be included in the distribution.",
+        "It can be given either as a list of package identifiers",
+        "or as a ``dict``-like structure with a single key ``find``",
+        "which corresponds to a dynamic call to",
+        "``setuptools.config.expand.find_packages`` function.",
+        "The ``find`` key is associated with a nested ``dict``-like structure that can",
+        "contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,",
+        "mimicking the keyword arguments of the associated function."
+      ],
+      "oneOf": [
+        {
+          "title": "Array of Python package identifiers",
+          "type": "array",
+          "items": {"$ref": "#/definitions/package-name"}
+        },
+        {"$ref": "#/definitions/find-directive"}
+      ]
+    },
+    "package-dir": {
+      "$$description": [
+        ":class:`dict`-like structure mapping from package names to directories where their",
+        "code can be found.",
+        "The empty string (as key) means that all packages are contained inside",
+        "the given directory will be included in the distribution."
+      ],
+      "type": "object",
+      "additionalProperties": false,
+      "propertyNames": {
+        "anyOf": [{"const": ""}, {"$ref": "#/definitions/package-name"}]
+      },
+      "patternProperties": {
+        "^.*$": {"type": "string" }
+      }
+    },
+    "package-data": {
+      "$$description": [
+        "Mapping from package names to lists of glob patterns.",
+        "Usually this option is not needed when using ``include-package-data = true``",
+        "For more information on how to include data files, check ``setuptools`` `docs",
+        "`_."
+      ],
+      "type": "object",
+      "additionalProperties": false,
+      "propertyNames": {
+        "anyOf": [{"$ref": "#/definitions/package-name"}, {"const": "*"}]
+      },
+      "patternProperties": {
+        "^.*$": {"type": "array", "items": {"type": "string"}}
+      }
+    },
+    "include-package-data": {
+      "$$description": [
+        "Automatically include any data files inside the package directories",
+        "that are specified by ``MANIFEST.in``",
+        "For more information on how to include data files, check ``setuptools`` `docs",
+        "`_."
+      ],
+      "type": "boolean"
+    },
+    "exclude-package-data": {
+      "$$description": [
+        "Mapping from package names to lists of glob patterns that should be excluded",
+        "For more information on how to include data files, check ``setuptools`` `docs",
+        "`_."
+      ],
+      "type": "object",
+      "additionalProperties": false,
+      "propertyNames": {
+        "anyOf": [{"$ref": "#/definitions/package-name"}, {"const": "*"}]
+      },
+      "patternProperties": {
+          "^.*$": {"type": "array", "items": {"type": "string"}}
+      }
+    },
+    "namespace-packages": {
+      "type": "array",
+      "items": {"type": "string", "format": "python-module-name-relaxed"},
+      "$comment": "https://setuptools.pypa.io/en/latest/userguide/package_discovery.html",
+      "description": "**DEPRECATED**: use implicit namespaces instead (:pep:`420`)."
+    },
+    "py-modules": {
+      "description": "Modules that setuptools will manipulate",
+      "type": "array",
+      "items": {"type": "string", "format": "python-module-name-relaxed"},
+      "$comment": "TODO: clarify the relationship with ``packages``"
+    },
+    "ext-modules": {
+      "description": "Extension modules to be compiled by setuptools",
+      "type": "array",
+      "items": {"$ref": "#/definitions/ext-module"}
+    },
+    "data-files": {
+      "$$description": [
+        "``dict``-like structure where each key represents a directory and",
+        "the value is a list of glob patterns that should be installed in them.",
+        "**DISCOURAGED**: please notice this might not work as expected with wheels.",
+        "Whenever possible, consider using data files inside the package directories",
+        "(or create a new namespace package that only contains data files).",
+        "See `data files support",
+        "`_."
+      ],
+      "type": "object",
+      "patternProperties": {
+          "^.*$": {"type": "array", "items": {"type": "string"}}
+      }
+    },
+    "cmdclass": {
+      "$$description": [
+        "Mapping of distutils-style command names to ``setuptools.Command`` subclasses",
+        "which in turn should be represented by strings with a qualified class name",
+        "(i.e., \"dotted\" form with module), e.g.::\n\n",
+        "    cmdclass = {mycmd = \"pkg.subpkg.module.CommandClass\"}\n\n",
+        "The command class should be a directly defined at the top-level of the",
+        "containing module (no class nesting)."
+      ],
+      "type": "object",
+      "patternProperties": {
+          "^.*$": {"type": "string", "format": "python-qualified-identifier"}
+      }
+    },
+    "license-files": {
+      "type": "array",
+      "items": {"type": "string"},
+      "$$description": [
+        "**PROVISIONAL**: list of glob patterns for all license files being distributed.",
+        "(likely to become standard with :pep:`639`).",
+        "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"
+      ],
+      "$comment": "TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?"
+    },
+    "dynamic": {
+      "type": "object",
+      "description": "Instructions for loading :pep:`621`-related metadata dynamically",
+      "additionalProperties": false,
+      "properties": {
+        "version": {
+          "$$description": [
+            "A version dynamically loaded via either the ``attr:`` or ``file:``",
+            "directives. Please make sure the given file or attribute respects :pep:`440`.",
+            "Also ensure to set ``project.dynamic`` accordingly."
+          ],
+          "oneOf": [
+            {"$ref": "#/definitions/attr-directive"},
+            {"$ref": "#/definitions/file-directive"}
+          ]
+        },
+        "classifiers": {"$ref": "#/definitions/file-directive"},
+        "description": {"$ref": "#/definitions/file-directive"},
+        "entry-points": {"$ref": "#/definitions/file-directive"},
+        "dependencies": {"$ref": "#/definitions/file-directive-for-dependencies"},
+        "optional-dependencies": {
+          "type": "object",
+          "propertyNames": {"type": "string", "format": "pep508-identifier"},
+          "additionalProperties": false,
+          "patternProperties": {
+            ".+": {"$ref": "#/definitions/file-directive-for-dependencies"}
+          }
+        },
+        "readme": {
+          "type": "object",
+          "anyOf": [
+            {"$ref": "#/definitions/file-directive"},
+            {
+              "type": "object",
+              "properties": {
+                "content-type": {"type": "string"},
+                "file": { "$ref": "#/definitions/file-directive/properties/file" }
+              },
+              "additionalProperties": false}
+          ],
+          "required": ["file"]
+        }
+      }
+    }
+  },
+
+  "definitions": {
+    "package-name": {
+      "$id": "#/definitions/package-name",
+      "title": "Valid package name",
+      "description": "Valid package name (importable or :pep:`561`).",
+      "type": "string",
+      "anyOf": [
+        {"type": "string", "format": "python-module-name-relaxed"},
+        {"type": "string", "format": "pep561-stub-name"}
+      ]
+    },
+    "ext-module": {
+      "$id": "#/definitions/ext-module",
+      "title": "Extension module",
+      "description": "Parameters to construct a :class:`setuptools.Extension` object",
+      "type": "object",
+      "required": ["name", "sources"],
+      "additionalProperties": false,
+      "properties": {
+        "name": {
+          "type": "string",
+          "format": "python-module-name-relaxed"
+        },
+        "sources": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "include-dirs":{
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "define-macros": {
+          "type": "array",
+          "items": {
+            "type": "array",
+            "items": [
+              {"description": "macro name", "type": "string"},
+              {"description": "macro value", "oneOf": [{"type": "string"}, {"type": "null"}]}
+            ],
+            "additionalItems": false
+          }
+        },
+        "undef-macros": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "library-dirs": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "libraries": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "runtime-library-dirs": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "extra-objects": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "extra-compile-args": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "extra-link-args": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "export-symbols": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "swig-opts": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "depends": {
+          "type": "array",
+          "items": {"type": "string"}
+        },
+        "language": {"type": "string"},
+        "optional": {"type": "boolean"},
+        "py-limited-api": {"type": "boolean"}
+      }
+    },
+    "file-directive": {
+      "$id": "#/definitions/file-directive",
+      "title": "'file:' directive",
+      "description":
+        "Value is read from a file (or list of files and then concatenated)",
+      "type": "object",
+      "additionalProperties": false,
+      "properties": {
+        "file": {
+          "oneOf": [
+            {"type": "string"},
+            {"type": "array", "items": {"type": "string"}}
+          ]
+        }
+      },
+      "required": ["file"]
+    },
+    "file-directive-for-dependencies": {
+      "title": "'file:' directive for dependencies",
+      "allOf": [
+        {
+          "$$description": [
+            "**BETA**: subset of the ``requirements.txt`` format",
+            "without ``pip`` flags and options",
+            "(one :pep:`508`-compliant string per line,",
+            "lines that are blank or start with ``#`` are excluded).",
+            "See `dynamic metadata",
+            "`_."
+          ]
+        },
+        {"$ref": "#/definitions/file-directive"}
+      ]
+    },
+    "attr-directive": {
+      "title": "'attr:' directive",
+      "$id": "#/definitions/attr-directive",
+      "$$description": [
+        "Value is read from a module attribute. Supports callables and iterables;",
+        "unsupported types are cast via ``str()``"
+      ],
+      "type": "object",
+      "additionalProperties": false,
+      "properties": {
+        "attr": {"type": "string", "format": "python-qualified-identifier"}
+      },
+      "required": ["attr"]
+    },
+    "find-directive": {
+      "$id": "#/definitions/find-directive",
+      "title": "'find:' directive",
+      "type": "object",
+      "additionalProperties": false,
+      "properties": {
+        "find": {
+          "type": "object",
+          "$$description": [
+            "Dynamic `package discovery",
+            "`_."
+          ],
+          "additionalProperties": false,
+          "properties": {
+            "where": {
+              "description":
+                "Directories to be searched for packages (Unix-style relative path)",
+              "type": "array",
+              "items": {"type": "string"}
+            },
+            "exclude": {
+              "type": "array",
+              "$$description": [
+                "Exclude packages that match the values listed in this field.",
+                "Can container shell-style wildcards (e.g. ``'pkg.*'``)"
+              ],
+              "items": {"type": "string"}
+            },
+            "include": {
+              "type": "array",
+              "$$description": [
+                "Restrict the found packages to just the ones listed in this field.",
+                "Can container shell-style wildcards (e.g. ``'pkg.*'``)"
+              ],
+              "items": {"type": "string"}
+            },
+            "namespaces": {
+              "type": "boolean",
+              "$$description": [
+                "When ``True``, directories without a ``__init__.py`` file will also",
+                "be scanned for :pep:`420`-style implicit namespaces"
+              ]
+            }
+          }
+        }
+      }
+    }
+  }
+}
diff --git a/setuptools/dep_util.py b/setuptools/dep_util.py
deleted file mode 100644
index dc9ccf62c2..0000000000
--- a/setuptools/dep_util.py
+++ /dev/null
@@ -1,24 +0,0 @@
-from distutils.dep_util import newer_group
-
-
-# yes, this is was almost entirely copy-pasted from
-# 'newer_pairwise()', this is just another convenience
-# function.
-def newer_pairwise_group(sources_groups, targets):
-    """Walk both arguments in parallel, testing if each source group is newer
-    than its corresponding target. Returns a pair of lists (sources_groups,
-    targets) where sources is newer than target, according to the semantics
-    of 'newer_group()'.
-    """
-    if len(sources_groups) != len(targets):
-        raise ValueError("'sources_group' and 'targets' must be the same length")
-
-    # build a pair of lists (sources_groups, targets) where source is newer
-    n_sources = []
-    n_targets = []
-    for i in range(len(sources_groups)):
-        if newer_group(sources_groups[i], targets[i]):
-            n_sources.append(sources_groups[i])
-            n_targets.append(targets[i])
-
-    return n_sources, n_targets
diff --git a/setuptools/depends.py b/setuptools/depends.py
index 180e820459..e5223b7956 100644
--- a/setuptools/depends.py
+++ b/setuptools/depends.py
@@ -1,23 +1,34 @@
-import sys
-import marshal
+from __future__ import annotations
+
 import contextlib
 import dis
+import marshal
+import sys
+from types import CodeType
+from typing import Any, Literal, TypeVar
 
+from packaging.version import Version
 
 from . import _imp
-from ._imp import find_module, PY_COMPILED, PY_FROZEN, PY_SOURCE
-from .extern.packaging.version import Version
+from ._imp import PY_COMPILED, PY_FROZEN, PY_SOURCE, find_module
 
+_T = TypeVar("_T")
 
-__all__ = ['Require', 'find_module', 'get_module_constant', 'extract_constant']
+__all__ = ['Require', 'find_module']
 
 
 class Require:
     """A prerequisite to building or installing a distribution"""
 
     def __init__(
-        self, name, requested_version, module, homepage='', attribute=None, format=None
-    ):
+        self,
+        name,
+        requested_version,
+        module,
+        homepage: str = '',
+        attribute=None,
+        format=None,
+    ) -> None:
         if format is None and requested_version is not None:
             format = Version
 
@@ -32,7 +43,7 @@ def __init__(
     def full_name(self):
         """Return full package/distribution name, w/version"""
         if self.requested_version is not None:
-            return '%s-%s' % (self.name, self.requested_version)
+            return f'{self.name}-{self.requested_version}'
         return self.name
 
     def version_ok(self, version):
@@ -44,7 +55,9 @@ def version_ok(self, version):
             and self.format(version) >= self.requested_version
         )
 
-    def get_version(self, paths=None, default="unknown"):
+    def get_version(
+        self, paths=None, default: _T | Literal["unknown"] = "unknown"
+    ) -> _T | Literal["unknown"] | None | Any:
         """Get version number of installed module, 'None', or 'default'
 
         Search 'paths' for module.  If not found, return 'None'.  If found,
@@ -57,12 +70,12 @@ def get_version(self, paths=None, default="unknown"):
 
         if self.attribute is None:
             try:
-                f, p, i = find_module(self.module, paths)
-                if f:
-                    f.close()
-                return default
+                f, _p, _i = find_module(self.module, paths)
             except ImportError:
                 return None
+            if f:
+                f.close()
+            return default
 
         v = get_module_constant(self.module, self.attribute, default, paths)
 
@@ -95,84 +108,78 @@ def empty():
     return contextlib.closing(f)
 
 
-def get_module_constant(module, symbol, default=-1, paths=None):
-    """Find 'module' by searching 'paths', and extract 'symbol'
-
-    Return 'None' if 'module' does not exist on 'paths', or it does not define
-    'symbol'.  If the module defines 'symbol' as a constant, return the
-    constant.  Otherwise, return 'default'."""
-
-    try:
-        f, path, (suffix, mode, kind) = info = find_module(module, paths)
-    except ImportError:
-        # Module doesn't exist
-        return None
-
-    with maybe_close(f):
-        if kind == PY_COMPILED:
-            f.read(8)  # skip magic & date
-            code = marshal.load(f)
-        elif kind == PY_FROZEN:
-            code = _imp.get_frozen_object(module, paths)
-        elif kind == PY_SOURCE:
-            code = compile(f.read(), path, 'exec')
-        else:
-            # Not something we can parse; we'll have to import it.  :(
-            imported = _imp.get_module(module, paths, info)
-            return getattr(imported, symbol, None)
-
-    return extract_constant(code, symbol, default)
-
-
-def extract_constant(code, symbol, default=-1):
-    """Extract the constant value of 'symbol' from 'code'
-
-    If the name 'symbol' is bound to a constant value by the Python code
-    object 'code', return that value.  If 'symbol' is bound to an expression,
-    return 'default'.  Otherwise, return 'None'.
-
-    Return value is based on the first assignment to 'symbol'.  'symbol' must
-    be a global, or at least a non-"fast" local in the code block.  That is,
-    only 'STORE_NAME' and 'STORE_GLOBAL' opcodes are checked, and 'symbol'
-    must be present in 'code.co_names'.
-    """
-    if symbol not in code.co_names:
-        # name's not there, can't possibly be an assignment
-        return None
-
-    name_idx = list(code.co_names).index(symbol)
-
-    STORE_NAME = 90
-    STORE_GLOBAL = 97
-    LOAD_CONST = 100
-
-    const = default
-
-    for byte_code in dis.Bytecode(code):
-        op = byte_code.opcode
-        arg = byte_code.arg
+# Some objects are not available on some platforms.
+# XXX it'd be better to test assertions about bytecode instead.
+if not sys.platform.startswith('java') and sys.platform != 'cli':
+
+    def get_module_constant(
+        module, symbol, default: _T | int = -1, paths=None
+    ) -> _T | int | None | Any:
+        """Find 'module' by searching 'paths', and extract 'symbol'
+
+        Return 'None' if 'module' does not exist on 'paths', or it does not define
+        'symbol'.  If the module defines 'symbol' as a constant, return the
+        constant.  Otherwise, return 'default'."""
+
+        try:
+            f, path, (_suffix, _mode, kind) = info = find_module(module, paths)
+        except ImportError:
+            # Module doesn't exist
+            return None
+
+        with maybe_close(f):
+            if kind == PY_COMPILED:
+                f.read(8)  # skip magic & date
+                code = marshal.load(f)
+            elif kind == PY_FROZEN:
+                code = _imp.get_frozen_object(module, paths)
+            elif kind == PY_SOURCE:
+                code = compile(f.read(), path, 'exec')
+            else:
+                # Not something we can parse; we'll have to import it.  :(
+                imported = _imp.get_module(module, paths, info)
+                return getattr(imported, symbol, None)
+
+        return extract_constant(code, symbol, default)
+
+    def extract_constant(
+        code: CodeType, symbol: str, default: _T | int = -1
+    ) -> _T | int | None | Any:
+        """Extract the constant value of 'symbol' from 'code'
+
+        If the name 'symbol' is bound to a constant value by the Python code
+        object 'code', return that value.  If 'symbol' is bound to an expression,
+        return 'default'.  Otherwise, return 'None'.
+
+        Return value is based on the first assignment to 'symbol'.  'symbol' must
+        be a global, or at least a non-"fast" local in the code block.  That is,
+        only 'STORE_NAME' and 'STORE_GLOBAL' opcodes are checked, and 'symbol'
+        must be present in 'code.co_names'.
+        """
+        if symbol not in code.co_names:
+            # name's not there, can't possibly be an assignment
+            return None
 
-        if op == LOAD_CONST:
-            const = code.co_consts[arg]
-        elif arg == name_idx and (op == STORE_NAME or op == STORE_GLOBAL):
-            return const
-        else:
-            const = default
+        name_idx = list(code.co_names).index(symbol)
 
+        STORE_NAME = dis.opmap['STORE_NAME']
+        STORE_GLOBAL = dis.opmap['STORE_GLOBAL']
+        LOAD_CONST = dis.opmap['LOAD_CONST']
 
-def _update_globals():
-    """
-    Patch the globals to remove the objects not available on some platforms.
+        const = default
 
-    XXX it'd be better to test assertions about bytecode instead.
-    """
+        for byte_code in dis.Bytecode(code):
+            op = byte_code.opcode
+            arg = byte_code.arg
 
-    if not sys.platform.startswith('java') and sys.platform != 'cli':
-        return
-    incompatible = 'extract_constant', 'get_module_constant'
-    for name in incompatible:
-        del globals()[name]
-        __all__.remove(name)
+            if op == LOAD_CONST:
+                assert arg is not None
+                const = code.co_consts[arg]
+            elif arg == name_idx and (op == STORE_NAME or op == STORE_GLOBAL):
+                return const
+            else:
+                const = default
 
+        return None
 
-_update_globals()
+    __all__ += ['get_module_constant', 'extract_constant']
diff --git a/setuptools/discovery.py b/setuptools/discovery.py
index 25962863b9..296d3193ab 100644
--- a/setuptools/discovery.py
+++ b/setuptools/discovery.py
@@ -37,38 +37,30 @@
 
 """
 
+from __future__ import annotations
+
 import itertools
 import os
+from collections.abc import Iterable, Iterator, Mapping
 from fnmatch import fnmatchcase
 from glob import glob
 from pathlib import Path
-from typing import (
-    TYPE_CHECKING,
-    Dict,
-    Iterable,
-    Iterator,
-    List,
-    Mapping,
-    Optional,
-    Tuple,
-    Union,
-)
+from typing import TYPE_CHECKING, ClassVar
 
 import _distutils_hack.override  # noqa: F401
 
+from ._path import StrPath
+
 from distutils import log
 from distutils.util import convert_path
 
-_Path = Union[str, os.PathLike]
-StrIter = Iterator[str]
+if TYPE_CHECKING:
+    from setuptools import Distribution
 
 chain_iter = itertools.chain.from_iterable
 
-if TYPE_CHECKING:
-    from setuptools import Distribution  # noqa
 
-
-def _valid_name(path: _Path) -> bool:
+def _valid_name(path: StrPath) -> bool:
     # Ignore invalid names that cannot be imported directly
     return os.path.basename(path).isidentifier()
 
@@ -79,7 +71,7 @@ class _Filter:
     the input matches at least one of the patterns.
     """
 
-    def __init__(self, *patterns: str):
+    def __init__(self, *patterns: str) -> None:
         self._patterns = dict.fromkeys(patterns)
 
     def __call__(self, item: str) -> bool:
@@ -92,33 +84,33 @@ def __contains__(self, item: str) -> bool:
 class _Finder:
     """Base class that exposes functionality for module/package finders"""
 
-    ALWAYS_EXCLUDE: Tuple[str, ...] = ()
-    DEFAULT_EXCLUDE: Tuple[str, ...] = ()
+    ALWAYS_EXCLUDE: ClassVar[tuple[str, ...]] = ()
+    DEFAULT_EXCLUDE: ClassVar[tuple[str, ...]] = ()
 
     @classmethod
     def find(
         cls,
-        where: _Path = '.',
+        where: StrPath = '.',
         exclude: Iterable[str] = (),
         include: Iterable[str] = ('*',),
-    ) -> List[str]:
+    ) -> list[str]:
         """Return a list of all Python items (packages or modules, depending on
-        the finder implementation) found within directory 'where'.
+        the finder implementation) found within directory ``where``.
 
-        'where' is the root directory which will be searched.
+        ``where`` is the root directory which will be searched.
         It should be supplied as a "cross-platform" (i.e. URL-style) path;
         it will be converted to the appropriate local path syntax.
 
-        'exclude' is a sequence of names to exclude; '*' can be used
+        ``exclude`` is a sequence of names to exclude; ``*`` can be used
         as a wildcard in the names.
-        When finding packages, 'foo.*' will exclude all subpackages of 'foo'
-        (but not 'foo' itself).
+        When finding packages, ``foo.*`` will exclude all subpackages of ``foo``
+        (but not ``foo`` itself).
 
-        'include' is a sequence of names to include.
+        ``include`` is a sequence of names to include.
         If it's specified, only the named items will be included.
         If it's not specified, all found items will be included.
-        'include' can contain shell style wildcard patterns just like
-        'exclude'.
+        ``include`` can contain shell style wildcard patterns just like
+        ``exclude``.
         """
 
         exclude = exclude or cls.DEFAULT_EXCLUDE
@@ -131,7 +123,9 @@ def find(
         )
 
     @classmethod
-    def _find_iter(cls, where: _Path, exclude: _Filter, include: _Filter) -> StrIter:
+    def _find_iter(
+        cls, where: StrPath, exclude: _Filter, include: _Filter
+    ) -> Iterator[str]:
         raise NotImplementedError
 
 
@@ -143,7 +137,9 @@ class PackageFinder(_Finder):
     ALWAYS_EXCLUDE = ("ez_setup", "*__pycache__")
 
     @classmethod
-    def _find_iter(cls, where: _Path, exclude: _Filter, include: _Filter) -> StrIter:
+    def _find_iter(
+        cls, where: StrPath, exclude: _Filter, include: _Filter
+    ) -> Iterator[str]:
         """
         All the packages found in 'where' that pass the 'include' filter, but
         not the 'exclude' filter.
@@ -175,14 +171,14 @@ def _find_iter(cls, where: _Path, exclude: _Filter, include: _Filter) -> StrIter
                 dirs.append(dir)
 
     @staticmethod
-    def _looks_like_package(path: _Path, _package_name: str) -> bool:
+    def _looks_like_package(path: StrPath, _package_name: str) -> bool:
         """Does a directory look like a package?"""
         return os.path.isfile(os.path.join(path, '__init__.py'))
 
 
 class PEP420PackageFinder(PackageFinder):
     @staticmethod
-    def _looks_like_package(_path: _Path, _package_name: str) -> bool:
+    def _looks_like_package(_path: StrPath, _package_name: str) -> bool:
         return True
 
 
@@ -192,7 +188,9 @@ class ModuleFinder(_Finder):
     """
 
     @classmethod
-    def _find_iter(cls, where: _Path, exclude: _Filter, include: _Filter) -> StrIter:
+    def _find_iter(
+        cls, where: StrPath, exclude: _Filter, include: _Filter
+    ) -> Iterator[str]:
         for file in glob(os.path.join(where, "*.py")):
             module, _ext = os.path.splitext(os.path.basename(file))
 
@@ -255,7 +253,7 @@ class FlatLayoutPackageFinder(PEP420PackageFinder):
     """Reserved package names"""
 
     @staticmethod
-    def _looks_like_package(_path: _Path, package_name: str) -> bool:
+    def _looks_like_package(_path: StrPath, package_name: str) -> bool:
         names = package_name.split('.')
         # Consider PEP 561
         root_pkg_is_valid = names[0].isidentifier() or names[0].endswith("-stubs")
@@ -292,7 +290,7 @@ class FlatLayoutModuleFinder(ModuleFinder):
     """Reserved top-level module names"""
 
 
-def _find_packages_within(root_pkg: str, pkg_dir: _Path) -> List[str]:
+def _find_packages_within(root_pkg: str, pkg_dir: StrPath) -> list[str]:
     nested = PEP420PackageFinder.find(pkg_dir)
     return [root_pkg] + [".".join((root_pkg, n)) for n in nested]
 
@@ -302,7 +300,7 @@ class ConfigDiscovery:
     (from other metadata/options, the file system or conventions)
     """
 
-    def __init__(self, distribution: "Distribution"):
+    def __init__(self, distribution: Distribution) -> None:
         self.dist = distribution
         self._called = False
         self._disabled = False
@@ -325,17 +323,19 @@ def _ignore_ext_modules(self):
         self._skip_ext_modules = True
 
     @property
-    def _root_dir(self) -> _Path:
+    def _root_dir(self) -> StrPath:
         # The best is to wait until `src_root` is set in dist, before using _root_dir.
         return self.dist.src_root or os.curdir
 
     @property
-    def _package_dir(self) -> Dict[str, str]:
+    def _package_dir(self) -> dict[str, str]:
         if self.dist.package_dir is None:
             return {}
         return self.dist.package_dir
 
-    def __call__(self, force=False, name=True, ignore_ext_modules=False):
+    def __call__(
+        self, force: bool = False, name: bool = True, ignore_ext_modules: bool = False
+    ) -> None:
         """Automatically discover missing configuration fields
         and modifies the given ``distribution`` object in-place.
 
@@ -456,7 +456,7 @@ def _analyse_flat_modules(self) -> bool:
         self._ensure_no_accidental_inclusion(self.dist.py_modules, "modules")
         return bool(self.dist.py_modules)
 
-    def _ensure_no_accidental_inclusion(self, detected: List[str], kind: str):
+    def _ensure_no_accidental_inclusion(self, detected: list[str], kind: str):
         if len(detected) > 1:
             from inspect import cleandoc
 
@@ -479,13 +479,13 @@ def _ensure_no_accidental_inclusion(self, detected: List[str], kind: str):
             """
             raise PackageDiscoveryError(cleandoc(msg))
 
-    def analyse_name(self):
+    def analyse_name(self) -> None:
         """The packages/modules are the essential contribution of the author.
         Therefore the name of the distribution can be derived from them.
         """
         if self.dist.metadata.name or self.dist.name:
             # get_name() is not reliable (can return "UNKNOWN")
-            return None
+            return
 
         log.debug("No `name` configuration, performing automatic discovery")
 
@@ -496,7 +496,7 @@ def analyse_name(self):
         if name:
             self.dist.metadata.name = name
 
-    def _find_name_single_package_or_module(self) -> Optional[str]:
+    def _find_name_single_package_or_module(self) -> str | None:
         """Exactly one module or package"""
         for field in ('packages', 'py_modules'):
             items = getattr(self.dist, field, None) or []
@@ -506,7 +506,7 @@ def _find_name_single_package_or_module(self) -> Optional[str]:
 
         return None
 
-    def _find_name_from_packages(self) -> Optional[str]:
+    def _find_name_from_packages(self) -> str | None:
         """Try to find the root package that is not a PEP 420 namespace"""
         if not self.dist.packages:
             return None
@@ -523,7 +523,7 @@ def _find_name_from_packages(self) -> Optional[str]:
         return None
 
 
-def remove_nested_packages(packages: List[str]) -> List[str]:
+def remove_nested_packages(packages: list[str]) -> list[str]:
     """Remove nested packages from a list of packages.
 
     >>> remove_nested_packages(["a", "a.b1", "a.b2", "a.b1.c1"])
@@ -541,7 +541,7 @@ def remove_nested_packages(packages: List[str]) -> List[str]:
     return top_level
 
 
-def remove_stubs(packages: List[str]) -> List[str]:
+def remove_stubs(packages: list[str]) -> list[str]:
     """Remove type stubs (:pep:`561`) from a list of packages.
 
     >>> remove_stubs(["a", "a.b", "a-stubs", "a-stubs.b.c", "b", "c-stubs"])
@@ -551,8 +551,8 @@ def remove_stubs(packages: List[str]) -> List[str]:
 
 
 def find_parent_package(
-    packages: List[str], package_dir: Mapping[str, str], root_dir: _Path
-) -> Optional[str]:
+    packages: list[str], package_dir: Mapping[str, str], root_dir: StrPath
+) -> str | None:
     """Find the parent package that is not a namespace."""
     packages = sorted(packages, key=len)
     common_ancestors = []
@@ -575,7 +575,7 @@ def find_parent_package(
 
 
 def find_package_path(
-    name: str, package_dir: Mapping[str, str], root_dir: _Path
+    name: str, package_dir: Mapping[str, str], root_dir: StrPath
 ) -> str:
     """Given a package name, return the path where it should be found on
     disk, considering the ``package_dir`` option.
@@ -608,7 +608,7 @@ def find_package_path(
     return os.path.join(root_dir, *parent.split("/"), *parts)
 
 
-def construct_package_dir(packages: List[str], package_path: _Path) -> Dict[str, str]:
+def construct_package_dir(packages: list[str], package_path: StrPath) -> dict[str, str]:
     parent_pkgs = remove_nested_packages(packages)
     prefix = Path(package_path).parts
     return {pkg: "/".join([*prefix, *pkg.split(".")]) for pkg in parent_pkgs}
diff --git a/setuptools/dist.py b/setuptools/dist.py
index f1d361f1c3..e600404198 100644
--- a/setuptools/dist.py
+++ b/setuptools/dist.py
@@ -1,16 +1,37 @@
-__all__ = ['Distribution']
-
+from __future__ import annotations
 
+import functools
 import io
 import itertools
 import numbers
 import os
 import re
 import sys
-from contextlib import suppress
-from glob import iglob
+from collections.abc import Iterable, Iterator, MutableMapping, Sequence
+from glob import glob
 from pathlib import Path
-from typing import List, Optional, Set
+from typing import TYPE_CHECKING, Any
+
+from more_itertools import partition, unique_everseen
+from packaging.markers import InvalidMarker, Marker
+from packaging.specifiers import InvalidSpecifier, SpecifierSet
+from packaging.version import Version
+
+from . import (
+    _entry_points,
+    _reqs,
+    _static,
+    command as _,  # noqa: F401 # imported for side-effects
+)
+from ._importlib import metadata
+from ._normalization import _canonicalize_license_expression
+from ._path import StrPath
+from ._reqs import _StrOrIter
+from .config import pyprojecttoml, setupcfg
+from .discovery import ConfigDiscovery
+from .errors import InvalidConfigError
+from .monkey import get_unpatched
+from .warnings import InformationOnly, SetuptoolsDeprecationWarning
 
 import distutils.cmd
 import distutils.command
@@ -22,24 +43,42 @@
 from distutils.fancy_getopt import translate_longopt
 from distutils.util import strtobool
 
-from .extern.more_itertools import partition, unique_everseen
-from .extern.ordered_set import OrderedSet
-from .extern.packaging.markers import InvalidMarker, Marker
-from .extern.packaging.specifiers import InvalidSpecifier, SpecifierSet
-from .extern.packaging.version import InvalidVersion, Version
+if TYPE_CHECKING:
+    from typing import TypeAlias
 
-from . import _entry_points
-from . import _normalization
-from . import _reqs
-from . import command as _  # noqa  -- imported for side-effects
-from ._importlib import metadata
-from .config import setupcfg, pyprojecttoml
-from .discovery import ConfigDiscovery
-from .monkey import get_unpatched
-from .warnings import InformationOnly, SetuptoolsDeprecationWarning
 
+__all__ = ['Distribution']
 
-sequence = tuple, list
+_sequence = tuple, list
+"""
+:meta private:
+
+Supported iterable types that are known to be:
+- ordered (which `set` isn't)
+- not match a str (which `Sequence[str]` does)
+- not imply a nested type (like `dict`)
+for use with `isinstance`.
+"""
+_Sequence: TypeAlias = tuple[str, ...] | list[str]
+# This is how stringifying _Sequence would look in Python 3.10
+_sequence_type_repr = "tuple[str, ...] | list[str]"
+_OrderedStrSequence: TypeAlias = str | dict[str, Any] | Sequence[str]
+"""
+:meta private:
+Avoid single-use iterable. Disallow sets.
+A poor approximation of an OrderedSequence (dict doesn't match a Sequence).
+"""
+
+
+def __getattr__(name: str) -> Any:  # pragma: no cover
+    if name == "sequence":
+        SetuptoolsDeprecationWarning.emit(
+            "`setuptools.dist.sequence` is an internal implementation detail.",
+            "Please define your own `sequence = tuple, list` instead.",
+            due_date=(2025, 8, 28),  # Originally added on 2024-08-27
+        )
+        return _sequence
+    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
 
 
 def check_importable(dist, attr, value):
@@ -48,21 +87,21 @@ def check_importable(dist, attr, value):
         assert not ep.extras
     except (TypeError, ValueError, AttributeError, AssertionError) as e:
         raise DistutilsSetupError(
-            "%r must be importable 'module:attrs' string (got %r)" % (attr, value)
+            f"{attr!r} must be importable 'module:attrs' string (got {value!r})"
         ) from e
 
 
-def assert_string_list(dist, attr, value):
+def assert_string_list(dist, attr: str, value: _Sequence) -> None:
     """Verify that value is a string list"""
     try:
         # verify that value is a list or tuple to exclude unordered
         # or single-use iterables
-        assert isinstance(value, (list, tuple))
+        assert isinstance(value, _sequence)
         # verify that elements of value are strings
         assert ''.join(value) != value
     except (TypeError, ValueError, AttributeError, AssertionError) as e:
         raise DistutilsSetupError(
-            "%r must be a list of strings (got %r)" % (attr, value)
+            f"{attr!r} must be of type <{_sequence_type_repr}> (got {value!r})"
         ) from e
 
 
@@ -73,10 +112,9 @@ def check_nsp(dist, attr, value):
     for nsp in ns_packages:
         if not dist.has_contents_for(nsp):
             raise DistutilsSetupError(
-                "Distribution contains no modules or packages for "
-                + "namespace package %r" % nsp
+                f"Distribution contains no modules or packages for namespace package {nsp!r}"
             )
-        parent, sep, child = nsp.rpartition('.')
+        parent, _sep, _child = nsp.rpartition('.')
         if parent and parent not in ns_packages:
             distutils.log.warn(
                 "WARNING: %r is declared as a package namespace, but %r"
@@ -87,7 +125,7 @@ def check_nsp(dist, attr, value):
         SetuptoolsDeprecationWarning.emit(
             "The namespace_packages parameter is deprecated.",
             "Please replace its usage with implicit namespaces (PEP 420).",
-            see_docs="references/keywords.html#keyword-namespace-packages"
+            see_docs="references/keywords.html#keyword-namespace-packages",
             # TODO: define due_date, it may break old packages that are no longer
             # maintained (e.g. sphinxcontrib extensions) when installed from source.
             # Warning officially introduced in May 2022, however the deprecation
@@ -108,7 +146,7 @@ def check_extras(dist, attr, value):
 
 
 def _check_extra(extra, reqs):
-    name, sep, marker = extra.partition(':')
+    _name, _sep, marker = extra.partition(':')
     try:
         _check_marker(marker)
     except InvalidMarker:
@@ -127,8 +165,7 @@ def _check_marker(marker):
 def assert_bool(dist, attr, value):
     """Verify that value is True, False, 0, or 1"""
     if bool(value) != value:
-        tmpl = "{attr!r} must be a boolean value (got {value!r})"
-        raise DistutilsSetupError(tmpl.format(attr=attr, value=value))
+        raise DistutilsSetupError(f"{attr!r} must be a boolean value (got {value!r})")
 
 
 def invalid_unless_false(dist, attr, value):
@@ -139,18 +176,18 @@ def invalid_unless_false(dist, attr, value):
     raise DistutilsSetupError(f"{attr} is invalid.")
 
 
-def check_requirements(dist, attr, value):
+def check_requirements(dist, attr: str, value: _OrderedStrSequence) -> None:
     """Verify that install_requires is a valid requirements list"""
     try:
         list(_reqs.parse(value))
-        if isinstance(value, (dict, set)):
+        if isinstance(value, set):
             raise TypeError("Unordered types are not allowed")
     except (TypeError, ValueError) as error:
-        tmpl = (
-            "{attr!r} must be a string or list of strings "
-            "containing valid project/version requirement specifiers; {error}"
+        msg = (
+            f"{attr!r} must be a string or iterable of strings "
+            f"containing valid project/version requirement specifiers; {error}"
         )
-        raise DistutilsSetupError(tmpl.format(attr=attr, error=error)) from error
+        raise DistutilsSetupError(msg) from error
 
 
 def check_specifier(dist, attr, value):
@@ -158,10 +195,8 @@ def check_specifier(dist, attr, value):
     try:
         SpecifierSet(value)
     except (InvalidSpecifier, AttributeError) as error:
-        tmpl = (
-            "{attr!r} must be a string " "containing valid version specifiers; {error}"
-        )
-        raise DistutilsSetupError(tmpl.format(attr=attr, error=error)) from error
+        msg = f"{attr!r} must be a string containing valid version specifiers; {error}"
+        raise DistutilsSetupError(msg) from error
 
 
 def check_entry_points(dist, attr, value):
@@ -172,24 +207,19 @@ def check_entry_points(dist, attr, value):
         raise DistutilsSetupError(e) from e
 
 
-def check_test_suite(dist, attr, value):
-    if not isinstance(value, str):
-        raise DistutilsSetupError("test_suite must be a string")
-
-
 def check_package_data(dist, attr, value):
     """Verify that value is a dictionary of package names to glob lists"""
     if not isinstance(value, dict):
         raise DistutilsSetupError(
-            "{!r} must be a dictionary mapping package names to lists of "
-            "string wildcard patterns".format(attr)
+            f"{attr!r} must be a dictionary mapping package names to lists of "
+            "string wildcard patterns"
         )
     for k, v in value.items():
         if not isinstance(k, str):
             raise DistutilsSetupError(
-                "keys of {!r} dict must be strings (got {!r})".format(attr, k)
+                f"keys of {attr!r} dict must be strings (got {k!r})"
             )
-        assert_string_list(dist, 'values of {!r} dict'.format(attr), v)
+        assert_string_list(dist, f'values of {attr!r} dict', v)
 
 
 def check_packages(dist, attr, value):
@@ -202,7 +232,11 @@ def check_packages(dist, attr, value):
             )
 
 
-_Distribution = get_unpatched(distutils.core.Distribution)
+if TYPE_CHECKING:
+    # Work around a mypy issue where type[T] can't be used as a base: https://github.com/python/mypy/issues/10962
+    from distutils.core import Distribution as _Distribution
+else:
+    _Distribution = get_unpatched(distutils.core.Distribution)
 
 
 class Distribution(_Distribution):
@@ -233,12 +267,6 @@ class Distribution(_Distribution):
         EasyInstall and requests one of your extras, the corresponding
         additional requirements will be installed if needed.
 
-     'test_suite' -- the name of a test suite to run for the 'test' command.
-        If the user runs 'python setup.py test', the package will be installed,
-        and the named test suite will be run.  The format is the same as
-        would be used on a 'unittest.py' command line.  That is, it is the
-        dotted name of an object to import and call to generate a test suite.
-
      'package_data' -- a dictionary mapping package names to lists of filenames
         or globs to use to find data files contained in the named packages.
         If the dictionary has filenames or globs listed under '""' (the empty
@@ -260,66 +288,48 @@ class Distribution(_Distribution):
     _DISTUTILS_UNSUPPORTED_METADATA = {
         'long_description_content_type': lambda: None,
         'project_urls': dict,
-        'provides_extras': OrderedSet,
+        'provides_extras': dict,  # behaves like an ordered set
+        'license_expression': lambda: None,
         'license_file': lambda: None,
         'license_files': lambda: None,
-        # Both install_requires and extras_require are needed to write PKG-INFO,
-        # So we take this opportunity to cache parsed requirement objects.
-        # These attributes are not part of the public API and intended for internal use.
-        '_normalized_install_requires': dict,  # Dict[str, Requirement]
-        '_normalized_extras_require': dict,  # Dict[str, Dict[str, Requirement]]
+        'install_requires': list,
+        'extras_require': dict,
     }
 
-    _patched_dist = None
+    # Used by build_py, editable_wheel and install_lib commands for legacy namespaces
+    namespace_packages: list[str]  #: :meta private: DEPRECATED
 
-    def patch_missing_pkg_info(self, attrs):
-        # Fake up a replacement for the data that would normally come from
-        # PKG-INFO, but which might not yet be built if this is a fresh
-        # checkout.
-        #
-        if not attrs or 'name' not in attrs or 'version' not in attrs:
-            return
-        name = _normalization.safe_name(str(attrs['name'])).lower()
-        with suppress(metadata.PackageNotFoundError):
-            dist = metadata.distribution(name)
-            if dist is not None and not dist.read_text('PKG-INFO'):
-                dist._version = _normalization.safe_version(str(attrs['version']))
-                self._patched_dist = dist
-
-    def __init__(self, attrs=None):
+    # Any: Dynamic assignment results in Incompatible types in assignment
+    def __init__(self, attrs: MutableMapping[str, Any] | None = None) -> None:
         have_package_data = hasattr(self, "package_data")
         if not have_package_data:
-            self.package_data = {}
+            self.package_data: dict[str, list[str]] = {}
         attrs = attrs or {}
-        self.dist_files = []
+        self.dist_files: list[tuple[str, str, str]] = []
+        self.include_package_data: bool | None = None
+        self.exclude_package_data: dict[str, list[str]] | None = None
         # Filter-out setuptools' specific options.
-        self.src_root = attrs.pop("src_root", None)
-        self.patch_missing_pkg_info(attrs)
-        self.dependency_links = attrs.pop('dependency_links', [])
-        self.setup_requires = attrs.pop('setup_requires', [])
+        self.src_root: str | None = attrs.pop("src_root", None)
+        self.dependency_links: list[str] = attrs.pop('dependency_links', [])
+        self.setup_requires: list[str] = attrs.pop('setup_requires', [])
         for ep in metadata.entry_points(group='distutils.setup_keywords'):
             vars(self).setdefault(ep.name, None)
-        _Distribution.__init__(
-            self,
-            {
-                k: v
-                for k, v in attrs.items()
-                if k not in self._DISTUTILS_UNSUPPORTED_METADATA
-            },
-        )
+
+        metadata_only = set(self._DISTUTILS_UNSUPPORTED_METADATA)
+        metadata_only -= {"install_requires", "extras_require"}
+        dist_attrs = {k: v for k, v in attrs.items() if k not in metadata_only}
+        _Distribution.__init__(self, dist_attrs)
 
         # Private API (setuptools-use only, not restricted to Distribution)
         # Stores files that are referenced by the configuration and need to be in the
         # sdist (e.g. `version = file: VERSION.txt`)
-        self._referenced_files: Set[str] = set()
+        self._referenced_files = set[str]()
 
         self.set_defaults = ConfigDiscovery(self)
 
         self._set_metadata_defaults(attrs)
 
-        self.metadata.version = self._normalize_version(
-            self._validate_version(self.metadata.version)
-        )
+        self.metadata.version = self._normalize_version(self.metadata.version)
         self._finalize_requires()
 
     def _validate_metadata(self):
@@ -349,7 +359,10 @@ def _set_metadata_defaults(self, attrs):
     def _normalize_version(version):
         from . import sic
 
-        if isinstance(version, sic) or version is None:
+        if isinstance(version, numbers.Number):
+            # Some people apparently take "version number" too literally :)
+            version = str(version)
+        elif isinstance(version, sic) or version is None:
             return version
 
         normalized = str(Version(version))
@@ -358,33 +371,6 @@ def _normalize_version(version):
             return normalized
         return version
 
-    @staticmethod
-    def _validate_version(version):
-        if isinstance(version, numbers.Number):
-            # Some people apparently take "version number" too literally :)
-            version = str(version)
-
-        if version is not None:
-            try:
-                Version(version)
-            except (InvalidVersion, TypeError):
-                from . import sic
-
-                SetuptoolsDeprecationWarning.emit(
-                    f"Invalid version: {version!r}.",
-                    """
-                    The version specified is not a valid version according to PEP 440.
-                    This may not work as expected with newer versions of
-                    setuptools, pip, and PyPI.
-                    """,
-                    see_url="https://peps.python.org/pep-0440/",
-                    due_date=(2023, 9, 26),
-                    # Warning initially introduced in 26 Sept 2014
-                    # pypa/packaging already removed legacy versions.
-                )
-                return sic(version)
-        return version
-
     def _finalize_requires(self):
         """
         Set `metadata.python_requires` and fix environment markers
@@ -394,37 +380,76 @@ def _finalize_requires(self):
             self.metadata.python_requires = self.python_requires
 
         self._normalize_requires()
+        self.metadata.install_requires = self.install_requires
+        self.metadata.extras_require = self.extras_require
 
         if self.extras_require:
             for extra in self.extras_require.keys():
                 # Setuptools allows a weird ": syntax for extras
                 extra = extra.split(':')[0]
                 if extra:
-                    self.metadata.provides_extras.add(extra)
+                    self.metadata.provides_extras.setdefault(extra)
 
     def _normalize_requires(self):
         """Make sure requirement-related attributes exist and are normalized"""
         install_requires = getattr(self, "install_requires", None) or []
         extras_require = getattr(self, "extras_require", None) or {}
-        meta = self.metadata
-        meta._normalized_install_requires = {
-            str(r): r for r in _reqs.parse(install_requires)
-        }
-        meta._normalized_extras_require = {
-            k: {str(r): r for r in _reqs.parse(v or [])}
-            for k, v in extras_require.items()
-        }
-        self.install_requires = list(meta._normalized_install_requires)
-        self.extras_require = {
-            k: list(v) for k, v in meta._normalized_extras_require.items()
-        }
 
-    def _finalize_license_files(self):
+        # Preserve the "static"-ness of values parsed from config files
+        list_ = _static.List if _static.is_static(install_requires) else list
+        self.install_requires = list_(map(str, _reqs.parse(install_requires)))
+
+        dict_ = _static.Dict if _static.is_static(extras_require) else dict
+        self.extras_require = dict_(
+            (k, list(map(str, _reqs.parse(v or [])))) for k, v in extras_require.items()
+        )
+
+    def _finalize_license_expression(self) -> None:
+        """
+        Normalize license and license_expression.
+        >>> dist = Distribution({"license_expression": _static.Str("mit aNd  gpl-3.0-OR-later")})
+        >>> _static.is_static(dist.metadata.license_expression)
+        True
+        >>> dist._finalize_license_expression()
+        >>> _static.is_static(dist.metadata.license_expression)  # preserve "static-ness"
+        True
+        >>> print(dist.metadata.license_expression)
+        MIT AND GPL-3.0-or-later
+        """
+        classifiers = self.metadata.get_classifiers()
+        license_classifiers = [cl for cl in classifiers if cl.startswith("License :: ")]
+
+        license_expr = self.metadata.license_expression
+        if license_expr:
+            str_ = _static.Str if _static.is_static(license_expr) else str
+            normalized = str_(_canonicalize_license_expression(license_expr))
+            if license_expr != normalized:
+                InformationOnly.emit(f"Normalizing '{license_expr}' to '{normalized}'")
+                self.metadata.license_expression = normalized
+            if license_classifiers:
+                raise InvalidConfigError(
+                    "License classifiers have been superseded by license expressions "
+                    "(see https://peps.python.org/pep-0639/). Please remove:\n\n"
+                    + "\n".join(license_classifiers),
+                )
+        elif license_classifiers:
+            pypa_guides = "guides/writing-pyproject-toml/#license"
+            SetuptoolsDeprecationWarning.emit(
+                "License classifiers are deprecated.",
+                "Please consider removing the following classifiers in favor of a "
+                "SPDX license expression:\n\n" + "\n".join(license_classifiers),
+                see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
+                # Warning introduced on 2025-02-17
+                # TODO: Should we add a due date? It may affect old/unmaintained
+                #       packages in the ecosystem and cause problems...
+            )
+
+    def _finalize_license_files(self) -> None:
         """Compute names of all license files which should be included."""
-        license_files: Optional[List[str]] = self.metadata.license_files
-        patterns: List[str] = license_files if license_files else []
+        license_files: list[str] | None = self.metadata.license_files
+        patterns = license_files or []
 
-        license_file: Optional[str] = self.metadata.license_file
+        license_file: str | None = self.metadata.license_file
         if license_file and license_file not in patterns:
             patterns.append(license_file)
 
@@ -432,27 +457,91 @@ def _finalize_license_files(self):
             # Default patterns match the ones wheel uses
             # See https://wheel.readthedocs.io/en/stable/user_guide.html
             # -> 'Including license files in the generated wheel file'
-            patterns = ('LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*')
+            patterns = ['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']
+            files = self._expand_patterns(patterns, enforce_match=False)
+        else:  # Patterns explicitly given by the user
+            files = self._expand_patterns(patterns, enforce_match=True)
 
-        self.metadata.license_files = list(
-            unique_everseen(self._expand_patterns(patterns))
-        )
+        self.metadata.license_files = list(unique_everseen(files))
 
-    @staticmethod
-    def _expand_patterns(patterns):
+    @classmethod
+    def _expand_patterns(
+        cls, patterns: list[str], enforce_match: bool = True
+    ) -> Iterator[str]:
         """
-        >>> list(Distribution._expand_patterns(['LICENSE']))
-        ['LICENSE']
-        >>> list(Distribution._expand_patterns(['setup.cfg', 'LIC*']))
-        ['setup.cfg', 'LICENSE']
+        >>> getfixture('sample_project_cwd')
+        >>> list(Distribution._expand_patterns(['LICENSE.txt']))
+        ['LICENSE.txt']
+        >>> list(Distribution._expand_patterns(['pyproject.toml', 'LIC*']))
+        ['pyproject.toml', 'LICENSE.txt']
+        >>> list(Distribution._expand_patterns(['src/**/*.dat']))
+        ['src/sample/package_data.dat']
         """
         return (
-            path
+            path.replace(os.sep, "/")
             for pattern in patterns
-            for path in sorted(iglob(pattern))
+            for path in sorted(cls._find_pattern(pattern, enforce_match))
             if not path.endswith('~') and os.path.isfile(path)
         )
 
+    @staticmethod
+    def _find_pattern(pattern: str, enforce_match: bool = True) -> list[str]:
+        r"""
+        >>> getfixture('sample_project_cwd')
+        >>> Distribution._find_pattern("LICENSE.txt")
+        ['LICENSE.txt']
+        >>> Distribution._find_pattern("/LICENSE.MIT")
+        Traceback (most recent call last):
+        ...
+        setuptools.errors.InvalidConfigError: Pattern '/LICENSE.MIT' should be relative...
+        >>> Distribution._find_pattern("../LICENSE.MIT")
+        Traceback (most recent call last):
+        ...
+        setuptools.warnings.SetuptoolsDeprecationWarning: ...Pattern '../LICENSE.MIT' cannot contain '..'...
+        >>> Distribution._find_pattern("LICEN{CSE*")
+        Traceback (most recent call last):
+        ...
+        setuptools.warnings.SetuptoolsDeprecationWarning: ...Pattern 'LICEN{CSE*' contains invalid characters...
+        """
+        pypa_guides = "specifications/glob-patterns/"
+        if ".." in pattern:
+            SetuptoolsDeprecationWarning.emit(
+                f"Pattern {pattern!r} cannot contain '..'",
+                """
+                Please ensure the files specified are contained by the root
+                of the Python package (normally marked by `pyproject.toml`).
+                """,
+                see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
+                due_date=(2027, 2, 18),  # Introduced in 2025-03-20
+                # Replace with InvalidConfigError after deprecation
+            )
+        if pattern.startswith((os.sep, "/")) or ":\\" in pattern:
+            raise InvalidConfigError(
+                f"Pattern {pattern!r} should be relative and must not start with '/'"
+            )
+        if re.match(r'^[\w\-\.\/\*\?\[\]]+$', pattern) is None:
+            SetuptoolsDeprecationWarning.emit(
+                "Please provide a valid glob pattern.",
+                "Pattern {pattern!r} contains invalid characters.",
+                pattern=pattern,
+                see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
+                due_date=(2027, 2, 18),  # Introduced in 2025-02-20
+            )
+
+        found = glob(pattern, recursive=True)
+
+        if enforce_match and not found:
+            SetuptoolsDeprecationWarning.emit(
+                "Cannot find any files for the given pattern.",
+                "Pattern {pattern!r} did not match any files.",
+                pattern=pattern,
+                due_date=(2027, 2, 18),  # Introduced in 2025-02-20
+                # PEP 639 requires us to error, but as a transition period
+                # we will only issue a warning to give people time to prepare.
+                # After the transition, this should raise an InvalidConfigError.
+            )
+        return found
+
     # FIXME: 'Distribution._parse_config_files' is too complex (14)
     def _parse_config_files(self, filenames=None):  # noqa: C901
         """
@@ -494,7 +583,7 @@ def _parse_config_files(self, filenames=None):  # noqa: C901
         parser = ConfigParser()
         parser.optionxform = str
         for filename in filenames:
-            with io.open(filename, encoding='utf-8') as reader:
+            with open(filename, encoding='utf-8') as reader:
                 if DEBUG:
                     self.announce("  reading {filename}".format(**locals()))
                 parser.read_file(reader)
@@ -507,8 +596,8 @@ def _parse_config_files(self, filenames=None):  # noqa: C901
                         continue
 
                     val = parser.get(section, opt)
-                    opt = self.warn_dash_deprecation(opt, section)
-                    opt = self.make_option_lowercase(opt, section)
+                    opt = self._enforce_underscore(opt, section)
+                    opt = self._enforce_option_lowercase(opt, section)
                     opt_dict[opt] = (filename, val)
 
             # Make the ConfigParser forget everything (so we retain
@@ -525,7 +614,7 @@ def _parse_config_files(self, filenames=None):  # noqa: C901
             alias = self.negative_opt.get(opt)
             if alias:
                 val = not strtobool(val)
-            elif opt in ('verbose', 'dry_run'):  # ugh!
+            elif opt == 'verbose':
                 val = strtobool(val)
 
             try:
@@ -533,64 +622,69 @@ def _parse_config_files(self, filenames=None):  # noqa: C901
             except ValueError as e:
                 raise DistutilsOptionError(e) from e
 
-    def warn_dash_deprecation(self, opt, section):
-        if section in (
-            'options.extras_require',
-            'options.data_files',
-        ):
+    def _enforce_underscore(self, opt: str, section: str) -> str:
+        if "-" not in opt or self._skip_setupcfg_normalization(section):
             return opt
 
         underscore_opt = opt.replace('-', '_')
-        commands = list(
-            itertools.chain(
-                distutils.command.__all__,
-                self._setuptools_commands(),
-            )
+        affected = f"(Affected: {self.metadata.name})." if self.metadata.name else ""
+        SetuptoolsDeprecationWarning.emit(
+            f"Invalid dash-separated key {opt!r} in {section!r} (setup.cfg), "
+            f"please use the underscore name {underscore_opt!r} instead.",
+            f"""
+            Usage of dash-separated {opt!r} will not be supported in future
+            versions. Please use the underscore name {underscore_opt!r} instead.
+            {affected}
+
+            Available configuration options are listed in:
+            https://setuptools.pypa.io/en/latest/userguide/declarative_config.html
+            """,
+            see_url="https://github.com/pypa/setuptools/discussions/5011",
+            due_date=(2026, 3, 3),
+            # Warning initially introduced in 3 Mar 2021
         )
-        if (
-            not section.startswith('options')
-            and section != 'metadata'
-            and section not in commands
-        ):
-            return underscore_opt
-
-        if '-' in opt:
-            SetuptoolsDeprecationWarning.emit(
-                "Invalid dash-separated options",
-                f"""
-                Usage of dash-separated {opt!r} will not be supported in future
-                versions. Please use the underscore name {underscore_opt!r} instead.
-                """,
-                see_docs="userguide/declarative_config.html",
-                due_date=(2023, 9, 26),
-                # Warning initially introduced in 3 Mar 2021
-            )
         return underscore_opt
 
-    def _setuptools_commands(self):
-        try:
-            return metadata.distribution('setuptools').entry_points.names
-        except metadata.PackageNotFoundError:
-            # during bootstrapping, distribution doesn't exist
-            return []
-
-    def make_option_lowercase(self, opt, section):
-        if section != 'metadata' or opt.islower():
+    def _enforce_option_lowercase(self, opt: str, section: str) -> str:
+        if opt.islower() or self._skip_setupcfg_normalization(section):
             return opt
 
         lowercase_opt = opt.lower()
+        affected = f"(Affected: {self.metadata.name})." if self.metadata.name else ""
         SetuptoolsDeprecationWarning.emit(
-            "Invalid uppercase configuration",
+            f"Invalid uppercase key {opt!r} in {section!r} (setup.cfg), "
+            f"please use lowercase {lowercase_opt!r} instead.",
             f"""
             Usage of uppercase key {opt!r} in {section!r} will not be supported in
             future versions. Please use lowercase {lowercase_opt!r} instead.
+            {affected}
+
+            Available configuration options are listed in:
+            https://setuptools.pypa.io/en/latest/userguide/declarative_config.html
             """,
-            see_docs="userguide/declarative_config.html",
-            due_date=(2023, 9, 26),
+            see_url="https://github.com/pypa/setuptools/discussions/5011",
+            due_date=(2026, 3, 3),
             # Warning initially introduced in 6 Mar 2021
         )
         return lowercase_opt
 
+    def _skip_setupcfg_normalization(self, section: str) -> bool:
+        skip = (
+            'options.extras_require',
+            'options.data_files',
+            'options.entry_points',
+            'options.package_data',
+            'options.exclude_package_data',
+        )
+        return section in skip or not self._is_setuptools_section(section)
+
+    def _is_setuptools_section(self, section: str) -> bool:
+        return (
+            section == "metadata"
+            or section.startswith("options")
+            or section in _setuptools_commands()
+        )
+
     # FIXME: 'Distribution._set_command_options' is too complex (14)
     def _set_command_options(self, command_obj, option_dict=None):  # noqa: C901
         """
@@ -609,10 +703,10 @@ def _set_command_options(self, command_obj, option_dict=None):  # noqa: C901
             option_dict = self.get_option_dict(command_name)
 
         if DEBUG:
-            self.announce("  setting options for '%s' command:" % command_name)
+            self.announce(f"  setting options for '{command_name}' command:")
         for option, (source, value) in option_dict.items():
             if DEBUG:
-                self.announce("    %s = %s (from %s)" % (option, value, source))
+                self.announce(f"    {option} = {value} (from {source})")
             try:
                 bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]
             except AttributeError:
@@ -632,13 +726,12 @@ def _set_command_options(self, command_obj, option_dict=None):  # noqa: C901
                     setattr(command_obj, option, value)
                 else:
                     raise DistutilsOptionError(
-                        "error in %s: command '%s' has no such option '%s'"
-                        % (source, command_name, option)
+                        f"error in {source}: command '{command_name}' has no such option '{option}'"
                     )
             except ValueError as e:
                 raise DistutilsOptionError(e) from e
 
-    def _get_project_config_files(self, filenames):
+    def _get_project_config_files(self, filenames: Iterable[StrPath] | None):
         """Add default file and split between INI and TOML"""
         tomlfiles = []
         standard_project_metadata = Path(self.src_root or os.curdir, "pyproject.toml")
@@ -650,7 +743,11 @@ def _get_project_config_files(self, filenames):
             tomlfiles = [standard_project_metadata]
         return filenames, tomlfiles
 
-    def parse_config_files(self, filenames=None, ignore_option_errors=False):
+    def parse_config_files(
+        self,
+        filenames: Iterable[StrPath] | None = None,
+        ignore_option_errors: bool = False,
+    ) -> None:
         """Parses configuration files from various levels
         and loads configuration.
         """
@@ -665,15 +762,16 @@ def parse_config_files(self, filenames=None, ignore_option_errors=False):
             pyprojecttoml.apply_configuration(self, filename, ignore_option_errors)
 
         self._finalize_requires()
+        self._finalize_license_expression()
         self._finalize_license_files()
 
-    def fetch_build_eggs(self, requires):
+    def fetch_build_eggs(self, requires: _StrOrIter) -> list[metadata.Distribution]:
         """Resolve pre-setup requirements"""
         from .installer import _fetch_build_eggs
 
         return _fetch_build_eggs(self, requires)
 
-    def finalize_options(self):
+    def finalize_options(self) -> None:
         """
         Allow plugins to apply arbitrary operations to the
         distribution. Each hook may optionally define a 'order'
@@ -711,7 +809,7 @@ def _finalize_setup_keywords(self):
             if value is not None:
                 ep.load()(self, ep.name, value)
 
-    def get_egg_cache_dir(self):
+    def get_egg_cache_dir(self) -> str:
         from . import windows_support
 
         egg_cache_dir = os.path.join(os.curdir, '.eggs')
@@ -719,7 +817,7 @@ def get_egg_cache_dir(self):
             os.mkdir(egg_cache_dir)
             windows_support.hide_file(egg_cache_dir)
             readme_txt_filename = os.path.join(egg_cache_dir, 'README.txt')
-            with open(readme_txt_filename, 'w') as f:
+            with open(readme_txt_filename, 'w', encoding="utf-8") as f:
                 f.write(
                     'This directory contains eggs that were downloaded '
                     'by setuptools to build, test, and run plug-ins.\n\n'
@@ -738,11 +836,17 @@ def fetch_build_egg(self, req):
 
         return fetch_build_egg(self, req)
 
-    def get_command_class(self, command):
+    def get_command_class(self, command: str) -> type[distutils.cmd.Command]:  # type: ignore[override] # Not doing complex overrides yet
         """Pluggable version of get_command_class()"""
         if command in self.cmdclass:
             return self.cmdclass[command]
 
+        # Special case bdist_wheel so it's never loaded from "wheel"
+        if command == 'bdist_wheel':
+            from .command.bdist_wheel import bdist_wheel
+
+            return bdist_wheel
+
         eps = metadata.entry_points(group='distutils.commands', name=command)
         for ep in eps:
             self.cmdclass[command] = cmdclass = ep.load()
@@ -764,7 +868,7 @@ def get_command_list(self):
                 self.cmdclass[ep.name] = cmdclass
         return _Distribution.get_command_list(self)
 
-    def include(self, **attrs):
+    def include(self, **attrs) -> None:
         """Add items to distribution that are named in keyword arguments
 
         For example, 'dist.include(py_modules=["x"])' would add 'x' to
@@ -786,7 +890,7 @@ def include(self, **attrs):
             else:
                 self._include_misc(k, v)
 
-    def exclude_package(self, package):
+    def exclude_package(self, package: str) -> None:
         """Remove packages, modules, and extensions in named package"""
 
         pfx = package + '.'
@@ -807,7 +911,7 @@ def exclude_package(self, package):
                 if p.name != package and not p.name.startswith(pfx)
             ]
 
-    def has_contents_for(self, package):
+    def has_contents_for(self, package: str) -> bool:
         """Return true if 'exclude_package(package)' would do something"""
 
         pfx = package + '.'
@@ -816,43 +920,47 @@ def has_contents_for(self, package):
             if p == package or p.startswith(pfx):
                 return True
 
-    def _exclude_misc(self, name, value):
+        return False
+
+    def _exclude_misc(self, name: str, value: _Sequence) -> None:
         """Handle 'exclude()' for list/tuple attrs without a special handler"""
-        if not isinstance(value, sequence):
+        if not isinstance(value, _sequence):
             raise DistutilsSetupError(
-                "%s: setting must be a list or tuple (%r)" % (name, value)
+                f"{name}: setting must be of type <{_sequence_type_repr}> (got {value!r})"
             )
         try:
             old = getattr(self, name)
         except AttributeError as e:
-            raise DistutilsSetupError("%s: No such distribution setting" % name) from e
-        if old is not None and not isinstance(old, sequence):
+            raise DistutilsSetupError(f"{name}: No such distribution setting") from e
+        if old is not None and not isinstance(old, _sequence):
             raise DistutilsSetupError(
                 name + ": this setting cannot be changed via include/exclude"
             )
         elif old:
             setattr(self, name, [item for item in old if item not in value])
 
-    def _include_misc(self, name, value):
+    def _include_misc(self, name: str, value: _Sequence) -> None:
         """Handle 'include()' for list/tuple attrs without a special handler"""
 
-        if not isinstance(value, sequence):
-            raise DistutilsSetupError("%s: setting must be a list (%r)" % (name, value))
+        if not isinstance(value, _sequence):
+            raise DistutilsSetupError(
+                f"{name}: setting must be of type <{_sequence_type_repr}> (got {value!r})"
+            )
         try:
             old = getattr(self, name)
         except AttributeError as e:
-            raise DistutilsSetupError("%s: No such distribution setting" % name) from e
+            raise DistutilsSetupError(f"{name}: No such distribution setting") from e
         if old is None:
             setattr(self, name, value)
-        elif not isinstance(old, sequence):
+        elif not isinstance(old, _sequence):
             raise DistutilsSetupError(
                 name + ": this setting cannot be changed via include/exclude"
             )
         else:
             new = [item for item in value if item not in old]
-            setattr(self, name, old + new)
+            setattr(self, name, list(old) + new)
 
-    def exclude(self, **attrs):
+    def exclude(self, **attrs) -> None:
         """Remove items from distribution that are named in keyword arguments
 
         For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
@@ -875,10 +983,10 @@ def exclude(self, **attrs):
             else:
                 self._exclude_misc(k, v)
 
-    def _exclude_packages(self, packages):
-        if not isinstance(packages, sequence):
+    def _exclude_packages(self, packages: _Sequence) -> None:
+        if not isinstance(packages, _sequence):
             raise DistutilsSetupError(
-                "packages: setting must be a list or tuple (%r)" % (packages,)
+                f"packages: setting must be of type <{_sequence_type_repr}> (got {packages!r})"
             )
         list(map(self.exclude_package, packages))
 
@@ -891,7 +999,7 @@ def _parse_command_opts(self, parser, args):
         command = args[0]
         aliases = self.get_option_dict('aliases')
         while command in aliases:
-            src, alias = aliases[command]
+            _src, alias = aliases[command]
             del aliases[command]  # ensure each alias can expand only once!
             import shlex
 
@@ -909,7 +1017,7 @@ def _parse_command_opts(self, parser, args):
 
         return nargs
 
-    def get_cmdline_options(self):
+    def get_cmdline_options(self) -> dict[str, dict[str, str | None]]:
         """Return a '{cmd: {opt:val}}' map of all command-line options
 
         Option names are all long, but do not include the leading '--', and
@@ -919,9 +1027,10 @@ def get_cmdline_options(self):
         Note that options provided by config files are intentionally excluded.
         """
 
-        d = {}
+        d: dict[str, dict[str, str | None]] = {}
 
         for cmd, opts in self.command_options.items():
+            val: str | None
             for opt, (src, val) in opts.items():
                 if src != "command line":
                     continue
@@ -947,22 +1056,19 @@ def get_cmdline_options(self):
 
         return d
 
-    def iter_distribution_names(self):
+    def iter_distribution_names(self) -> Iterator[str]:
         """Yield all packages, modules, and extension names in distribution"""
 
-        for pkg in self.packages or ():
-            yield pkg
+        yield from self.packages or ()
 
-        for module in self.py_modules or ():
-            yield module
+        yield from self.py_modules or ()
 
         for ext in self.ext_modules or ():
             if isinstance(ext, tuple):
-                name, buildinfo = ext
+                name, _buildinfo = ext
             else:
                 name = ext.name
-            if name.endswith('module'):
-                name = name[:-6]
+            name = name.removesuffix('module')
             yield name
 
     def handle_display_options(self, option_order):
@@ -993,7 +1099,7 @@ def handle_display_options(self, option_order):
         finally:
             sys.stdout.reconfigure(encoding=encoding)
 
-    def run_command(self, command):
+    def run_command(self, command) -> None:
         self.set_defaults()
         # Postpone defaults until all explicit configuration is considered
         # (setup() args, config files, command line and plugins)
@@ -1001,6 +1107,18 @@ def run_command(self, command):
         super().run_command(command)
 
 
+@functools.cache
+def _setuptools_commands() -> set[str]:
+    try:
+        # Use older API for importlib.metadata compatibility
+        entry_points = metadata.distribution('setuptools').entry_points
+        eps: Iterable[str] = (ep.name for ep in entry_points)
+    except metadata.PackageNotFoundError:
+        # during bootstrapping, distribution doesn't exist
+        eps = []
+    return {*distutils.command.__all__, *eps}
+
+
 class DistDeprecationWarning(SetuptoolsDeprecationWarning):
     """Class for warning about deprecations in dist in
     setuptools. Not ignored by default, unlike DeprecationWarning."""
diff --git a/setuptools/errors.py b/setuptools/errors.py
index ec7fb3b6c4..990ecbf4e2 100644
--- a/setuptools/errors.py
+++ b/setuptools/errors.py
@@ -3,8 +3,9 @@
 Provides exceptions used by setuptools modules.
 """
 
-from distutils import errors as _distutils_errors
+from __future__ import annotations
 
+from distutils import errors as _distutils_errors
 
 # Re-export errors from distutils to facilitate the migration to PEP632
 
@@ -29,7 +30,15 @@
 BaseError = _distutils_errors.DistutilsError
 
 
-class RemovedCommandError(BaseError, RuntimeError):
+class InvalidConfigError(OptionError):  # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+
+    """Error used for invalid configurations."""
+
+
+class RemovedConfigError(OptionError):  # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+
+    """Error used for configurations that were deprecated and removed."""
+
+
+class RemovedCommandError(BaseError, RuntimeError):  # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+
     """Error used for commands that have been removed in setuptools.
 
     Since ``setuptools`` is built on ``distutils``, simply removing a command
@@ -39,7 +48,7 @@ class RemovedCommandError(BaseError, RuntimeError):
     """
 
 
-class PackageDiscoveryError(BaseError, RuntimeError):
+class PackageDiscoveryError(BaseError, RuntimeError):  # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+
     """Impossible to perform automatic discovery of packages and/or modules.
 
     The current project layout or given discovery options can lead to problems when
diff --git a/setuptools/extension.py b/setuptools/extension.py
index 58c023f6b4..3e63cbe12a 100644
--- a/setuptools/extension.py
+++ b/setuptools/extension.py
@@ -1,13 +1,20 @@
-import re
+from __future__ import annotations
+
 import functools
+import re
+from collections.abc import Iterable
+from typing import TYPE_CHECKING
+
+from setuptools._path import StrPath
+
+from .monkey import get_unpatched
+
 import distutils.core
 import distutils.errors
 import distutils.extension
 
-from .monkey import get_unpatched
 
-
-def _have_cython():
+def _have_cython() -> bool:
     """
     Return True if Cython can be imported.
     """
@@ -15,16 +22,18 @@ def _have_cython():
     try:
         # from (cython_impl) import build_ext
         __import__(cython_impl, fromlist=['build_ext']).build_ext
-        return True
     except Exception:
-        pass
-    return False
+        return False
+    return True
 
 
 # for compatibility
 have_pyrex = _have_cython
-
-_Extension = get_unpatched(distutils.core.Extension)
+if TYPE_CHECKING:
+    # Work around a mypy issue where type[T] can't be used as a base: https://github.com/python/mypy/issues/10962
+    from distutils.core import Extension as _Extension
+else:
+    _Extension = get_unpatched(distutils.core.Extension)
 
 
 class Extension(_Extension):
@@ -44,8 +53,9 @@ class Extension(_Extension):
       the full name of the extension, including any packages -- ie.
       *not* a filename or pathname, but Python dotted name
 
-    :arg list[str] sources:
-      list of source filenames, relative to the distribution root
+    :arg Iterable[str | os.PathLike[str]] sources:
+      iterable of source filenames, (except strings, which could be misinterpreted
+      as a single filename), relative to the distribution root
       (where the setup script lives), in Unix form (slash-separated)
       for portability.  Source files may be C, C++, SWIG (.i),
       platform-specific resource files, or whatever else is recognized
@@ -119,15 +129,36 @@ class Extension(_Extension):
     :keyword bool py_limited_api:
       opt-in flag for the usage of :doc:`Python's limited API `.
 
-    :raises setuptools.errors.PlatformError: if 'runtime_library_dirs' is
+    :raises setuptools.errors.PlatformError: if ``runtime_library_dirs`` is
       specified on Windows. (since v63)
     """
 
-    def __init__(self, name, sources, *args, **kw):
+    # These 4 are set and used in setuptools/command/build_ext.py
+    # The lack of a default value and risk of `AttributeError` is purposeful
+    # to avoid people forgetting to call finalize_options if they modify the extension list.
+    # See example/rationale in https://github.com/pypa/setuptools/issues/4529.
+    _full_name: str  #: Private API, internal use only.
+    _links_to_dynamic: bool  #: Private API, internal use only.
+    _needs_stub: bool  #: Private API, internal use only.
+    _file_name: str  #: Private API, internal use only.
+
+    def __init__(
+        self,
+        name: str,
+        sources: Iterable[StrPath],
+        *args,
+        py_limited_api: bool = False,
+        **kw,
+    ) -> None:
         # The *args is needed for compatibility as calls may use positional
         # arguments. py_limited_api may be set only via keyword.
-        self.py_limited_api = kw.pop("py_limited_api", False)
-        super().__init__(name, sources, *args, **kw)
+        self.py_limited_api = py_limited_api
+        super().__init__(
+            name,
+            sources,  # type: ignore[arg-type] # Vendored version of setuptools supports PathLike
+            *args,
+            **kw,
+        )
 
     def _convert_pyx_sources_to_lang(self):
         """
diff --git a/setuptools/extern/__init__.py b/setuptools/extern/__init__.py
deleted file mode 100644
index 67c4a4552f..0000000000
--- a/setuptools/extern/__init__.py
+++ /dev/null
@@ -1,84 +0,0 @@
-import importlib.util
-import sys
-
-
-class VendorImporter:
-    """
-    A PEP 302 meta path importer for finding optionally-vendored
-    or otherwise naturally-installed packages from root_name.
-    """
-
-    def __init__(self, root_name, vendored_names=(), vendor_pkg=None):
-        self.root_name = root_name
-        self.vendored_names = set(vendored_names)
-        self.vendor_pkg = vendor_pkg or root_name.replace('extern', '_vendor')
-
-    @property
-    def search_path(self):
-        """
-        Search first the vendor package then as a natural package.
-        """
-        yield self.vendor_pkg + '.'
-        yield ''
-
-    def _module_matches_namespace(self, fullname):
-        """Figure out if the target module is vendored."""
-        root, base, target = fullname.partition(self.root_name + '.')
-        return not root and any(map(target.startswith, self.vendored_names))
-
-    def load_module(self, fullname):
-        """
-        Iterate over the search path to locate and load fullname.
-        """
-        root, base, target = fullname.partition(self.root_name + '.')
-        for prefix in self.search_path:
-            try:
-                extant = prefix + target
-                __import__(extant)
-                mod = sys.modules[extant]
-                sys.modules[fullname] = mod
-                return mod
-            except ImportError:
-                pass
-        else:
-            raise ImportError(
-                "The '{target}' package is required; "
-                "normally this is bundled with this package so if you get "
-                "this warning, consult the packager of your "
-                "distribution.".format(**locals())
-            )
-
-    def create_module(self, spec):
-        return self.load_module(spec.name)
-
-    def exec_module(self, module):
-        pass
-
-    def find_spec(self, fullname, path=None, target=None):
-        """Return a module spec for vendored names."""
-        return (
-            importlib.util.spec_from_loader(fullname, self)
-            if self._module_matches_namespace(fullname)
-            else None
-        )
-
-    def install(self):
-        """
-        Install this importer into sys.meta_path if not already present.
-        """
-        if self not in sys.meta_path:
-            sys.meta_path.append(self)
-
-
-names = (
-    'packaging',
-    'ordered_set',
-    'more_itertools',
-    'importlib_metadata',
-    'zipp',
-    'importlib_resources',
-    'jaraco',
-    'typing_extensions',
-    'tomli',
-)
-VendorImporter(__name__, names, 'setuptools._vendor').install()
diff --git a/setuptools/glob.py b/setuptools/glob.py
index 647b9bc6ed..1dfff2cd50 100644
--- a/setuptools/glob.py
+++ b/setuptools/glob.py
@@ -6,14 +6,21 @@
  * Hidden files are not ignored.
 """
 
+from __future__ import annotations
+
+import fnmatch
 import os
 import re
-import fnmatch
+from collections.abc import Iterable, Iterator
+from typing import TYPE_CHECKING, AnyStr, overload
+
+if TYPE_CHECKING:
+    from _typeshed import BytesPath, StrOrBytesPath, StrPath
 
 __all__ = ["glob", "iglob", "escape"]
 
 
-def glob(pathname, recursive=False):
+def glob(pathname: AnyStr, recursive: bool = False) -> list[AnyStr]:
     """Return a list of paths matching a pathname pattern.
 
     The pattern may contain simple shell-style wildcards a la
@@ -27,7 +34,7 @@ def glob(pathname, recursive=False):
     return list(iglob(pathname, recursive=recursive))
 
 
-def iglob(pathname, recursive=False):
+def iglob(pathname: AnyStr, recursive: bool = False) -> Iterator[AnyStr]:
     """Return an iterator which yields the paths matching a pathname pattern.
 
     The pattern may contain simple shell-style wildcards a la
@@ -45,7 +52,7 @@ def iglob(pathname, recursive=False):
     return it
 
 
-def _iglob(pathname, recursive):
+def _iglob(pathname: AnyStr, recursive: bool) -> Iterator[AnyStr]:
     dirname, basename = os.path.split(pathname)
     glob_in_dir = glob2 if recursive and _isrecursive(basename) else glob1
 
@@ -66,7 +73,7 @@ def _iglob(pathname, recursive):
     # drive or UNC path.  Prevent an infinite recursion if a drive or UNC path
     # contains magic characters (i.e. r'\\?\C:').
     if dirname != pathname and has_magic(dirname):
-        dirs = _iglob(dirname, recursive)
+        dirs: Iterable[AnyStr] = _iglob(dirname, recursive)
     else:
         dirs = [dirname]
     if not has_magic(basename):
@@ -81,7 +88,11 @@ def _iglob(pathname, recursive):
 # takes a literal basename (so it only has to check for its existence).
 
 
-def glob1(dirname, pattern):
+@overload
+def glob1(dirname: StrPath, pattern: str) -> list[str]: ...
+@overload
+def glob1(dirname: BytesPath, pattern: bytes) -> list[bytes]: ...
+def glob1(dirname: StrOrBytesPath, pattern: str | bytes) -> list[str] | list[bytes]:
     if not dirname:
         if isinstance(pattern, bytes):
             dirname = os.curdir.encode('ASCII')
@@ -91,7 +102,8 @@ def glob1(dirname, pattern):
         names = os.listdir(dirname)
     except OSError:
         return []
-    return fnmatch.filter(names, pattern)
+    # mypy false-positives: str or bytes type possibility is always kept in sync
+    return fnmatch.filter(names, pattern)  # type: ignore[type-var, return-value]
 
 
 def glob0(dirname, basename):
@@ -110,15 +122,22 @@ def glob0(dirname, basename):
 # directory.
 
 
-def glob2(dirname, pattern):
+@overload
+def glob2(dirname: StrPath, pattern: str) -> Iterator[str]: ...
+@overload
+def glob2(dirname: BytesPath, pattern: bytes) -> Iterator[bytes]: ...
+def glob2(dirname: StrOrBytesPath, pattern: str | bytes) -> Iterator[str | bytes]:
     assert _isrecursive(pattern)
     yield pattern[:0]
-    for x in _rlistdir(dirname):
-        yield x
+    yield from _rlistdir(dirname)
 
 
 # Recursively yields relative pathnames inside a literal directory.
-def _rlistdir(dirname):
+@overload
+def _rlistdir(dirname: StrPath) -> Iterator[str]: ...
+@overload
+def _rlistdir(dirname: BytesPath) -> Iterator[bytes]: ...
+def _rlistdir(dirname: StrOrBytesPath) -> Iterator[str | bytes]:
     if not dirname:
         if isinstance(dirname, bytes):
             dirname = os.curdir.encode('ASCII')
@@ -126,28 +145,28 @@ def _rlistdir(dirname):
             dirname = os.curdir
     try:
         names = os.listdir(dirname)
-    except os.error:
+    except OSError:
         return
     for x in names:
         yield x
-        path = os.path.join(dirname, x) if dirname else x
+        # mypy false-positives: str or bytes type possibility is always kept in sync
+        path = os.path.join(dirname, x) if dirname else x  # type: ignore[arg-type]
         for y in _rlistdir(path):
-            yield os.path.join(x, y)
+            yield os.path.join(x, y)  # type: ignore[arg-type]
 
 
 magic_check = re.compile('([*?[])')
 magic_check_bytes = re.compile(b'([*?[])')
 
 
-def has_magic(s):
+def has_magic(s: str | bytes) -> bool:
     if isinstance(s, bytes):
-        match = magic_check_bytes.search(s)
+        return magic_check_bytes.search(s) is not None
     else:
-        match = magic_check.search(s)
-    return match is not None
+        return magic_check.search(s) is not None
 
 
-def _isrecursive(pattern):
+def _isrecursive(pattern: str | bytes) -> bool:
     if isinstance(pattern, bytes):
         return pattern == b'**'
     else:
@@ -160,7 +179,7 @@ def escape(pathname):
     # Metacharacters do not work in the drive part and shouldn't be escaped.
     drive, pathname = os.path.splitdrive(pathname)
     if isinstance(pathname, bytes):
-        pathname = magic_check_bytes.sub(br'[\1]', pathname)
+        pathname = magic_check_bytes.sub(rb'[\1]', pathname)
     else:
         pathname = magic_check.sub(r'[\1]', pathname)
     return drive + pathname
diff --git a/setuptools/installer.py b/setuptools/installer.py
index e83f959a1b..36a8b09227 100644
--- a/setuptools/installer.py
+++ b/setuptools/installer.py
@@ -1,15 +1,22 @@
+from __future__ import annotations
+
 import glob
+import itertools
 import os
 import subprocess
 import sys
 import tempfile
-from distutils import log
-from distutils.errors import DistutilsError
-from functools import partial
+
+import packaging.requirements
+import packaging.utils
 
 from . import _reqs
-from .wheel import Wheel
+from ._importlib import metadata
 from .warnings import SetuptoolsDeprecationWarning
+from .wheel import Wheel
+
+from distutils import log
+from distutils.errors import DistutilsError
 
 
 def _fixup_find_links(find_links):
@@ -20,7 +27,7 @@ def _fixup_find_links(find_links):
     return find_links
 
 
-def fetch_build_egg(dist, req):
+def fetch_build_egg(dist, req) -> metadata.Distribution | metadata.PathDistribution:
     """Fetch an egg needed for building.
 
     Use pip/wheel to fetch/build a wheel."""
@@ -29,25 +36,38 @@ def fetch_build_egg(dist, req):
     return _fetch_build_egg_no_warn(dist, req)
 
 
-def _fetch_build_eggs(dist, requires):
-    import pkg_resources  # Delay import to avoid unnecessary side-effects
+def _present(req):
+    return any(_dist_matches_req(dist, req) for dist in metadata.distributions())
+
 
+def _fetch_build_eggs(dist, requires: _reqs._StrOrIter) -> list[metadata.Distribution]:
     _DeprecatedInstaller.emit(stacklevel=3)
     _warn_wheel_not_available(dist)
 
-    resolved_dists = pkg_resources.working_set.resolve(
-        _reqs.parse(requires, pkg_resources.Requirement),  # required for compatibility
-        installer=partial(_fetch_build_egg_no_warn, dist),  # avoid warning twice
-        replace_conflicting=True,
+    parsed_reqs = _reqs.parse(requires)
+
+    missing_reqs = itertools.filterfalse(_present, parsed_reqs)
+
+    needed_reqs = (
+        req for req in missing_reqs if not req.marker or req.marker.evaluate()
     )
+    resolved_dists = [_fetch_build_egg_no_warn(dist, req) for req in needed_reqs]
     for dist in resolved_dists:
-        pkg_resources.working_set.add(dist, replace=True)
+        # dist.locate_file('') is the directory containing EGG-INFO, where the importabl
+        # contents can be found.
+        sys.path.insert(0, str(dist.locate_file('')))
     return resolved_dists
 
 
-def _fetch_build_egg_no_warn(dist, req):  # noqa: C901  # is too complex (16)  # FIXME
-    import pkg_resources  # Delay import to avoid unnecessary side-effects
+def _dist_matches_req(egg_dist, req):
+    return (
+        packaging.utils.canonicalize_name(egg_dist.name)
+        == packaging.utils.canonicalize_name(req.name)
+        and egg_dist.version in req.specifier
+    )
+
 
+def _fetch_build_egg_no_warn(dist, req):  # noqa: C901  # is too complex (16)  # FIXME
     # Ignore environment markers; if supplied, it is required.
     req = strip_marker(req)
     # Take easy_install options into account, but do not override relevant
@@ -72,9 +92,9 @@ def _fetch_build_egg_no_warn(dist, req):  # noqa: C901  # is too complex (16)  #
     if dist.dependency_links:
         find_links.extend(dist.dependency_links)
     eggs_dir = os.path.realpath(dist.get_egg_cache_dir())
-    environment = pkg_resources.Environment()
-    for egg_dist in pkg_resources.find_distributions(eggs_dir):
-        if egg_dist in req and environment.can_add(egg_dist):
+    cached_dists = metadata.Distribution.discover(path=glob.glob(f'{eggs_dir}/*.egg'))
+    for egg_dist in cached_dists:
+        if _dist_matches_req(egg_dist, req):
             return egg_dist
     with tempfile.TemporaryDirectory() as tmpdir:
         cmd = [
@@ -104,35 +124,25 @@ def _fetch_build_egg_no_warn(dist, req):  # noqa: C901  # is too complex (16)  #
         wheel = Wheel(glob.glob(os.path.join(tmpdir, '*.whl'))[0])
         dist_location = os.path.join(eggs_dir, wheel.egg_name())
         wheel.install_as_egg(dist_location)
-        dist_metadata = pkg_resources.PathMetadata(
-            dist_location, os.path.join(dist_location, 'EGG-INFO')
-        )
-        dist = pkg_resources.Distribution.from_filename(
-            dist_location, metadata=dist_metadata
-        )
-        return dist
+        return metadata.Distribution.at(dist_location + '/EGG-INFO')
 
 
-def strip_marker(req):
+def strip_marker(req) -> packaging.requirements.Requirement:
     """
     Return a new requirement without the environment marker to avoid
     calling pip with something like `babel; extra == "i18n"`, which
     would always be ignored.
     """
-    import pkg_resources  # Delay import to avoid unnecessary side-effects
-
     # create a copy to avoid mutating the input
-    req = pkg_resources.Requirement.parse(str(req))
+    req = packaging.requirements.Requirement(str(req))
     req.marker = None
     return req
 
 
 def _warn_wheel_not_available(dist):
-    import pkg_resources  # Delay import to avoid unnecessary side-effects
-
     try:
-        pkg_resources.get_distribution('wheel')
-    except pkg_resources.DistributionNotFound:
+        metadata.distribution('wheel')
+    except metadata.PackageNotFoundError:
         dist.announce('WARNING: The wheel package is not available.', log.WARN)
 
 
@@ -142,4 +152,4 @@ class _DeprecatedInstaller(SetuptoolsDeprecationWarning):
     Requirements should be satisfied by a PEP 517 installer.
     If you are using pip, you can try `pip install --use-pep517`.
     """
-    # _DUE_DATE not decided yet
+    _DUE_DATE = 2025, 10, 31
diff --git a/setuptools/launch.py b/setuptools/launch.py
index 0208fdf33b..0d162647d5 100644
--- a/setuptools/launch.py
+++ b/setuptools/launch.py
@@ -6,11 +6,11 @@
 # Note that setuptools gets imported implicitly by the
 # invocation of this script using python -m setuptools.launch
 
-import tokenize
 import sys
+import tokenize
 
 
-def run():
+def run() -> None:
     """
     Run the script in sys.argv[1] as if it had
     been invoked naturally.
diff --git a/setuptools/command/launcher manifest.xml b/setuptools/launcher manifest.xml
similarity index 100%
rename from setuptools/command/launcher manifest.xml
rename to setuptools/launcher manifest.xml
diff --git a/setuptools/logging.py b/setuptools/logging.py
index ceca99ca76..532da899f7 100644
--- a/setuptools/logging.py
+++ b/setuptools/logging.py
@@ -1,15 +1,17 @@
-import sys
 import inspect
 import logging
-import distutils.log
+import sys
+
 from . import monkey
 
+import distutils.log
+
 
 def _not_warning(record):
     return record.levelno < logging.WARNING
 
 
-def configure():
+def configure() -> None:
     """
     Configure logging to emit warning and above to stderr
     and everything else to stdout. This behavior is provided
@@ -33,6 +35,6 @@ def configure():
         distutils.dist.log = distutils.log
 
 
-def set_threshold(level):
+def set_threshold(level: int) -> int:
     logging.root.setLevel(level * 10)
     return set_threshold.unpatched(level)
diff --git a/setuptools/modified.py b/setuptools/modified.py
new file mode 100644
index 0000000000..6ba02fab68
--- /dev/null
+++ b/setuptools/modified.py
@@ -0,0 +1,18 @@
+try:
+    # Ensure a DistutilsError raised by these methods is the same as distutils.errors.DistutilsError
+    from distutils._modified import (
+        newer,
+        newer_group,
+        newer_pairwise,
+        newer_pairwise_group,
+    )
+except ImportError:
+    # fallback for SETUPTOOLS_USE_DISTUTILS=stdlib, because _modified never existed in stdlib
+    from ._distutils._modified import (
+        newer,
+        newer_group,
+        newer_pairwise,
+        newer_pairwise_group,
+    )
+
+__all__ = ['newer', 'newer_pairwise', 'newer_group', 'newer_pairwise_group']
diff --git a/setuptools/monkey.py b/setuptools/monkey.py
index 2ab98c178a..24bb8180f9 100644
--- a/setuptools/monkey.py
+++ b/setuptools/monkey.py
@@ -2,17 +2,21 @@
 Monkey patching of distutils.
 """
 
-import functools
+from __future__ import annotations
+
 import inspect
 import platform
 import sys
 import types
-from importlib import import_module
+from typing import TypeVar, cast, overload
 
 import distutils.filelist
 
+_T = TypeVar("_T")
+_UnpatchT = TypeVar("_UnpatchT", type, types.FunctionType)
+
 
-__all__ = []
+__all__: list[str] = []
 """
 Everything is private. Contact the project team
 if you think you need this functionality.
@@ -33,53 +37,43 @@ def _get_mro(cls):
     return inspect.getmro(cls)
 
 
-def get_unpatched(item):
-    lookup = (
-        get_unpatched_class
-        if isinstance(item, type)
-        else get_unpatched_function
-        if isinstance(item, types.FunctionType)
-        else lambda item: None
-    )
-    return lookup(item)
+@overload
+def get_unpatched(item: _UnpatchT) -> _UnpatchT: ...
+@overload
+def get_unpatched(item: object) -> None: ...
+def get_unpatched(
+    item: type | types.FunctionType | object,
+) -> type | types.FunctionType | None:
+    if isinstance(item, type):
+        return get_unpatched_class(item)
+    if isinstance(item, types.FunctionType):
+        return get_unpatched_function(item)
+    return None
 
 
-def get_unpatched_class(cls):
+def get_unpatched_class(cls: type[_T]) -> type[_T]:
     """Protect against re-patching the distutils if reloaded
 
     Also ensures that no other distutils extension monkeypatched the distutils
     first.
     """
     external_bases = (
-        cls for cls in _get_mro(cls) if not cls.__module__.startswith('setuptools')
+        cast(type[_T], cls)
+        for cls in _get_mro(cls)
+        if not cls.__module__.startswith('setuptools')
     )
     base = next(external_bases)
     if not base.__module__.startswith('distutils'):
-        msg = "distutils has already been patched by %r" % cls
+        msg = f"distutils has already been patched by {cls!r}"
         raise AssertionError(msg)
     return base
 
 
-def patch_all():
+def patch_all() -> None:
     import setuptools
 
     # we can't patch distutils.cmd, alas
-    distutils.core.Command = setuptools.Command
-
-    has_issue_12885 = sys.version_info <= (3, 5, 3)
-
-    if has_issue_12885:
-        # fix findall bug in distutils (http://bugs.python.org/issue12885)
-        distutils.filelist.findall = setuptools.findall
-
-    needs_warehouse = (3, 4) < sys.version_info < (3, 4, 6) or (
-        3,
-        5,
-    ) < sys.version_info <= (3, 5, 3)
-
-    if needs_warehouse:
-        warehouse = 'https://upload.pypi.org/legacy/'
-        distutils.config.PyPIRCCommand.DEFAULT_REPOSITORY = warehouse
+    distutils.core.Command = setuptools.Command  # type: ignore[misc,assignment] # monkeypatching
 
     _patch_distribution_metadata()
 
@@ -88,15 +82,13 @@ def patch_all():
         module.Distribution = setuptools.dist.Distribution
 
     # Install the patched Extension
-    distutils.core.Extension = setuptools.extension.Extension
-    distutils.extension.Extension = setuptools.extension.Extension
+    distutils.core.Extension = setuptools.extension.Extension  # type: ignore[misc,assignment] # monkeypatching
+    distutils.extension.Extension = setuptools.extension.Extension  # type: ignore[misc,assignment] # monkeypatching
     if 'distutils.command.build_ext' in sys.modules:
         sys.modules[
             'distutils.command.build_ext'
         ].Extension = setuptools.extension.Extension
 
-    patch_for_msvc_specialized_compiler()
-
 
 def _patch_distribution_metadata():
     from . import _core_metadata
@@ -107,12 +99,13 @@ def _patch_distribution_metadata():
         'write_pkg_file',
         'read_pkg_file',
         'get_metadata_version',
+        'get_fullname',
     ):
         new_val = getattr(_core_metadata, attr)
         setattr(distutils.dist.DistributionMetadata, attr, new_val)
 
 
-def patch_func(replacement, target_mod, func_name):
+def patch_func(replacement, target_mod, func_name) -> None:
     """
     Patch func_name in target_mod with replacement
 
@@ -130,38 +123,4 @@ def patch_func(replacement, target_mod, func_name):
 
 
 def get_unpatched_function(candidate):
-    return getattr(candidate, 'unpatched')
-
-
-def patch_for_msvc_specialized_compiler():
-    """
-    Patch functions in distutils to use standalone Microsoft Visual C++
-    compilers.
-    """
-    # import late to avoid circular imports on Python < 3.5
-    msvc = import_module('setuptools.msvc')
-
-    if platform.system() != 'Windows':
-        # Compilers only available on Microsoft Windows
-        return
-
-    def patch_params(mod_name, func_name):
-        """
-        Prepare the parameters for patch_func to patch indicated function.
-        """
-        repl_prefix = 'msvc14_'
-        repl_name = repl_prefix + func_name.lstrip('_')
-        repl = getattr(msvc, repl_name)
-        mod = import_module(mod_name)
-        if not hasattr(mod, func_name):
-            raise ImportError(func_name)
-        return repl, mod, func_name
-
-    # Python 3.5+
-    msvc14 = functools.partial(patch_params, 'distutils._msvccompiler')
-
-    try:
-        # Patch distutils._msvccompiler._get_vc_env
-        patch_func(*msvc14('_get_vc_env'))
-    except ImportError:
-        pass
+    return candidate.unpatched
diff --git a/setuptools/msvc.py b/setuptools/msvc.py
index 5785c16945..f506c8222d 100644
--- a/setuptools/msvc.py
+++ b/setuptools/msvc.py
@@ -1,29 +1,32 @@
 """
-Improved support for Microsoft Visual C++ compilers.
+Environment info about Microsoft Compilers.
 
-Known supported compilers:
---------------------------
-Microsoft Visual C++ 14.X:
-    Microsoft Visual C++ Build Tools 2015 (x86, x64, arm)
-    Microsoft Visual Studio Build Tools 2017 (x86, x64, arm, arm64)
-    Microsoft Visual Studio Build Tools 2019 (x86, x64, arm, arm64)
-
-This may also support compilers shipped with compatible Visual Studio versions.
+>>> getfixture('windows_only')
+>>> ei = EnvironmentInfo('amd64')
 """
 
-import json
-from io import open
-from os import listdir, pathsep
-from os.path import join, isfile, isdir, dirname
-from subprocess import CalledProcessError
+from __future__ import annotations
+
 import contextlib
-import platform
 import itertools
-import subprocess
+import json
+import os
+import os.path
+import platform
+from typing import TYPE_CHECKING, TypedDict, overload
+
+from more_itertools import unique_everseen
+
+from ._path import StrPath
+from .compat import py310
+
 import distutils.errors
-from setuptools.extern.more_itertools import unique_everseen
 
-if platform.system() == 'Windows':
+if TYPE_CHECKING:
+    from typing_extensions import LiteralString, NotRequired
+
+# https://github.com/python/mypy/issues/8166
+if not TYPE_CHECKING and platform.system() == 'Windows':
     import winreg
     from os import environ
 else:
@@ -35,244 +38,7 @@ class winreg:
         HKEY_LOCAL_MACHINE = None
         HKEY_CLASSES_ROOT = None
 
-    environ = dict()
-
-
-def _msvc14_find_vc2015():
-    """Python 3.8 "distutils/_msvccompiler.py" backport"""
-    try:
-        key = winreg.OpenKey(
-            winreg.HKEY_LOCAL_MACHINE,
-            r"Software\Microsoft\VisualStudio\SxS\VC7",
-            0,
-            winreg.KEY_READ | winreg.KEY_WOW64_32KEY,
-        )
-    except OSError:
-        return None, None
-
-    best_version = 0
-    best_dir = None
-    with key:
-        for i in itertools.count():
-            try:
-                v, vc_dir, vt = winreg.EnumValue(key, i)
-            except OSError:
-                break
-            if v and vt == winreg.REG_SZ and isdir(vc_dir):
-                try:
-                    version = int(float(v))
-                except (ValueError, TypeError):
-                    continue
-                if version >= 14 and version > best_version:
-                    best_version, best_dir = version, vc_dir
-    return best_version, best_dir
-
-
-def _msvc14_find_vc2017():
-    """Python 3.8 "distutils/_msvccompiler.py" backport
-
-    Returns "15, path" based on the result of invoking vswhere.exe
-    If no install is found, returns "None, None"
-
-    The version is returned to avoid unnecessarily changing the function
-    result. It may be ignored when the path is not None.
-
-    If vswhere.exe is not available, by definition, VS 2017 is not
-    installed.
-    """
-    root = environ.get("ProgramFiles(x86)") or environ.get("ProgramFiles")
-    if not root:
-        return None, None
-
-    suitable_components = (
-        "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
-        "Microsoft.VisualStudio.Workload.WDExpress",
-    )
-
-    for component in suitable_components:
-        # Workaround for `-requiresAny` (only available on VS 2017 > 15.6)
-        with contextlib.suppress(CalledProcessError, OSError, UnicodeDecodeError):
-            path = (
-                subprocess.check_output(
-                    [
-                        join(
-                            root, "Microsoft Visual Studio", "Installer", "vswhere.exe"
-                        ),
-                        "-latest",
-                        "-prerelease",
-                        "-requires",
-                        component,
-                        "-property",
-                        "installationPath",
-                        "-products",
-                        "*",
-                    ]
-                )
-                .decode(encoding="mbcs", errors="strict")
-                .strip()
-            )
-
-            path = join(path, "VC", "Auxiliary", "Build")
-            if isdir(path):
-                return 15, path
-
-    return None, None  # no suitable component found
-
-
-PLAT_SPEC_TO_RUNTIME = {
-    'x86': 'x86',
-    'x86_amd64': 'x64',
-    'x86_arm': 'arm',
-    'x86_arm64': 'arm64',
-}
-
-
-def _msvc14_find_vcvarsall(plat_spec):
-    """Python 3.8 "distutils/_msvccompiler.py" backport"""
-    _, best_dir = _msvc14_find_vc2017()
-    vcruntime = None
-
-    if plat_spec in PLAT_SPEC_TO_RUNTIME:
-        vcruntime_plat = PLAT_SPEC_TO_RUNTIME[plat_spec]
-    else:
-        vcruntime_plat = 'x64' if 'amd64' in plat_spec else 'x86'
-
-    if best_dir:
-        vcredist = join(
-            best_dir,
-            "..",
-            "..",
-            "redist",
-            "MSVC",
-            "**",
-            vcruntime_plat,
-            "Microsoft.VC14*.CRT",
-            "vcruntime140.dll",
-        )
-        try:
-            import glob
-
-            vcruntime = glob.glob(vcredist, recursive=True)[-1]
-        except (ImportError, OSError, LookupError):
-            vcruntime = None
-
-    if not best_dir:
-        best_version, best_dir = _msvc14_find_vc2015()
-        if best_version:
-            vcruntime = join(
-                best_dir,
-                'redist',
-                vcruntime_plat,
-                "Microsoft.VC140.CRT",
-                "vcruntime140.dll",
-            )
-
-    if not best_dir:
-        return None, None
-
-    vcvarsall = join(best_dir, "vcvarsall.bat")
-    if not isfile(vcvarsall):
-        return None, None
-
-    if not vcruntime or not isfile(vcruntime):
-        vcruntime = None
-
-    return vcvarsall, vcruntime
-
-
-def _msvc14_get_vc_env(plat_spec):
-    """Python 3.8 "distutils/_msvccompiler.py" backport"""
-    if "DISTUTILS_USE_SDK" in environ:
-        return {key.lower(): value for key, value in environ.items()}
-
-    vcvarsall, vcruntime = _msvc14_find_vcvarsall(plat_spec)
-    if not vcvarsall:
-        raise distutils.errors.DistutilsPlatformError("Unable to find vcvarsall.bat")
-
-    try:
-        out = subprocess.check_output(
-            'cmd /u /c "{}" {} && set'.format(vcvarsall, plat_spec),
-            stderr=subprocess.STDOUT,
-        ).decode('utf-16le', errors='replace')
-    except subprocess.CalledProcessError as exc:
-        raise distutils.errors.DistutilsPlatformError(
-            "Error executing {}".format(exc.cmd)
-        ) from exc
-
-    env = {
-        key.lower(): value
-        for key, _, value in (line.partition('=') for line in out.splitlines())
-        if key and value
-    }
-
-    if vcruntime:
-        env['py_vcruntime_redist'] = vcruntime
-    return env
-
-
-def msvc14_get_vc_env(plat_spec):
-    """
-    Patched "distutils._msvccompiler._get_vc_env" for support extra
-    Microsoft Visual C++ 14.X compilers.
-
-    Set environment without use of "vcvarsall.bat".
-
-    Parameters
-    ----------
-    plat_spec: str
-        Target architecture.
-
-    Return
-    ------
-    dict
-        environment
-    """
-
-    # Always use backport from CPython 3.8
-    try:
-        return _msvc14_get_vc_env(plat_spec)
-    except distutils.errors.DistutilsPlatformError as exc:
-        _augment_exception(exc, 14.0)
-        raise
-
-
-def _augment_exception(exc, version, arch=''):
-    """
-    Add details to the exception message to help guide the user
-    as to what action will resolve it.
-    """
-    # Error if MSVC++ directory not found or environment not set
-    message = exc.args[0]
-
-    if "vcvarsall" in message.lower() or "visual c" in message.lower():
-        # Special error message if MSVC++ not installed
-        tmpl = 'Microsoft Visual C++ {version:0.1f} or greater is required.'
-        message = tmpl.format(**locals())
-        msdownload = 'www.microsoft.com/download/details.aspx?id=%d'
-        if version == 9.0:
-            if arch.lower().find('ia64') > -1:
-                # For VC++ 9.0, if IA64 support is needed, redirect user
-                # to Windows SDK 7.0.
-                # Note: No download link available from Microsoft.
-                message += ' Get it with "Microsoft Windows SDK 7.0"'
-            else:
-                # For VC++ 9.0 redirect user to Vc++ for Python 2.7 :
-                # This redirection link is maintained by Microsoft.
-                # Contact vspython@microsoft.com if it needs updating.
-                message += ' Get it from http://aka.ms/vcpython27'
-        elif version == 10.0:
-            # For VC++ 10.0 Redirect user to Windows SDK 7.1
-            message += ' Get it with "Microsoft Windows SDK 7.1": '
-            message += msdownload % 8279
-        elif version >= 14.0:
-            # For VC++ 14.X Redirect user to latest Visual C++ Build Tools
-            message += (
-                ' Get it with "Microsoft C++ Build Tools": '
-                r'https://visualstudio.microsoft.com'
-                r'/visual-cpp-build-tools/'
-            )
-
-    exc.args = (message,)
+    environ: dict[str, str] = dict()
 
 
 class PlatformInfo:
@@ -287,11 +53,11 @@ class PlatformInfo:
 
     current_cpu = environ.get('processor_architecture', '').lower()
 
-    def __init__(self, arch):
+    def __init__(self, arch: str) -> None:
         self.arch = arch.lower().replace('x64', 'amd64')
 
     @property
-    def target_cpu(self):
+    def target_cpu(self) -> str:
         """
         Return Target CPU architecture.
 
@@ -302,7 +68,7 @@ def target_cpu(self):
         """
         return self.arch[self.arch.find('_') + 1 :]
 
-    def target_is_x86(self):
+    def target_is_x86(self) -> bool:
         """
         Return True if target CPU is x86 32 bits..
 
@@ -313,7 +79,7 @@ def target_is_x86(self):
         """
         return self.target_cpu == 'x86'
 
-    def current_is_x86(self):
+    def current_is_x86(self) -> bool:
         """
         Return True if current CPU is x86 32 bits..
 
@@ -324,7 +90,7 @@ def current_is_x86(self):
         """
         return self.current_cpu == 'x86'
 
-    def current_dir(self, hidex86=False, x64=False):
+    def current_dir(self, hidex86=False, x64=False) -> str:
         """
         Current platform specific subfolder.
 
@@ -345,10 +111,10 @@ def current_dir(self, hidex86=False, x64=False):
             if (self.current_cpu == 'x86' and hidex86)
             else r'\x64'
             if (self.current_cpu == 'amd64' and x64)
-            else r'\%s' % self.current_cpu
+            else rf'\{self.current_cpu}'
         )
 
-    def target_dir(self, hidex86=False, x64=False):
+    def target_dir(self, hidex86=False, x64=False) -> str:
         r"""
         Target platform specific subfolder.
 
@@ -369,10 +135,10 @@ def target_dir(self, hidex86=False, x64=False):
             if (self.target_cpu == 'x86' and hidex86)
             else r'\x64'
             if (self.target_cpu == 'amd64' and x64)
-            else r'\%s' % self.target_cpu
+            else rf'\{self.target_cpu}'
         )
 
-    def cross_dir(self, forcex86=False):
+    def cross_dir(self, forcex86=False) -> str:
         r"""
         Cross platform specific subfolder.
 
@@ -392,7 +158,7 @@ def cross_dir(self, forcex86=False):
         return (
             ''
             if self.target_cpu == current
-            else self.target_dir().replace('\\', '\\%s_' % current)
+            else self.target_dir().replace('\\', f'\\{current}_')
         )
 
 
@@ -413,11 +179,11 @@ class RegistryInfo:
         winreg.HKEY_CLASSES_ROOT,
     )
 
-    def __init__(self, platform_info):
+    def __init__(self, platform_info: PlatformInfo) -> None:
         self.pi = platform_info
 
     @property
-    def visualstudio(self):
+    def visualstudio(self) -> LiteralString:
         """
         Microsoft Visual Studio root registry key.
 
@@ -429,7 +195,7 @@ def visualstudio(self):
         return 'VisualStudio'
 
     @property
-    def sxs(self):
+    def sxs(self) -> LiteralString:
         """
         Microsoft Visual Studio SxS registry key.
 
@@ -438,10 +204,10 @@ def sxs(self):
         str
             Registry key
         """
-        return join(self.visualstudio, 'SxS')
+        return os.path.join(self.visualstudio, 'SxS')
 
     @property
-    def vc(self):
+    def vc(self) -> LiteralString:
         """
         Microsoft Visual C++ VC7 registry key.
 
@@ -450,10 +216,10 @@ def vc(self):
         str
             Registry key
         """
-        return join(self.sxs, 'VC7')
+        return os.path.join(self.sxs, 'VC7')
 
     @property
-    def vs(self):
+    def vs(self) -> LiteralString:
         """
         Microsoft Visual Studio VS7 registry key.
 
@@ -462,10 +228,10 @@ def vs(self):
         str
             Registry key
         """
-        return join(self.sxs, 'VS7')
+        return os.path.join(self.sxs, 'VS7')
 
     @property
-    def vc_for_python(self):
+    def vc_for_python(self) -> LiteralString:
         """
         Microsoft Visual C++ for Python registry key.
 
@@ -477,7 +243,7 @@ def vc_for_python(self):
         return r'DevDiv\VCForPython'
 
     @property
-    def microsoft_sdk(self):
+    def microsoft_sdk(self) -> LiteralString:
         """
         Microsoft SDK registry key.
 
@@ -489,7 +255,7 @@ def microsoft_sdk(self):
         return 'Microsoft SDKs'
 
     @property
-    def windows_sdk(self):
+    def windows_sdk(self) -> LiteralString:
         """
         Microsoft Windows/Platform SDK registry key.
 
@@ -498,10 +264,10 @@ def windows_sdk(self):
         str
             Registry key
         """
-        return join(self.microsoft_sdk, 'Windows')
+        return os.path.join(self.microsoft_sdk, 'Windows')
 
     @property
-    def netfx_sdk(self):
+    def netfx_sdk(self) -> LiteralString:
         """
         Microsoft .NET Framework SDK registry key.
 
@@ -510,10 +276,10 @@ def netfx_sdk(self):
         str
             Registry key
         """
-        return join(self.microsoft_sdk, 'NETFXSDK')
+        return os.path.join(self.microsoft_sdk, 'NETFXSDK')
 
     @property
-    def windows_kits_roots(self):
+    def windows_kits_roots(self) -> LiteralString:
         """
         Microsoft Windows Kits Roots registry key.
 
@@ -524,7 +290,11 @@ def windows_kits_roots(self):
         """
         return r'Windows Kits\Installed Roots'
 
-    def microsoft(self, key, x86=False):
+    @overload
+    def microsoft(self, key: LiteralString, x86: bool = False) -> LiteralString: ...
+    @overload
+    def microsoft(self, key: str, x86: bool = False) -> str: ...  # type: ignore[misc]
+    def microsoft(self, key: str, x86: bool = False) -> str:
         """
         Return key in Microsoft software registry.
 
@@ -532,7 +302,7 @@ def microsoft(self, key, x86=False):
         ----------
         key: str
             Registry key path where look.
-        x86: str
+        x86: bool
             Force x86 software registry.
 
         Return
@@ -541,9 +311,9 @@ def microsoft(self, key, x86=False):
             Registry key
         """
         node64 = '' if self.pi.current_is_x86() or x86 else 'Wow6432Node'
-        return join('Software', node64, 'Microsoft', key)
+        return os.path.join('Software', node64, 'Microsoft', key)
 
-    def lookup(self, key, name):
+    def lookup(self, key: str, name: str) -> str | None:
         """
         Look for values in registry in Microsoft software registry.
 
@@ -556,7 +326,7 @@ def lookup(self, key, name):
 
         Return
         ------
-        str
+        str | None
             value
         """
         key_read = winreg.KEY_READ
@@ -567,21 +337,22 @@ def lookup(self, key, name):
             bkey = None
             try:
                 bkey = openkey(hkey, ms(key), 0, key_read)
-            except (OSError, IOError):
+            except OSError:
                 if not self.pi.current_is_x86():
                     try:
                         bkey = openkey(hkey, ms(key, True), 0, key_read)
-                    except (OSError, IOError):
+                    except OSError:
                         continue
                 else:
                     continue
             try:
                 return winreg.QueryValueEx(bkey, name)[0]
-            except (OSError, IOError):
+            except OSError:
                 pass
             finally:
                 if bkey:
                     closekey(bkey)
+        return None
 
 
 class SystemInfo:
@@ -602,7 +373,9 @@ class SystemInfo:
     ProgramFiles = environ.get('ProgramFiles', '')
     ProgramFilesx86 = environ.get('ProgramFiles(x86)', ProgramFiles)
 
-    def __init__(self, registry_info, vc_ver=None):
+    def __init__(
+        self, registry_info: RegistryInfo, vc_ver: float | None = None
+    ) -> None:
         self.ri = registry_info
         self.pi = self.ri.pi
 
@@ -629,9 +402,9 @@ def _find_latest_available_vs_ver(self):
 
         vc_vers = set(reg_vc_vers)
         vc_vers.update(self.known_vs_paths)
-        return sorted(vc_vers)[-1]
+        return max(vc_vers)
 
-    def find_reg_vs_vers(self):
+    def find_reg_vs_vers(self) -> list[float]:
         """
         Find Microsoft Visual Studio versions available in registry.
 
@@ -646,7 +419,7 @@ def find_reg_vs_vers(self):
         for hkey, key in itertools.product(self.ri.HKEYS, vckeys):
             try:
                 bkey = winreg.OpenKey(hkey, ms(key), 0, winreg.KEY_READ)
-            except (OSError, IOError):
+            except OSError:
                 continue
             with bkey:
                 subkeys, values, _ = winreg.QueryInfoKey(bkey)
@@ -662,7 +435,7 @@ def find_reg_vs_vers(self):
                             vs_vers.append(ver)
         return sorted(vs_vers)
 
-    def find_programdata_vs_vers(self):
+    def find_programdata_vs_vers(self) -> dict[float, str]:
         r"""
         Find Visual studio 2017+ versions from information in
         "C:\ProgramData\Microsoft\VisualStudio\Packages\_Instances".
@@ -672,33 +445,33 @@ def find_programdata_vs_vers(self):
         dict
             float version as key, path as value.
         """
-        vs_versions = {}
+        vs_versions: dict[float, str] = {}
         instances_dir = r'C:\ProgramData\Microsoft\VisualStudio\Packages\_Instances'
 
         try:
-            hashed_names = listdir(instances_dir)
+            hashed_names = os.listdir(instances_dir)
 
-        except (OSError, IOError):
+        except OSError:
             # Directory not exists with all Visual Studio versions
             return vs_versions
 
         for name in hashed_names:
             try:
                 # Get VS installation path from "state.json" file
-                state_path = join(instances_dir, name, 'state.json')
+                state_path = os.path.join(instances_dir, name, 'state.json')
                 with open(state_path, 'rt', encoding='utf-8') as state_file:
                     state = json.load(state_file)
                 vs_path = state['installationPath']
 
                 # Raises OSError if this VS installation does not contain VC
-                listdir(join(vs_path, r'VC\Tools\MSVC'))
+                os.listdir(os.path.join(vs_path, r'VC\Tools\MSVC'))
 
                 # Store version and path
-                vs_versions[
-                    self._as_float_version(state['installationVersion'])
-                ] = vs_path
+                vs_versions[self._as_float_version(state['installationVersion'])] = (
+                    vs_path
+                )
 
-            except (OSError, IOError, KeyError):
+            except (OSError, KeyError):
                 # Skip if "state.json" file is missing or bad format
                 continue
 
@@ -722,7 +495,7 @@ def _as_float_version(version):
         return float('.'.join(version.split('.')[:2]))
 
     @property
-    def VSInstallDir(self):
+    def VSInstallDir(self) -> str:
         """
         Microsoft Visual Studio directory.
 
@@ -732,15 +505,15 @@ def VSInstallDir(self):
             path
         """
         # Default path
-        default = join(
-            self.ProgramFilesx86, 'Microsoft Visual Studio %0.1f' % self.vs_ver
+        default = os.path.join(
+            self.ProgramFilesx86, f'Microsoft Visual Studio {self.vs_ver:0.1f}'
         )
 
         # Try to get path from registry, if fail use default path
-        return self.ri.lookup(self.ri.vs, '%0.1f' % self.vs_ver) or default
+        return self.ri.lookup(self.ri.vs, f'{self.vs_ver:0.1f}') or default
 
     @property
-    def VCInstallDir(self):
+    def VCInstallDir(self) -> str:
         """
         Microsoft Visual C++ directory.
 
@@ -751,7 +524,7 @@ def VCInstallDir(self):
         """
         path = self._guess_vc() or self._guess_vc_legacy()
 
-        if not isdir(path):
+        if not os.path.isdir(path):
             msg = 'Microsoft Visual C++ directory not found'
             raise distutils.errors.DistutilsPlatformError(msg)
 
@@ -776,15 +549,15 @@ def _guess_vc(self):
             # Else, search with path from registry
             vs_dir = self.VSInstallDir
 
-        guess_vc = join(vs_dir, r'VC\Tools\MSVC')
+        guess_vc = os.path.join(vs_dir, r'VC\Tools\MSVC')
 
         # Subdir with VC exact version as name
         try:
             # Update the VC version with real one instead of VS version
-            vc_ver = listdir(guess_vc)[-1]
+            vc_ver = os.listdir(guess_vc)[-1]
             self.vc_ver = self._as_float_version(vc_ver)
-            return join(guess_vc, vc_ver)
-        except (OSError, IOError, IndexError):
+            return os.path.join(guess_vc, vc_ver)
+        except (OSError, IndexError):
             return ''
 
     def _guess_vc_legacy(self):
@@ -796,20 +569,21 @@ def _guess_vc_legacy(self):
         str
             path
         """
-        default = join(
-            self.ProgramFilesx86, r'Microsoft Visual Studio %0.1f\VC' % self.vs_ver
+        default = os.path.join(
+            self.ProgramFilesx86,
+            rf'Microsoft Visual Studio {self.vs_ver:0.1f}\VC',
         )
 
         # Try to get "VC++ for Python" path from registry as default path
-        reg_path = join(self.ri.vc_for_python, '%0.1f' % self.vs_ver)
+        reg_path = os.path.join(self.ri.vc_for_python, f'{self.vs_ver:0.1f}')
         python_vc = self.ri.lookup(reg_path, 'installdir')
-        default_vc = join(python_vc, 'VC') if python_vc else default
+        default_vc = os.path.join(python_vc, 'VC') if python_vc else default
 
         # Try to get path from registry, if fail use default path
-        return self.ri.lookup(self.ri.vc, '%0.1f' % self.vs_ver) or default_vc
+        return self.ri.lookup(self.ri.vc, f'{self.vs_ver:0.1f}') or default_vc
 
     @property
-    def WindowsSdkVersion(self):
+    def WindowsSdkVersion(self) -> tuple[LiteralString, ...]:
         """
         Microsoft Windows SDK versions for specified MSVC++ version.
 
@@ -828,9 +602,10 @@ def WindowsSdkVersion(self):
             return '8.1', '8.1a'
         elif self.vs_ver >= 14.0:
             return '10.0', '8.1'
+        return ()
 
     @property
-    def WindowsSdkLastVersion(self):
+    def WindowsSdkLastVersion(self) -> str:
         """
         Microsoft Windows SDK last version.
 
@@ -839,10 +614,10 @@ def WindowsSdkLastVersion(self):
         str
             version
         """
-        return self._use_last_dir_name(join(self.WindowsSdkDir, 'lib'))
+        return self._use_last_dir_name(os.path.join(self.WindowsSdkDir, 'lib'))
 
-    @property  # noqa: C901
-    def WindowsSdkDir(self):  # noqa: C901  # is too complex (12)  # FIXME
+    @property
+    def WindowsSdkDir(self) -> str:  # noqa: C901  # is too complex (12)  # FIXME
         """
         Microsoft Windows SDK directory.
 
@@ -851,47 +626,47 @@ def WindowsSdkDir(self):  # noqa: C901  # is too complex (12)  # FIXME
         str
             path
         """
-        sdkdir = ''
+        sdkdir: str | None = ''
         for ver in self.WindowsSdkVersion:
             # Try to get it from registry
-            loc = join(self.ri.windows_sdk, 'v%s' % ver)
+            loc = os.path.join(self.ri.windows_sdk, f'v{ver}')
             sdkdir = self.ri.lookup(loc, 'installationfolder')
             if sdkdir:
                 break
-        if not sdkdir or not isdir(sdkdir):
+        if not sdkdir or not os.path.isdir(sdkdir):
             # Try to get "VC++ for Python" version from registry
-            path = join(self.ri.vc_for_python, '%0.1f' % self.vc_ver)
+            path = os.path.join(self.ri.vc_for_python, f'{self.vc_ver:0.1f}')
             install_base = self.ri.lookup(path, 'installdir')
             if install_base:
-                sdkdir = join(install_base, 'WinSDK')
-        if not sdkdir or not isdir(sdkdir):
+                sdkdir = os.path.join(install_base, 'WinSDK')
+        if not sdkdir or not os.path.isdir(sdkdir):
             # If fail, use default new path
             for ver in self.WindowsSdkVersion:
                 intver = ver[: ver.rfind('.')]
-                path = r'Microsoft SDKs\Windows Kits\%s' % intver
-                d = join(self.ProgramFiles, path)
-                if isdir(d):
+                path = rf'Microsoft SDKs\Windows Kits\{intver}'
+                d = os.path.join(self.ProgramFiles, path)
+                if os.path.isdir(d):
                     sdkdir = d
-        if not sdkdir or not isdir(sdkdir):
+        if not sdkdir or not os.path.isdir(sdkdir):
             # If fail, use default old path
             for ver in self.WindowsSdkVersion:
-                path = r'Microsoft SDKs\Windows\v%s' % ver
-                d = join(self.ProgramFiles, path)
-                if isdir(d):
+                path = rf'Microsoft SDKs\Windows\v{ver}'
+                d = os.path.join(self.ProgramFiles, path)
+                if os.path.isdir(d):
                     sdkdir = d
         if not sdkdir:
             # If fail, use Platform SDK
-            sdkdir = join(self.VCInstallDir, 'PlatformSDK')
+            sdkdir = os.path.join(self.VCInstallDir, 'PlatformSDK')
         return sdkdir
 
     @property
-    def WindowsSDKExecutablePath(self):
+    def WindowsSDKExecutablePath(self) -> str | None:
         """
         Microsoft Windows SDK executable directory.
 
         Return
         ------
-        str
+        str | None
             path
         """
         # Find WinSDK NetFx Tools registry dir name
@@ -901,17 +676,17 @@ def WindowsSDKExecutablePath(self):
         else:
             netfxver = 40
             hidex86 = True if self.vs_ver <= 12.0 else False
-            arch = self.pi.current_dir(x64=True, hidex86=hidex86)
-        fx = 'WinSDK-NetFx%dTools%s' % (netfxver, arch.replace('\\', '-'))
+            arch = self.pi.current_dir(x64=True, hidex86=hidex86).replace('\\', '-')
+        fx = f'WinSDK-NetFx{netfxver}Tools{arch}'
 
         # list all possibles registry paths
         regpaths = []
         if self.vs_ver >= 14.0:
             for ver in self.NetFxSdkVersion:
-                regpaths += [join(self.ri.netfx_sdk, ver, fx)]
+                regpaths += [os.path.join(self.ri.netfx_sdk, ver, fx)]
 
         for ver in self.WindowsSdkVersion:
-            regpaths += [join(self.ri.windows_sdk, 'v%sA' % ver, fx)]
+            regpaths += [os.path.join(self.ri.windows_sdk, f'v{ver}A', fx)]
 
         # Return installation folder from the more recent path
         for path in regpaths:
@@ -919,8 +694,10 @@ def WindowsSDKExecutablePath(self):
             if execpath:
                 return execpath
 
+        return None
+
     @property
-    def FSharpInstallDir(self):
+    def FSharpInstallDir(self) -> str:
         """
         Microsoft Visual F# directory.
 
@@ -929,17 +706,17 @@ def FSharpInstallDir(self):
         str
             path
         """
-        path = join(self.ri.visualstudio, r'%0.1f\Setup\F#' % self.vs_ver)
+        path = os.path.join(self.ri.visualstudio, rf'{self.vs_ver:0.1f}\Setup\F#')
         return self.ri.lookup(path, 'productdir') or ''
 
     @property
-    def UniversalCRTSdkDir(self):
+    def UniversalCRTSdkDir(self) -> str | None:
         """
         Microsoft Universal CRT SDK directory.
 
         Return
         ------
-        str
+        str | None
             path
         """
         # Set Kit Roots versions for specified MSVC++ version
@@ -947,12 +724,14 @@ def UniversalCRTSdkDir(self):
 
         # Find path of the more recent Kit
         for ver in vers:
-            sdkdir = self.ri.lookup(self.ri.windows_kits_roots, 'kitsroot%s' % ver)
+            sdkdir = self.ri.lookup(self.ri.windows_kits_roots, f'kitsroot{ver}')
             if sdkdir:
-                return sdkdir or ''
+                return sdkdir
+
+        return None
 
     @property
-    def UniversalCRTSdkLastVersion(self):
+    def UniversalCRTSdkLastVersion(self) -> str:
         """
         Microsoft Universal C Runtime SDK last version.
 
@@ -961,10 +740,14 @@ def UniversalCRTSdkLastVersion(self):
         str
             version
         """
-        return self._use_last_dir_name(join(self.UniversalCRTSdkDir, 'lib'))
+        try:
+            return self._use_last_dir_name(os.path.join(self.UniversalCRTSdkDir, 'lib'))  # type: ignore[arg-type] # Expected TypeError
+        except TypeError as ex:
+            py310.add_note(ex, "Cannot find UniversalCRTSdkDir")
+            raise
 
     @property
-    def NetFxSdkVersion(self):
+    def NetFxSdkVersion(self) -> tuple[LiteralString, ...]:
         """
         Microsoft .NET Framework SDK versions.
 
@@ -981,25 +764,25 @@ def NetFxSdkVersion(self):
         )
 
     @property
-    def NetFxSdkDir(self):
+    def NetFxSdkDir(self) -> str | None:
         """
         Microsoft .NET Framework SDK directory.
 
         Return
         ------
-        str
+        str | None
             path
         """
-        sdkdir = ''
+        sdkdir: str | None = ''
         for ver in self.NetFxSdkVersion:
-            loc = join(self.ri.netfx_sdk, ver)
+            loc = os.path.join(self.ri.netfx_sdk, ver)
             sdkdir = self.ri.lookup(loc, 'kitsinstallationfolder')
             if sdkdir:
                 break
         return sdkdir
 
     @property
-    def FrameworkDir32(self):
+    def FrameworkDir32(self) -> str:
         """
         Microsoft .NET Framework 32bit directory.
 
@@ -1009,13 +792,13 @@ def FrameworkDir32(self):
             path
         """
         # Default path
-        guess_fw = join(self.WinDir, r'Microsoft.NET\Framework')
+        guess_fw = os.path.join(self.WinDir, r'Microsoft.NET\Framework')
 
         # Try to get path from registry, if fail use default path
         return self.ri.lookup(self.ri.vc, 'frameworkdir32') or guess_fw
 
     @property
-    def FrameworkDir64(self):
+    def FrameworkDir64(self) -> str:
         """
         Microsoft .NET Framework 64bit directory.
 
@@ -1025,13 +808,13 @@ def FrameworkDir64(self):
             path
         """
         # Default path
-        guess_fw = join(self.WinDir, r'Microsoft.NET\Framework64')
+        guess_fw = os.path.join(self.WinDir, r'Microsoft.NET\Framework64')
 
         # Try to get path from registry, if fail use default path
         return self.ri.lookup(self.ri.vc, 'frameworkdir64') or guess_fw
 
     @property
-    def FrameworkVersion32(self):
+    def FrameworkVersion32(self) -> tuple[str, ...]:
         """
         Microsoft .NET Framework 32bit versions.
 
@@ -1043,7 +826,7 @@ def FrameworkVersion32(self):
         return self._find_dot_net_versions(32)
 
     @property
-    def FrameworkVersion64(self):
+    def FrameworkVersion64(self) -> tuple[str, ...]:
         """
         Microsoft .NET Framework 64bit versions.
 
@@ -1054,7 +837,7 @@ def FrameworkVersion64(self):
         """
         return self._find_dot_net_versions(64)
 
-    def _find_dot_net_versions(self, bits):
+    def _find_dot_net_versions(self, bits) -> tuple[str, ...]:
         """
         Find Microsoft .NET Framework versions.
 
@@ -1069,8 +852,8 @@ def _find_dot_net_versions(self, bits):
             versions
         """
         # Find actual .NET version in registry
-        reg_ver = self.ri.lookup(self.ri.vc, 'frameworkver%d' % bits)
-        dot_net_dir = getattr(self, 'FrameworkDir%d' % bits)
+        reg_ver = self.ri.lookup(self.ri.vc, f'frameworkver{bits}')
+        dot_net_dir = getattr(self, f'FrameworkDir{bits}')
         ver = reg_ver or self._use_last_dir_name(dot_net_dir, 'v') or ''
 
         # Set .NET versions for specified MSVC++ version
@@ -1082,15 +865,16 @@ def _find_dot_net_versions(self, bits):
             return 'v3.5', 'v2.0.50727'
         elif self.vs_ver == 8.0:
             return 'v3.0', 'v2.0.50727'
+        return ()
 
     @staticmethod
-    def _use_last_dir_name(path, prefix=''):
+    def _use_last_dir_name(path: StrPath, prefix: str = '') -> str:
         """
         Return name of the last dir in path or '' if no dir found.
 
         Parameters
         ----------
-        path: str
+        path: StrPath
             Use dirs in this path
         prefix: str
             Use only dirs starting by this prefix
@@ -1102,10 +886,19 @@ def _use_last_dir_name(path, prefix=''):
         """
         matching_dirs = (
             dir_name
-            for dir_name in reversed(listdir(path))
-            if isdir(join(path, dir_name)) and dir_name.startswith(prefix)
+            for dir_name in reversed(os.listdir(path))
+            if os.path.isdir(os.path.join(path, dir_name))
+            and dir_name.startswith(prefix)
         )
-        return next(matching_dirs, None) or ''
+        return next(matching_dirs, '')
+
+
+class _EnvironmentDict(TypedDict):
+    include: str
+    lib: str
+    libpath: str
+    path: str
+    py_vcruntime_redist: NotRequired[str | None]
 
 
 class EnvironmentInfo:
@@ -1132,7 +925,7 @@ class EnvironmentInfo:
     # Variables and properties in this class use originals CamelCase variables
     # names from Microsoft source files for more easy comparison.
 
-    def __init__(self, arch, vc_ver=None, vc_min_ver=0):
+    def __init__(self, arch, vc_ver=None, vc_min_ver=0) -> None:
         self.pi = PlatformInfo(arch)
         self.ri = RegistryInfo(self.pi)
         self.si = SystemInfo(self.ri, vc_ver)
@@ -1181,9 +974,9 @@ def VSTools(self):
             arch_subdir = self.pi.current_dir(hidex86=True, x64=True)
             paths += [r'Common7\IDE\CommonExtensions\Microsoft\TestWindow']
             paths += [r'Team Tools\Performance Tools']
-            paths += [r'Team Tools\Performance Tools%s' % arch_subdir]
+            paths += [rf'Team Tools\Performance Tools{arch_subdir}']
 
-        return [join(self.si.VSInstallDir, path) for path in paths]
+        return [os.path.join(self.si.VSInstallDir, path) for path in paths]
 
     @property
     def VCIncludes(self):
@@ -1196,8 +989,8 @@ def VCIncludes(self):
             paths
         """
         return [
-            join(self.si.VCInstallDir, 'Include'),
-            join(self.si.VCInstallDir, r'ATLMFC\Include'),
+            os.path.join(self.si.VCInstallDir, 'Include'),
+            os.path.join(self.si.VCInstallDir, r'ATLMFC\Include'),
         ]
 
     @property
@@ -1214,12 +1007,12 @@ def VCLibraries(self):
             arch_subdir = self.pi.target_dir(x64=True)
         else:
             arch_subdir = self.pi.target_dir(hidex86=True)
-        paths = ['Lib%s' % arch_subdir, r'ATLMFC\Lib%s' % arch_subdir]
+        paths = [f'Lib{arch_subdir}', rf'ATLMFC\Lib{arch_subdir}']
 
         if self.vs_ver >= 14.0:
-            paths += [r'Lib\store%s' % arch_subdir]
+            paths += [rf'Lib\store{arch_subdir}']
 
-        return [join(self.si.VCInstallDir, path) for path in paths]
+        return [os.path.join(self.si.VCInstallDir, path) for path in paths]
 
     @property
     def VCStoreRefs(self):
@@ -1233,7 +1026,7 @@ def VCStoreRefs(self):
         """
         if self.vs_ver < 14.0:
             return []
-        return [join(self.si.VCInstallDir, r'Lib\store\references')]
+        return [os.path.join(self.si.VCInstallDir, r'Lib\store\references')]
 
     @property
     def VCTools(self):
@@ -1244,32 +1037,45 @@ def VCTools(self):
         ------
         list of str
             paths
+
+        When host CPU is ARM, the tools should be found for ARM.
+
+        >>> getfixture('windows_only')
+        >>> mp = getfixture('monkeypatch')
+        >>> mp.setattr(PlatformInfo, 'current_cpu', 'arm64')
+        >>> ei = EnvironmentInfo(arch='irrelevant')
+        >>> paths = ei.VCTools
+        >>> any('HostARM64' in path for path in paths)
+        True
         """
         si = self.si
-        tools = [join(si.VCInstallDir, 'VCPackages')]
+        tools = [os.path.join(si.VCInstallDir, 'VCPackages')]
 
         forcex86 = True if self.vs_ver <= 10.0 else False
         arch_subdir = self.pi.cross_dir(forcex86)
         if arch_subdir:
-            tools += [join(si.VCInstallDir, 'Bin%s' % arch_subdir)]
+            tools += [os.path.join(si.VCInstallDir, f'Bin{arch_subdir}')]
 
         if self.vs_ver == 14.0:
-            path = 'Bin%s' % self.pi.current_dir(hidex86=True)
-            tools += [join(si.VCInstallDir, path)]
+            path = f'Bin{self.pi.current_dir(hidex86=True)}'
+            tools += [os.path.join(si.VCInstallDir, path)]
 
         elif self.vs_ver >= 15.0:
-            host_dir = (
-                r'bin\HostX86%s' if self.pi.current_is_x86() else r'bin\HostX64%s'
-            )
-            tools += [join(si.VCInstallDir, host_dir % self.pi.target_dir(x64=True))]
+            host_id = self.pi.current_cpu.replace('amd64', 'x64').upper()
+            host_dir = os.path.join('bin', f'Host{host_id}%s')
+            tools += [
+                os.path.join(si.VCInstallDir, host_dir % self.pi.target_dir(x64=True))
+            ]
 
             if self.pi.current_cpu != self.pi.target_cpu:
                 tools += [
-                    join(si.VCInstallDir, host_dir % self.pi.current_dir(x64=True))
+                    os.path.join(
+                        si.VCInstallDir, host_dir % self.pi.current_dir(x64=True)
+                    )
                 ]
 
         else:
-            tools += [join(si.VCInstallDir, 'Bin')]
+            tools += [os.path.join(si.VCInstallDir, 'Bin')]
 
         return tools
 
@@ -1285,13 +1091,13 @@ def OSLibraries(self):
         """
         if self.vs_ver <= 10.0:
             arch_subdir = self.pi.target_dir(hidex86=True, x64=True)
-            return [join(self.si.WindowsSdkDir, 'Lib%s' % arch_subdir)]
+            return [os.path.join(self.si.WindowsSdkDir, f'Lib{arch_subdir}')]
 
         else:
             arch_subdir = self.pi.target_dir(x64=True)
-            lib = join(self.si.WindowsSdkDir, 'lib')
+            lib = os.path.join(self.si.WindowsSdkDir, 'lib')
             libver = self._sdk_subdir
-            return [join(lib, '%sum%s' % (libver, arch_subdir))]
+            return [os.path.join(lib, f'{libver}um{arch_subdir}')]
 
     @property
     def OSIncludes(self):
@@ -1303,10 +1109,10 @@ def OSIncludes(self):
         list of str
             paths
         """
-        include = join(self.si.WindowsSdkDir, 'include')
+        include = os.path.join(self.si.WindowsSdkDir, 'include')
 
         if self.vs_ver <= 10.0:
-            return [include, join(include, 'gl')]
+            return [include, os.path.join(include, 'gl')]
 
         else:
             if self.vs_ver >= 14.0:
@@ -1314,9 +1120,9 @@ def OSIncludes(self):
             else:
                 sdkver = ''
             return [
-                join(include, '%sshared' % sdkver),
-                join(include, '%sum' % sdkver),
-                join(include, '%swinrt' % sdkver),
+                os.path.join(include, f'{sdkver}shared'),
+                os.path.join(include, f'{sdkver}um'),
+                os.path.join(include, f'{sdkver}winrt'),
             ]
 
     @property
@@ -1329,27 +1135,29 @@ def OSLibpath(self):
         list of str
             paths
         """
-        ref = join(self.si.WindowsSdkDir, 'References')
+        ref = os.path.join(self.si.WindowsSdkDir, 'References')
         libpath = []
 
         if self.vs_ver <= 9.0:
             libpath += self.OSLibraries
 
         if self.vs_ver >= 11.0:
-            libpath += [join(ref, r'CommonConfiguration\Neutral')]
+            libpath += [os.path.join(ref, r'CommonConfiguration\Neutral')]
 
         if self.vs_ver >= 14.0:
             libpath += [
                 ref,
-                join(self.si.WindowsSdkDir, 'UnionMetadata'),
-                join(ref, 'Windows.Foundation.UniversalApiContract', '1.0.0.0'),
-                join(ref, 'Windows.Foundation.FoundationContract', '1.0.0.0'),
-                join(ref, 'Windows.Networking.Connectivity.WwanContract', '1.0.0.0'),
-                join(
+                os.path.join(self.si.WindowsSdkDir, 'UnionMetadata'),
+                os.path.join(ref, 'Windows.Foundation.UniversalApiContract', '1.0.0.0'),
+                os.path.join(ref, 'Windows.Foundation.FoundationContract', '1.0.0.0'),
+                os.path.join(
+                    ref, 'Windows.Networking.Connectivity.WwanContract', '1.0.0.0'
+                ),
+                os.path.join(
                     self.si.WindowsSdkDir,
                     'ExtensionSDKs',
                     'Microsoft.VCLibs',
-                    '%0.1f' % self.vs_ver,
+                    f'{self.vs_ver:0.1f}',
                     'References',
                     'CommonConfiguration',
                     'neutral',
@@ -1380,32 +1188,32 @@ def _sdk_tools(self):
         """
         if self.vs_ver < 15.0:
             bin_dir = 'Bin' if self.vs_ver <= 11.0 else r'Bin\x86'
-            yield join(self.si.WindowsSdkDir, bin_dir)
+            yield os.path.join(self.si.WindowsSdkDir, bin_dir)
 
         if not self.pi.current_is_x86():
             arch_subdir = self.pi.current_dir(x64=True)
-            path = 'Bin%s' % arch_subdir
-            yield join(self.si.WindowsSdkDir, path)
+            path = f'Bin{arch_subdir}'
+            yield os.path.join(self.si.WindowsSdkDir, path)
 
         if self.vs_ver in (10.0, 11.0):
             if self.pi.target_is_x86():
                 arch_subdir = ''
             else:
                 arch_subdir = self.pi.current_dir(hidex86=True, x64=True)
-            path = r'Bin\NETFX 4.0 Tools%s' % arch_subdir
-            yield join(self.si.WindowsSdkDir, path)
+            path = rf'Bin\NETFX 4.0 Tools{arch_subdir}'
+            yield os.path.join(self.si.WindowsSdkDir, path)
 
         elif self.vs_ver >= 15.0:
-            path = join(self.si.WindowsSdkDir, 'Bin')
+            path = os.path.join(self.si.WindowsSdkDir, 'Bin')
             arch_subdir = self.pi.current_dir(x64=True)
             sdkver = self.si.WindowsSdkLastVersion
-            yield join(path, '%s%s' % (sdkver, arch_subdir))
+            yield os.path.join(path, f'{sdkver}{arch_subdir}')
 
         if self.si.WindowsSDKExecutablePath:
             yield self.si.WindowsSDKExecutablePath
 
     @property
-    def _sdk_subdir(self):
+    def _sdk_subdir(self) -> str:
         """
         Microsoft Windows SDK version subdir.
 
@@ -1415,7 +1223,7 @@ def _sdk_subdir(self):
             subdir
         """
         ucrtver = self.si.WindowsSdkLastVersion
-        return ('%s\\' % ucrtver) if ucrtver else ''
+        return (f'{ucrtver}\\') if ucrtver else ''
 
     @property
     def SdkSetup(self):
@@ -1430,7 +1238,7 @@ def SdkSetup(self):
         if self.vs_ver > 9.0:
             return []
 
-        return [join(self.si.WindowsSdkDir, 'Setup')]
+        return [os.path.join(self.si.WindowsSdkDir, 'Setup')]
 
     @property
     def FxTools(self):
@@ -1454,9 +1262,13 @@ def FxTools(self):
 
         tools = []
         if include32:
-            tools += [join(si.FrameworkDir32, ver) for ver in si.FrameworkVersion32]
+            tools += [
+                os.path.join(si.FrameworkDir32, ver) for ver in si.FrameworkVersion32
+            ]
         if include64:
-            tools += [join(si.FrameworkDir64, ver) for ver in si.FrameworkVersion64]
+            tools += [
+                os.path.join(si.FrameworkDir64, ver) for ver in si.FrameworkVersion64
+            ]
         return tools
 
     @property
@@ -1473,7 +1285,7 @@ def NetFxSDKLibraries(self):
             return []
 
         arch_subdir = self.pi.target_dir(x64=True)
-        return [join(self.si.NetFxSdkDir, r'lib\um%s' % arch_subdir)]
+        return [os.path.join(self.si.NetFxSdkDir, rf'lib\um{arch_subdir}')]
 
     @property
     def NetFxSDKIncludes(self):
@@ -1488,7 +1300,7 @@ def NetFxSDKIncludes(self):
         if self.vs_ver < 14.0 or not self.si.NetFxSdkDir:
             return []
 
-        return [join(self.si.NetFxSdkDir, r'include\um')]
+        return [os.path.join(self.si.NetFxSdkDir, r'include\um')]
 
     @property
     def VsTDb(self):
@@ -1500,7 +1312,7 @@ def VsTDb(self):
         list of str
             paths
         """
-        return [join(self.si.VSInstallDir, r'VSTSDB\Deploy')]
+        return [os.path.join(self.si.VSInstallDir, r'VSTSDB\Deploy')]
 
     @property
     def MSBuild(self):
@@ -1521,12 +1333,12 @@ def MSBuild(self):
             base_path = self.si.VSInstallDir
             arch_subdir = ''
 
-        path = r'MSBuild\%0.1f\bin%s' % (self.vs_ver, arch_subdir)
-        build = [join(base_path, path)]
+        path = rf'MSBuild\{self.vs_ver:0.1f}\bin{arch_subdir}'
+        build = [os.path.join(base_path, path)]
 
         if self.vs_ver >= 15.0:
             # Add Roslyn C# & Visual Basic Compiler
-            build += [join(base_path, path, 'Roslyn')]
+            build += [os.path.join(base_path, path, 'Roslyn')]
 
         return build
 
@@ -1543,10 +1355,10 @@ def HTMLHelpWorkshop(self):
         if self.vs_ver < 11.0:
             return []
 
-        return [join(self.si.ProgramFilesx86, 'HTML Help Workshop')]
+        return [os.path.join(self.si.ProgramFilesx86, 'HTML Help Workshop')]
 
     @property
-    def UCRTLibraries(self):
+    def UCRTLibraries(self) -> list[str]:
         """
         Microsoft Universal C Runtime SDK Libraries.
 
@@ -1559,12 +1371,16 @@ def UCRTLibraries(self):
             return []
 
         arch_subdir = self.pi.target_dir(x64=True)
-        lib = join(self.si.UniversalCRTSdkDir, 'lib')
+        try:
+            lib = os.path.join(self.si.UniversalCRTSdkDir, 'lib')  # type: ignore[arg-type] # Expected TypeError
+        except TypeError as ex:
+            py310.add_note(ex, "Cannot find UniversalCRTSdkDir")
+            raise
         ucrtver = self._ucrt_subdir
-        return [join(lib, '%sucrt%s' % (ucrtver, arch_subdir))]
+        return [os.path.join(lib, f'{ucrtver}ucrt{arch_subdir}')]
 
     @property
-    def UCRTIncludes(self):
+    def UCRTIncludes(self) -> list[str]:
         """
         Microsoft Universal C Runtime SDK Include.
 
@@ -1576,11 +1392,15 @@ def UCRTIncludes(self):
         if self.vs_ver < 14.0:
             return []
 
-        include = join(self.si.UniversalCRTSdkDir, 'include')
-        return [join(include, '%sucrt' % self._ucrt_subdir)]
+        try:
+            include = os.path.join(self.si.UniversalCRTSdkDir, 'include')  # type: ignore[arg-type] # Expected TypeError
+        except TypeError as ex:
+            py310.add_note(ex, "Cannot find UniversalCRTSdkDir")
+            raise
+        return [os.path.join(include, f'{self._ucrt_subdir}ucrt')]
 
     @property
-    def _ucrt_subdir(self):
+    def _ucrt_subdir(self) -> str:
         """
         Microsoft Universal C Runtime SDK version subdir.
 
@@ -1590,7 +1410,7 @@ def _ucrt_subdir(self):
             subdir
         """
         ucrtver = self.si.UniversalCRTSdkLastVersion
-        return ('%s\\' % ucrtver) if ucrtver else ''
+        return (f'{ucrtver}\\') if ucrtver else ''
 
     @property
     def FSharp(self):
@@ -1608,43 +1428,41 @@ def FSharp(self):
         return [self.si.FSharpInstallDir]
 
     @property
-    def VCRuntimeRedist(self):
+    def VCRuntimeRedist(self) -> str | None:
         """
         Microsoft Visual C++ runtime redistributable dll.
 
-        Return
-        ------
-        str
-            path
+        Returns the first suitable path found or None.
         """
-        vcruntime = 'vcruntime%d0.dll' % self.vc_ver
+        vcruntime = f'vcruntime{self.vc_ver}0.dll'
         arch_subdir = self.pi.target_dir(x64=True).strip('\\')
 
         # Installation prefixes candidates
         prefixes = []
         tools_path = self.si.VCInstallDir
-        redist_path = dirname(tools_path.replace(r'\Tools', r'\Redist'))
-        if isdir(redist_path):
+        redist_path = os.path.dirname(tools_path.replace(r'\Tools', r'\Redist'))
+        if os.path.isdir(redist_path):
             # Redist version may not be exactly the same as tools
-            redist_path = join(redist_path, listdir(redist_path)[-1])
-            prefixes += [redist_path, join(redist_path, 'onecore')]
+            redist_path = os.path.join(redist_path, os.listdir(redist_path)[-1])
+            prefixes += [redist_path, os.path.join(redist_path, 'onecore')]
 
-        prefixes += [join(tools_path, 'redist')]  # VS14 legacy path
+        prefixes += [os.path.join(tools_path, 'redist')]  # VS14 legacy path
 
         # CRT directory
         crt_dirs = (
-            'Microsoft.VC%d.CRT' % (self.vc_ver * 10),
+            f'Microsoft.VC{self.vc_ver * 10}.CRT',
             # Sometime store in directory with VS version instead of VC
-            'Microsoft.VC%d.CRT' % (int(self.vs_ver) * 10),
+            f'Microsoft.VC{int(self.vs_ver) * 10}.CRT',
         )
 
         # vcruntime path
-        for prefix, crt_dir in itertools.product(prefixes, crt_dirs):
-            path = join(prefix, arch_subdir, crt_dir, vcruntime)
-            if isfile(path):
-                return path
+        candidate_paths = (
+            os.path.join(prefix, arch_subdir, crt_dir, vcruntime)
+            for (prefix, crt_dir) in itertools.product(prefixes, crt_dirs)
+        )
+        return next(filter(os.path.isfile, candidate_paths), None)  # type: ignore[arg-type] #python/mypy#12682
 
-    def return_env(self, exists=True):
+    def return_env(self, exists: bool = True) -> _EnvironmentDict:
         """
         Return environment dict.
 
@@ -1658,7 +1476,7 @@ def return_env(self, exists=True):
         dict
             environment
         """
-        env = dict(
+        env = _EnvironmentDict(
             include=self._build_paths(
                 'include',
                 [
@@ -1701,7 +1519,7 @@ def return_env(self, exists=True):
                 exists,
             ),
         )
-        if self.vs_ver >= 14 and isfile(self.VCRuntimeRedist):
+        if self.vs_ver >= 14 and self.VCRuntimeRedist:
             env['py_vcruntime_redist'] = self.VCRuntimeRedist
         return env
 
@@ -1729,11 +1547,11 @@ def _build_paths(self, name, spec_path_lists, exists):
         """
         # flatten spec_path_lists
         spec_paths = itertools.chain.from_iterable(spec_path_lists)
-        env_paths = environ.get(name, '').split(pathsep)
+        env_paths = environ.get(name, '').split(os.pathsep)
         paths = itertools.chain(spec_paths, env_paths)
-        extant_paths = list(filter(isdir, paths)) if exists else paths
+        extant_paths = list(filter(os.path.isdir, paths)) if exists else paths
         if not extant_paths:
-            msg = "%s environment variable is empty" % name.upper()
+            msg = f"{name.upper()} environment variable is empty"
             raise distutils.errors.DistutilsPlatformError(msg)
         unique_paths = unique_everseen(extant_paths)
-        return pathsep.join(unique_paths)
+        return os.pathsep.join(unique_paths)
diff --git a/setuptools/namespaces.py b/setuptools/namespaces.py
index 5402f120b8..7760f07fb4 100644
--- a/setuptools/namespaces.py
+++ b/setuptools/namespaces.py
@@ -1,7 +1,9 @@
-import os
-from distutils import log
 import itertools
+import os
+
+from .compat import py312
 
+from distutils import log
 
 flatten = itertools.chain.from_iterable
 
@@ -9,49 +11,47 @@
 class Installer:
     nspkg_ext = '-nspkg.pth'
 
-    def install_namespaces(self):
+    def install_namespaces(self) -> None:
         nsp = self._get_all_ns_packages()
         if not nsp:
             return
-        filename, ext = os.path.splitext(self._get_target())
-        filename += self.nspkg_ext
+        filename = self._get_nspkg_file()
         self.outputs.append(filename)
         log.info("Installing %s", filename)
         lines = map(self._gen_nspkg_line, nsp)
 
-        if self.dry_run:
-            # always generate the lines, even in dry run
-            list(lines)
-            return
-
-        with open(filename, 'wt') as f:
+        with open(filename, 'wt', encoding=py312.PTH_ENCODING) as f:
+            # Python<3.13 requires encoding="locale" instead of "utf-8"
+            # See: python/cpython#77102
             f.writelines(lines)
 
-    def uninstall_namespaces(self):
-        filename, ext = os.path.splitext(self._get_target())
-        filename += self.nspkg_ext
+    def uninstall_namespaces(self) -> None:
+        filename = self._get_nspkg_file()
         if not os.path.exists(filename):
             return
         log.info("Removing %s", filename)
         os.remove(filename)
 
+    def _get_nspkg_file(self):
+        filename, _ = os.path.splitext(self._get_target())
+        return filename + self.nspkg_ext
+
     def _get_target(self):
         return self.target
 
     _nspkg_tmpl = (
         "import sys, types, os",
-        "has_mfs = sys.version_info > (3, 5)",
         "p = os.path.join(%(root)s, *%(pth)r)",
-        "importlib = has_mfs and __import__('importlib.util')",
-        "has_mfs and __import__('importlib.machinery')",
+        "importlib = __import__('importlib.util')",
+        "__import__('importlib.machinery')",
         (
-            "m = has_mfs and "
+            "m = "
             "sys.modules.setdefault(%(pkg)r, "
             "importlib.util.module_from_spec("
             "importlib.machinery.PathFinder.find_spec(%(pkg)r, "
             "[os.path.dirname(p)])))"
         ),
-        ("m = m or " "sys.modules.setdefault(%(pkg)r, types.ModuleType(%(pkg)r))"),
+        ("m = m or sys.modules.setdefault(%(pkg)r, types.ModuleType(%(pkg)r))"),
         "mp = (m or []) and m.__dict__.setdefault('__path__',[])",
         "(p not in mp) and mp.append(p)",
     )
@@ -75,7 +75,7 @@ def _gen_nspkg_line(self, pkg):
     def _get_all_ns_packages(self):
         """Return sorted list of all package namespaces"""
         pkgs = self.distribution.namespace_packages or []
-        return sorted(flatten(map(self._pkg_names, pkgs)))
+        return sorted(set(flatten(map(self._pkg_names, pkgs))))
 
     @staticmethod
     def _pkg_names(pkg):
diff --git a/setuptools/package_index.py b/setuptools/package_index.py
deleted file mode 100644
index 7095585008..0000000000
--- a/setuptools/package_index.py
+++ /dev/null
@@ -1,1131 +0,0 @@
-"""PyPI and direct package downloading."""
-
-import sys
-import os
-import re
-import io
-import shutil
-import socket
-import base64
-import hashlib
-import itertools
-import configparser
-import html
-import http.client
-import urllib.parse
-import urllib.request
-import urllib.error
-from functools import wraps
-
-import setuptools
-from pkg_resources import (
-    CHECKOUT_DIST,
-    Distribution,
-    BINARY_DIST,
-    normalize_path,
-    SOURCE_DIST,
-    Environment,
-    find_distributions,
-    safe_name,
-    safe_version,
-    to_filename,
-    Requirement,
-    DEVELOP_DIST,
-    EGG_DIST,
-    parse_version,
-)
-from distutils import log
-from distutils.errors import DistutilsError
-from fnmatch import translate
-from setuptools.wheel import Wheel
-from setuptools.extern.more_itertools import unique_everseen
-
-
-EGG_FRAGMENT = re.compile(r'^egg=([-A-Za-z0-9_.+!]+)$')
-HREF = re.compile(r"""href\s*=\s*['"]?([^'"> ]+)""", re.I)
-PYPI_MD5 = re.compile(
-    r'([^<]+)\n\s+\(md5\)'
-)
-URL_SCHEME = re.compile('([-+.a-z0-9]{2,}):', re.I).match
-EXTENSIONS = ".tar.gz .tar.bz2 .tar .zip .tgz".split()
-
-__all__ = [
-    'PackageIndex',
-    'distros_for_url',
-    'parse_bdist_wininst',
-    'interpret_distro_name',
-]
-
-_SOCKET_TIMEOUT = 15
-
-_tmpl = "setuptools/{setuptools.__version__} Python-urllib/{py_major}"
-user_agent = _tmpl.format(
-    py_major='{}.{}'.format(*sys.version_info), setuptools=setuptools
-)
-
-
-def parse_requirement_arg(spec):
-    try:
-        return Requirement.parse(spec)
-    except ValueError as e:
-        raise DistutilsError(
-            "Not a URL, existing file, or requirement spec: %r" % (spec,)
-        ) from e
-
-
-def parse_bdist_wininst(name):
-    """Return (base,pyversion) or (None,None) for possible .exe name"""
-
-    lower = name.lower()
-    base, py_ver, plat = None, None, None
-
-    if lower.endswith('.exe'):
-        if lower.endswith('.win32.exe'):
-            base = name[:-10]
-            plat = 'win32'
-        elif lower.startswith('.win32-py', -16):
-            py_ver = name[-7:-4]
-            base = name[:-16]
-            plat = 'win32'
-        elif lower.endswith('.win-amd64.exe'):
-            base = name[:-14]
-            plat = 'win-amd64'
-        elif lower.startswith('.win-amd64-py', -20):
-            py_ver = name[-7:-4]
-            base = name[:-20]
-            plat = 'win-amd64'
-    return base, py_ver, plat
-
-
-def egg_info_for_url(url):
-    parts = urllib.parse.urlparse(url)
-    scheme, server, path, parameters, query, fragment = parts
-    base = urllib.parse.unquote(path.split('/')[-1])
-    if server == 'sourceforge.net' and base == 'download':  # XXX Yuck
-        base = urllib.parse.unquote(path.split('/')[-2])
-    if '#' in base:
-        base, fragment = base.split('#', 1)
-    return base, fragment
-
-
-def distros_for_url(url, metadata=None):
-    """Yield egg or source distribution objects that might be found at a URL"""
-    base, fragment = egg_info_for_url(url)
-    for dist in distros_for_location(url, base, metadata):
-        yield dist
-    if fragment:
-        match = EGG_FRAGMENT.match(fragment)
-        if match:
-            for dist in interpret_distro_name(
-                url, match.group(1), metadata, precedence=CHECKOUT_DIST
-            ):
-                yield dist
-
-
-def distros_for_location(location, basename, metadata=None):
-    """Yield egg or source distribution objects based on basename"""
-    if basename.endswith('.egg.zip'):
-        basename = basename[:-4]  # strip the .zip
-    if basename.endswith('.egg') and '-' in basename:
-        # only one, unambiguous interpretation
-        return [Distribution.from_location(location, basename, metadata)]
-    if basename.endswith('.whl') and '-' in basename:
-        wheel = Wheel(basename)
-        if not wheel.is_compatible():
-            return []
-        return [
-            Distribution(
-                location=location,
-                project_name=wheel.project_name,
-                version=wheel.version,
-                # Increase priority over eggs.
-                precedence=EGG_DIST + 1,
-            )
-        ]
-    if basename.endswith('.exe'):
-        win_base, py_ver, platform = parse_bdist_wininst(basename)
-        if win_base is not None:
-            return interpret_distro_name(
-                location, win_base, metadata, py_ver, BINARY_DIST, platform
-            )
-    # Try source distro extensions (.zip, .tgz, etc.)
-    #
-    for ext in EXTENSIONS:
-        if basename.endswith(ext):
-            basename = basename[: -len(ext)]
-            return interpret_distro_name(location, basename, metadata)
-    return []  # no extension matched
-
-
-def distros_for_filename(filename, metadata=None):
-    """Yield possible egg or source distribution objects based on a filename"""
-    return distros_for_location(
-        normalize_path(filename), os.path.basename(filename), metadata
-    )
-
-
-def interpret_distro_name(
-    location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None
-):
-    """Generate the interpretation of a source distro name
-
-    Note: if `location` is a filesystem filename, you should call
-    ``pkg_resources.normalize_path()`` on it before passing it to this
-    routine!
-    """
-
-    parts = basename.split('-')
-    if not py_version and any(re.match(r'py\d\.\d$', p) for p in parts[2:]):
-        # it is a bdist_dumb, not an sdist -- bail out
-        return
-
-    # find the pivot (p) that splits the name from the version.
-    # infer the version as the first item that has a digit.
-    for p in range(len(parts)):
-        if parts[p][:1].isdigit():
-            break
-    else:
-        p = len(parts)
-
-    yield Distribution(
-        location,
-        metadata,
-        '-'.join(parts[:p]),
-        '-'.join(parts[p:]),
-        py_version=py_version,
-        precedence=precedence,
-        platform=platform,
-    )
-
-
-def unique_values(func):
-    """
-    Wrap a function returning an iterable such that the resulting iterable
-    only ever yields unique items.
-    """
-
-    @wraps(func)
-    def wrapper(*args, **kwargs):
-        return unique_everseen(func(*args, **kwargs))
-
-    return wrapper
-
-
-REL = re.compile(r"""<([^>]*\srel\s{0,10}=\s{0,10}['"]?([^'" >]+)[^>]*)>""", re.I)
-"""
-Regex for an HTML tag with 'rel="val"' attributes.
-"""
-
-
-@unique_values
-def find_external_links(url, page):
-    """Find rel="homepage" and rel="download" links in `page`, yielding URLs"""
-
-    for match in REL.finditer(page):
-        tag, rel = match.groups()
-        rels = set(map(str.strip, rel.lower().split(',')))
-        if 'homepage' in rels or 'download' in rels:
-            for match in HREF.finditer(tag):
-                yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
-
-    for tag in ("Home Page", "Download URL"):
-        pos = page.find(tag)
-        if pos != -1:
-            match = HREF.search(page, pos)
-            if match:
-                yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
-
-
-class ContentChecker:
-    """
-    A null content checker that defines the interface for checking content
-    """
-
-    def feed(self, block):
-        """
-        Feed a block of data to the hash.
-        """
-        return
-
-    def is_valid(self):
-        """
-        Check the hash. Return False if validation fails.
-        """
-        return True
-
-    def report(self, reporter, template):
-        """
-        Call reporter with information about the checker (hash name)
-        substituted into the template.
-        """
-        return
-
-
-class HashChecker(ContentChecker):
-    pattern = re.compile(
-        r'(?Psha1|sha224|sha384|sha256|sha512|md5)='
-        r'(?P[a-f0-9]+)'
-    )
-
-    def __init__(self, hash_name, expected):
-        self.hash_name = hash_name
-        self.hash = hashlib.new(hash_name)
-        self.expected = expected
-
-    @classmethod
-    def from_url(cls, url):
-        "Construct a (possibly null) ContentChecker from a URL"
-        fragment = urllib.parse.urlparse(url)[-1]
-        if not fragment:
-            return ContentChecker()
-        match = cls.pattern.search(fragment)
-        if not match:
-            return ContentChecker()
-        return cls(**match.groupdict())
-
-    def feed(self, block):
-        self.hash.update(block)
-
-    def is_valid(self):
-        return self.hash.hexdigest() == self.expected
-
-    def report(self, reporter, template):
-        msg = template % self.hash_name
-        return reporter(msg)
-
-
-class PackageIndex(Environment):
-    """A distribution index that scans web pages for download URLs"""
-
-    def __init__(
-        self,
-        index_url="https://pypi.org/simple/",
-        hosts=('*',),
-        ca_bundle=None,
-        verify_ssl=True,
-        *args,
-        **kw,
-    ):
-        super().__init__(*args, **kw)
-        self.index_url = index_url + "/"[: not index_url.endswith('/')]
-        self.scanned_urls = {}
-        self.fetched_urls = {}
-        self.package_pages = {}
-        self.allows = re.compile('|'.join(map(translate, hosts))).match
-        self.to_scan = []
-        self.opener = urllib.request.urlopen
-
-    def add(self, dist):
-        # ignore invalid versions
-        try:
-            parse_version(dist.version)
-        except Exception:
-            return
-        return super().add(dist)
-
-    # FIXME: 'PackageIndex.process_url' is too complex (14)
-    def process_url(self, url, retrieve=False):  # noqa: C901
-        """Evaluate a URL as a possible download, and maybe retrieve it"""
-        if url in self.scanned_urls and not retrieve:
-            return
-        self.scanned_urls[url] = True
-        if not URL_SCHEME(url):
-            self.process_filename(url)
-            return
-        else:
-            dists = list(distros_for_url(url))
-            if dists:
-                if not self.url_ok(url):
-                    return
-                self.debug("Found link: %s", url)
-
-        if dists or not retrieve or url in self.fetched_urls:
-            list(map(self.add, dists))
-            return  # don't need the actual page
-
-        if not self.url_ok(url):
-            self.fetched_urls[url] = True
-            return
-
-        self.info("Reading %s", url)
-        self.fetched_urls[url] = True  # prevent multiple fetch attempts
-        tmpl = "Download error on %s: %%s -- Some packages may not be found!"
-        f = self.open_url(url, tmpl % url)
-        if f is None:
-            return
-        if isinstance(f, urllib.error.HTTPError) and f.code == 401:
-            self.info("Authentication error: %s" % f.msg)
-        self.fetched_urls[f.url] = True
-        if 'html' not in f.headers.get('content-type', '').lower():
-            f.close()  # not html, we can't process it
-            return
-
-        base = f.url  # handle redirects
-        page = f.read()
-        if not isinstance(page, str):
-            # In Python 3 and got bytes but want str.
-            if isinstance(f, urllib.error.HTTPError):
-                # Errors have no charset, assume latin1:
-                charset = 'latin-1'
-            else:
-                charset = f.headers.get_param('charset') or 'latin-1'
-            page = page.decode(charset, "ignore")
-        f.close()
-        for match in HREF.finditer(page):
-            link = urllib.parse.urljoin(base, htmldecode(match.group(1)))
-            self.process_url(link)
-        if url.startswith(self.index_url) and getattr(f, 'code', None) != 404:
-            page = self.process_index(url, page)
-
-    def process_filename(self, fn, nested=False):
-        # process filenames or directories
-        if not os.path.exists(fn):
-            self.warn("Not found: %s", fn)
-            return
-
-        if os.path.isdir(fn) and not nested:
-            path = os.path.realpath(fn)
-            for item in os.listdir(path):
-                self.process_filename(os.path.join(path, item), True)
-
-        dists = distros_for_filename(fn)
-        if dists:
-            self.debug("Found: %s", fn)
-            list(map(self.add, dists))
-
-    def url_ok(self, url, fatal=False):
-        s = URL_SCHEME(url)
-        is_file = s and s.group(1).lower() == 'file'
-        if is_file or self.allows(urllib.parse.urlparse(url)[1]):
-            return True
-        msg = (
-            "\nNote: Bypassing %s (disallowed host; see "
-            "https://setuptools.pypa.io/en/latest/deprecated/"
-            "easy_install.html#restricting-downloads-with-allow-hosts for details).\n"
-        )
-        if fatal:
-            raise DistutilsError(msg % url)
-        else:
-            self.warn(msg, url)
-
-    def scan_egg_links(self, search_path):
-        dirs = filter(os.path.isdir, search_path)
-        egg_links = (
-            (path, entry)
-            for path in dirs
-            for entry in os.listdir(path)
-            if entry.endswith('.egg-link')
-        )
-        list(itertools.starmap(self.scan_egg_link, egg_links))
-
-    def scan_egg_link(self, path, entry):
-        with open(os.path.join(path, entry)) as raw_lines:
-            # filter non-empty lines
-            lines = list(filter(None, map(str.strip, raw_lines)))
-
-        if len(lines) != 2:
-            # format is not recognized; punt
-            return
-
-        egg_path, setup_path = lines
-
-        for dist in find_distributions(os.path.join(path, egg_path)):
-            dist.location = os.path.join(path, *lines)
-            dist.precedence = SOURCE_DIST
-            self.add(dist)
-
-    def _scan(self, link):
-        # Process a URL to see if it's for a package page
-        NO_MATCH_SENTINEL = None, None
-        if not link.startswith(self.index_url):
-            return NO_MATCH_SENTINEL
-
-        parts = list(map(urllib.parse.unquote, link[len(self.index_url) :].split('/')))
-        if len(parts) != 2 or '#' in parts[1]:
-            return NO_MATCH_SENTINEL
-
-        # it's a package page, sanitize and index it
-        pkg = safe_name(parts[0])
-        ver = safe_version(parts[1])
-        self.package_pages.setdefault(pkg.lower(), {})[link] = True
-        return to_filename(pkg), to_filename(ver)
-
-    def process_index(self, url, page):
-        """Process the contents of a PyPI page"""
-
-        # process an index page into the package-page index
-        for match in HREF.finditer(page):
-            try:
-                self._scan(urllib.parse.urljoin(url, htmldecode(match.group(1))))
-            except ValueError:
-                pass
-
-        pkg, ver = self._scan(url)  # ensure this page is in the page index
-        if not pkg:
-            return ""  # no sense double-scanning non-package pages
-
-        # process individual package page
-        for new_url in find_external_links(url, page):
-            # Process the found URL
-            base, frag = egg_info_for_url(new_url)
-            if base.endswith('.py') and not frag:
-                if ver:
-                    new_url += '#egg=%s-%s' % (pkg, ver)
-                else:
-                    self.need_version_info(url)
-            self.scan_url(new_url)
-
-        return PYPI_MD5.sub(
-            lambda m: '%s' % m.group(1, 3, 2), page
-        )
-
-    def need_version_info(self, url):
-        self.scan_all(
-            "Page at %s links to .py file(s) without version info; an index "
-            "scan is required.",
-            url,
-        )
-
-    def scan_all(self, msg=None, *args):
-        if self.index_url not in self.fetched_urls:
-            if msg:
-                self.warn(msg, *args)
-            self.info("Scanning index of all packages (this may take a while)")
-        self.scan_url(self.index_url)
-
-    def find_packages(self, requirement):
-        self.scan_url(self.index_url + requirement.unsafe_name + '/')
-
-        if not self.package_pages.get(requirement.key):
-            # Fall back to safe version of the name
-            self.scan_url(self.index_url + requirement.project_name + '/')
-
-        if not self.package_pages.get(requirement.key):
-            # We couldn't find the target package, so search the index page too
-            self.not_found_in_index(requirement)
-
-        for url in list(self.package_pages.get(requirement.key, ())):
-            # scan each page that might be related to the desired package
-            self.scan_url(url)
-
-    def obtain(self, requirement, installer=None):
-        self.prescan()
-        self.find_packages(requirement)
-        for dist in self[requirement.key]:
-            if dist in requirement:
-                return dist
-            self.debug("%s does not match %s", requirement, dist)
-        return super(PackageIndex, self).obtain(requirement, installer)
-
-    def check_hash(self, checker, filename, tfp):
-        """
-        checker is a ContentChecker
-        """
-        checker.report(self.debug, "Validating %%s checksum for %s" % filename)
-        if not checker.is_valid():
-            tfp.close()
-            os.unlink(filename)
-            raise DistutilsError(
-                "%s validation failed for %s; "
-                "possible download problem?"
-                % (checker.hash.name, os.path.basename(filename))
-            )
-
-    def add_find_links(self, urls):
-        """Add `urls` to the list that will be prescanned for searches"""
-        for url in urls:
-            if (
-                self.to_scan is None  # if we have already "gone online"
-                or not URL_SCHEME(url)  # or it's a local file/directory
-                or url.startswith('file:')
-                or list(distros_for_url(url))  # or a direct package link
-            ):
-                # then go ahead and process it now
-                self.scan_url(url)
-            else:
-                # otherwise, defer retrieval till later
-                self.to_scan.append(url)
-
-    def prescan(self):
-        """Scan urls scheduled for prescanning (e.g. --find-links)"""
-        if self.to_scan:
-            list(map(self.scan_url, self.to_scan))
-        self.to_scan = None  # from now on, go ahead and process immediately
-
-    def not_found_in_index(self, requirement):
-        if self[requirement.key]:  # we've seen at least one distro
-            meth, msg = self.info, "Couldn't retrieve index page for %r"
-        else:  # no distros seen for this name, might be misspelled
-            meth, msg = (
-                self.warn,
-                "Couldn't find index page for %r (maybe misspelled?)",
-            )
-        meth(msg, requirement.unsafe_name)
-        self.scan_all()
-
-    def download(self, spec, tmpdir):
-        """Locate and/or download `spec` to `tmpdir`, returning a local path
-
-        `spec` may be a ``Requirement`` object, or a string containing a URL,
-        an existing local filename, or a project/version requirement spec
-        (i.e. the string form of a ``Requirement`` object).  If it is the URL
-        of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one
-        that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is
-        automatically created alongside the downloaded file.
-
-        If `spec` is a ``Requirement`` object or a string containing a
-        project/version requirement spec, this method returns the location of
-        a matching distribution (possibly after downloading it to `tmpdir`).
-        If `spec` is a locally existing file or directory name, it is simply
-        returned unchanged.  If `spec` is a URL, it is downloaded to a subpath
-        of `tmpdir`, and the local filename is returned.  Various errors may be
-        raised if a problem occurs during downloading.
-        """
-        if not isinstance(spec, Requirement):
-            scheme = URL_SCHEME(spec)
-            if scheme:
-                # It's a url, download it to tmpdir
-                found = self._download_url(scheme.group(1), spec, tmpdir)
-                base, fragment = egg_info_for_url(spec)
-                if base.endswith('.py'):
-                    found = self.gen_setup(found, fragment, tmpdir)
-                return found
-            elif os.path.exists(spec):
-                # Existing file or directory, just return it
-                return spec
-            else:
-                spec = parse_requirement_arg(spec)
-        return getattr(self.fetch_distribution(spec, tmpdir), 'location', None)
-
-    def fetch_distribution(  # noqa: C901  # is too complex (14)  # FIXME
-        self,
-        requirement,
-        tmpdir,
-        force_scan=False,
-        source=False,
-        develop_ok=False,
-        local_index=None,
-    ):
-        """Obtain a distribution suitable for fulfilling `requirement`
-
-        `requirement` must be a ``pkg_resources.Requirement`` instance.
-        If necessary, or if the `force_scan` flag is set, the requirement is
-        searched for in the (online) package index as well as the locally
-        installed packages.  If a distribution matching `requirement` is found,
-        the returned distribution's ``location`` is the value you would have
-        gotten from calling the ``download()`` method with the matching
-        distribution's URL or filename.  If no matching distribution is found,
-        ``None`` is returned.
-
-        If the `source` flag is set, only source distributions and source
-        checkout links will be considered.  Unless the `develop_ok` flag is
-        set, development and system eggs (i.e., those using the ``.egg-info``
-        format) will be ignored.
-        """
-        # process a Requirement
-        self.info("Searching for %s", requirement)
-        skipped = {}
-        dist = None
-
-        def find(req, env=None):
-            if env is None:
-                env = self
-            # Find a matching distribution; may be called more than once
-
-            for dist in env[req.key]:
-                if dist.precedence == DEVELOP_DIST and not develop_ok:
-                    if dist not in skipped:
-                        self.warn(
-                            "Skipping development or system egg: %s",
-                            dist,
-                        )
-                        skipped[dist] = 1
-                    continue
-
-                test = dist in req and (dist.precedence <= SOURCE_DIST or not source)
-                if test:
-                    loc = self.download(dist.location, tmpdir)
-                    dist.download_location = loc
-                    if os.path.exists(dist.download_location):
-                        return dist
-
-        if force_scan:
-            self.prescan()
-            self.find_packages(requirement)
-            dist = find(requirement)
-
-        if not dist and local_index is not None:
-            dist = find(requirement, local_index)
-
-        if dist is None:
-            if self.to_scan is not None:
-                self.prescan()
-            dist = find(requirement)
-
-        if dist is None and not force_scan:
-            self.find_packages(requirement)
-            dist = find(requirement)
-
-        if dist is None:
-            self.warn(
-                "No local packages or working download links found for %s%s",
-                (source and "a source distribution of " or ""),
-                requirement,
-            )
-        else:
-            self.info("Best match: %s", dist)
-            return dist.clone(location=dist.download_location)
-
-    def fetch(self, requirement, tmpdir, force_scan=False, source=False):
-        """Obtain a file suitable for fulfilling `requirement`
-
-        DEPRECATED; use the ``fetch_distribution()`` method now instead.  For
-        backward compatibility, this routine is identical but returns the
-        ``location`` of the downloaded distribution instead of a distribution
-        object.
-        """
-        dist = self.fetch_distribution(requirement, tmpdir, force_scan, source)
-        if dist is not None:
-            return dist.location
-        return None
-
-    def gen_setup(self, filename, fragment, tmpdir):
-        match = EGG_FRAGMENT.match(fragment)
-        dists = (
-            match
-            and [
-                d
-                for d in interpret_distro_name(filename, match.group(1), None)
-                if d.version
-            ]
-            or []
-        )
-
-        if len(dists) == 1:  # unambiguous ``#egg`` fragment
-            basename = os.path.basename(filename)
-
-            # Make sure the file has been downloaded to the temp dir.
-            if os.path.dirname(filename) != tmpdir:
-                dst = os.path.join(tmpdir, basename)
-                if not (os.path.exists(dst) and os.path.samefile(filename, dst)):
-                    shutil.copy2(filename, dst)
-                    filename = dst
-
-            with open(os.path.join(tmpdir, 'setup.py'), 'w') as file:
-                file.write(
-                    "from setuptools import setup\n"
-                    "setup(name=%r, version=%r, py_modules=[%r])\n"
-                    % (
-                        dists[0].project_name,
-                        dists[0].version,
-                        os.path.splitext(basename)[0],
-                    )
-                )
-            return filename
-
-        elif match:
-            raise DistutilsError(
-                "Can't unambiguously interpret project/version identifier %r; "
-                "any dashes in the name or version should be escaped using "
-                "underscores. %r" % (fragment, dists)
-            )
-        else:
-            raise DistutilsError(
-                "Can't process plain .py files without an '#egg=name-version'"
-                " suffix to enable automatic setup script generation."
-            )
-
-    dl_blocksize = 8192
-
-    def _download_to(self, url, filename):
-        self.info("Downloading %s", url)
-        # Download the file
-        fp = None
-        try:
-            checker = HashChecker.from_url(url)
-            fp = self.open_url(url)
-            if isinstance(fp, urllib.error.HTTPError):
-                raise DistutilsError(
-                    "Can't download %s: %s %s" % (url, fp.code, fp.msg)
-                )
-            headers = fp.info()
-            blocknum = 0
-            bs = self.dl_blocksize
-            size = -1
-            if "content-length" in headers:
-                # Some servers return multiple Content-Length headers :(
-                sizes = headers.get_all('Content-Length')
-                size = max(map(int, sizes))
-                self.reporthook(url, filename, blocknum, bs, size)
-            with open(filename, 'wb') as tfp:
-                while True:
-                    block = fp.read(bs)
-                    if block:
-                        checker.feed(block)
-                        tfp.write(block)
-                        blocknum += 1
-                        self.reporthook(url, filename, blocknum, bs, size)
-                    else:
-                        break
-                self.check_hash(checker, filename, tfp)
-            return headers
-        finally:
-            if fp:
-                fp.close()
-
-    def reporthook(self, url, filename, blocknum, blksize, size):
-        pass  # no-op
-
-    # FIXME:
-    def open_url(self, url, warning=None):  # noqa: C901  # is too complex (12)
-        if url.startswith('file:'):
-            return local_open(url)
-        try:
-            return open_with_auth(url, self.opener)
-        except (ValueError, http.client.InvalidURL) as v:
-            msg = ' '.join([str(arg) for arg in v.args])
-            if warning:
-                self.warn(warning, msg)
-            else:
-                raise DistutilsError('%s %s' % (url, msg)) from v
-        except urllib.error.HTTPError as v:
-            return v
-        except urllib.error.URLError as v:
-            if warning:
-                self.warn(warning, v.reason)
-            else:
-                raise DistutilsError(
-                    "Download error for %s: %s" % (url, v.reason)
-                ) from v
-        except http.client.BadStatusLine as v:
-            if warning:
-                self.warn(warning, v.line)
-            else:
-                raise DistutilsError(
-                    '%s returned a bad status line. The server might be '
-                    'down, %s' % (url, v.line)
-                ) from v
-        except (http.client.HTTPException, socket.error) as v:
-            if warning:
-                self.warn(warning, v)
-            else:
-                raise DistutilsError("Download error for %s: %s" % (url, v)) from v
-
-    def _download_url(self, scheme, url, tmpdir):
-        # Determine download filename
-        #
-        name, fragment = egg_info_for_url(url)
-        if name:
-            while '..' in name:
-                name = name.replace('..', '.').replace('\\', '_')
-        else:
-            name = "__downloaded__"  # default if URL has no path contents
-
-        if name.endswith('.egg.zip'):
-            name = name[:-4]  # strip the extra .zip before download
-
-        filename = os.path.join(tmpdir, name)
-
-        # Download the file
-        #
-        if scheme == 'svn' or scheme.startswith('svn+'):
-            return self._download_svn(url, filename)
-        elif scheme == 'git' or scheme.startswith('git+'):
-            return self._download_git(url, filename)
-        elif scheme.startswith('hg+'):
-            return self._download_hg(url, filename)
-        elif scheme == 'file':
-            return urllib.request.url2pathname(urllib.parse.urlparse(url)[2])
-        else:
-            self.url_ok(url, True)  # raises error if not allowed
-            return self._attempt_download(url, filename)
-
-    def scan_url(self, url):
-        self.process_url(url, True)
-
-    def _attempt_download(self, url, filename):
-        headers = self._download_to(url, filename)
-        if 'html' in headers.get('content-type', '').lower():
-            return self._invalid_download_html(url, headers, filename)
-        else:
-            return filename
-
-    def _invalid_download_html(self, url, headers, filename):
-        os.unlink(filename)
-        raise DistutilsError(f"Unexpected HTML page found at {url}")
-
-    def _download_svn(self, url, _filename):
-        raise DistutilsError(f"Invalid config, SVN download is not supported: {url}")
-
-    @staticmethod
-    def _vcs_split_rev_from_url(url, pop_prefix=False):
-        scheme, netloc, path, query, frag = urllib.parse.urlsplit(url)
-
-        scheme = scheme.split('+', 1)[-1]
-
-        # Some fragment identification fails
-        path = path.split('#', 1)[0]
-
-        rev = None
-        if '@' in path:
-            path, rev = path.rsplit('@', 1)
-
-        # Also, discard fragment
-        url = urllib.parse.urlunsplit((scheme, netloc, path, query, ''))
-
-        return url, rev
-
-    def _download_git(self, url, filename):
-        filename = filename.split('#', 1)[0]
-        url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
-
-        self.info("Doing git clone from %s to %s", url, filename)
-        os.system("git clone --quiet %s %s" % (url, filename))
-
-        if rev is not None:
-            self.info("Checking out %s", rev)
-            os.system(
-                "git -C %s checkout --quiet %s"
-                % (
-                    filename,
-                    rev,
-                )
-            )
-
-        return filename
-
-    def _download_hg(self, url, filename):
-        filename = filename.split('#', 1)[0]
-        url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
-
-        self.info("Doing hg clone from %s to %s", url, filename)
-        os.system("hg clone --quiet %s %s" % (url, filename))
-
-        if rev is not None:
-            self.info("Updating to %s", rev)
-            os.system(
-                "hg --cwd %s up -C -r %s -q"
-                % (
-                    filename,
-                    rev,
-                )
-            )
-
-        return filename
-
-    def debug(self, msg, *args):
-        log.debug(msg, *args)
-
-    def info(self, msg, *args):
-        log.info(msg, *args)
-
-    def warn(self, msg, *args):
-        log.warn(msg, *args)
-
-
-# This pattern matches a character entity reference (a decimal numeric
-# references, a hexadecimal numeric reference, or a named reference).
-entity_sub = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?').sub
-
-
-def decode_entity(match):
-    what = match.group(0)
-    return html.unescape(what)
-
-
-def htmldecode(text):
-    """
-    Decode HTML entities in the given text.
-
-    >>> htmldecode(
-    ...     'https://../package_name-0.1.2.tar.gz'
-    ...     '?tokena=A&tokenb=B">package_name-0.1.2.tar.gz')
-    'https://../package_name-0.1.2.tar.gz?tokena=A&tokenb=B">package_name-0.1.2.tar.gz'
-    """
-    return entity_sub(decode_entity, text)
-
-
-def socket_timeout(timeout=15):
-    def _socket_timeout(func):
-        def _socket_timeout(*args, **kwargs):
-            old_timeout = socket.getdefaulttimeout()
-            socket.setdefaulttimeout(timeout)
-            try:
-                return func(*args, **kwargs)
-            finally:
-                socket.setdefaulttimeout(old_timeout)
-
-        return _socket_timeout
-
-    return _socket_timeout
-
-
-def _encode_auth(auth):
-    """
-    Encode auth from a URL suitable for an HTTP header.
-    >>> str(_encode_auth('username%3Apassword'))
-    'dXNlcm5hbWU6cGFzc3dvcmQ='
-
-    Long auth strings should not cause a newline to be inserted.
-    >>> long_auth = 'username:' + 'password'*10
-    >>> chr(10) in str(_encode_auth(long_auth))
-    False
-    """
-    auth_s = urllib.parse.unquote(auth)
-    # convert to bytes
-    auth_bytes = auth_s.encode()
-    encoded_bytes = base64.b64encode(auth_bytes)
-    # convert back to a string
-    encoded = encoded_bytes.decode()
-    # strip the trailing carriage return
-    return encoded.replace('\n', '')
-
-
-class Credential:
-    """
-    A username/password pair. Use like a namedtuple.
-    """
-
-    def __init__(self, username, password):
-        self.username = username
-        self.password = password
-
-    def __iter__(self):
-        yield self.username
-        yield self.password
-
-    def __str__(self):
-        return '%(username)s:%(password)s' % vars(self)
-
-
-class PyPIConfig(configparser.RawConfigParser):
-    def __init__(self):
-        """
-        Load from ~/.pypirc
-        """
-        defaults = dict.fromkeys(['username', 'password', 'repository'], '')
-        super().__init__(defaults)
-
-        rc = os.path.join(os.path.expanduser('~'), '.pypirc')
-        if os.path.exists(rc):
-            self.read(rc)
-
-    @property
-    def creds_by_repository(self):
-        sections_with_repositories = [
-            section
-            for section in self.sections()
-            if self.get(section, 'repository').strip()
-        ]
-
-        return dict(map(self._get_repo_cred, sections_with_repositories))
-
-    def _get_repo_cred(self, section):
-        repo = self.get(section, 'repository').strip()
-        return repo, Credential(
-            self.get(section, 'username').strip(),
-            self.get(section, 'password').strip(),
-        )
-
-    def find_credential(self, url):
-        """
-        If the URL indicated appears to be a repository defined in this
-        config, return the credential for that repository.
-        """
-        for repository, cred in self.creds_by_repository.items():
-            if url.startswith(repository):
-                return cred
-
-
-def open_with_auth(url, opener=urllib.request.urlopen):
-    """Open a urllib2 request, handling HTTP authentication"""
-
-    parsed = urllib.parse.urlparse(url)
-    scheme, netloc, path, params, query, frag = parsed
-
-    # Double scheme does not raise on macOS as revealed by a
-    # failing test. We would expect "nonnumeric port". Refs #20.
-    if netloc.endswith(':'):
-        raise http.client.InvalidURL("nonnumeric port: ''")
-
-    if scheme in ('http', 'https'):
-        auth, address = _splituser(netloc)
-    else:
-        auth = None
-
-    if not auth:
-        cred = PyPIConfig().find_credential(url)
-        if cred:
-            auth = str(cred)
-            info = cred.username, url
-            log.info('Authenticating as %s for %s (from .pypirc)', *info)
-
-    if auth:
-        auth = "Basic " + _encode_auth(auth)
-        parts = scheme, address, path, params, query, frag
-        new_url = urllib.parse.urlunparse(parts)
-        request = urllib.request.Request(new_url)
-        request.add_header("Authorization", auth)
-    else:
-        request = urllib.request.Request(url)
-
-    request.add_header('User-Agent', user_agent)
-    fp = opener(request)
-
-    if auth:
-        # Put authentication info back into request URL if same host,
-        # so that links found on the page will work
-        s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url)
-        if s2 == scheme and h2 == address:
-            parts = s2, netloc, path2, param2, query2, frag2
-            fp.url = urllib.parse.urlunparse(parts)
-
-    return fp
-
-
-# copy of urllib.parse._splituser from Python 3.8
-def _splituser(host):
-    """splituser('user[:passwd]@host[:port]')
-    --> 'user[:passwd]', 'host[:port]'."""
-    user, delim, host = host.rpartition('@')
-    return (user if delim else None), host
-
-
-# adding a timeout to avoid freezing package_index
-open_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth)
-
-
-def fix_sf_url(url):
-    return url  # backward compatibility
-
-
-def local_open(url):
-    """Read a local path, with special support for directories"""
-    scheme, server, path, param, query, frag = urllib.parse.urlparse(url)
-    filename = urllib.request.url2pathname(path)
-    if os.path.isfile(filename):
-        return urllib.request.urlopen(url)
-    elif path.endswith('/') and os.path.isdir(filename):
-        files = []
-        for f in os.listdir(filename):
-            filepath = os.path.join(filename, f)
-            if f == 'index.html':
-                with open(filepath, 'r') as fp:
-                    body = fp.read()
-                break
-            elif os.path.isdir(filepath):
-                f += '/'
-            files.append('{name}'.format(name=f))
-        else:
-            tmpl = (
-                "{url}" "{files}"
-            )
-            body = tmpl.format(url=url, files='\n'.join(files))
-        status, message = 200, "OK"
-    else:
-        status, message, body = 404, "Path not found", "Not found"
-
-    headers = {'content-type': 'text/html'}
-    body_stream = io.StringIO(body)
-    return urllib.error.HTTPError(url, status, message, headers, body_stream)
diff --git a/setuptools/py312compat.py b/setuptools/py312compat.py
deleted file mode 100644
index 28175b1f75..0000000000
--- a/setuptools/py312compat.py
+++ /dev/null
@@ -1,12 +0,0 @@
-import sys
-import shutil
-
-
-def shutil_rmtree(path, ignore_errors=False, onexc=None):
-    if sys.version_info >= (3, 12):
-        return shutil.rmtree(path, ignore_errors, onexc=onexc)
-
-    def _handler(fn, path, excinfo):
-        return onexc(fn, path, excinfo[1])
-
-    return shutil.rmtree(path, ignore_errors, onerror=_handler)
diff --git a/setuptools/sandbox.py b/setuptools/sandbox.py
deleted file mode 100644
index 017c897b86..0000000000
--- a/setuptools/sandbox.py
+++ /dev/null
@@ -1,530 +0,0 @@
-import os
-import sys
-import tempfile
-import operator
-import functools
-import itertools
-import re
-import contextlib
-import pickle
-import textwrap
-import builtins
-
-import pkg_resources
-from distutils.errors import DistutilsError
-from pkg_resources import working_set
-
-if sys.platform.startswith('java'):
-    import org.python.modules.posix.PosixModule as _os
-else:
-    _os = sys.modules[os.name]
-try:
-    _file = file
-except NameError:
-    _file = None
-_open = open
-
-
-__all__ = [
-    "AbstractSandbox",
-    "DirectorySandbox",
-    "SandboxViolation",
-    "run_setup",
-]
-
-
-def _execfile(filename, globals, locals=None):
-    """
-    Python 3 implementation of execfile.
-    """
-    mode = 'rb'
-    with open(filename, mode) as stream:
-        script = stream.read()
-    if locals is None:
-        locals = globals
-    code = compile(script, filename, 'exec')
-    exec(code, globals, locals)
-
-
-@contextlib.contextmanager
-def save_argv(repl=None):
-    saved = sys.argv[:]
-    if repl is not None:
-        sys.argv[:] = repl
-    try:
-        yield saved
-    finally:
-        sys.argv[:] = saved
-
-
-@contextlib.contextmanager
-def save_path():
-    saved = sys.path[:]
-    try:
-        yield saved
-    finally:
-        sys.path[:] = saved
-
-
-@contextlib.contextmanager
-def override_temp(replacement):
-    """
-    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
-    """
-    os.makedirs(replacement, exist_ok=True)
-
-    saved = tempfile.tempdir
-
-    tempfile.tempdir = replacement
-
-    try:
-        yield
-    finally:
-        tempfile.tempdir = saved
-
-
-@contextlib.contextmanager
-def pushd(target):
-    saved = os.getcwd()
-    os.chdir(target)
-    try:
-        yield saved
-    finally:
-        os.chdir(saved)
-
-
-class UnpickleableException(Exception):
-    """
-    An exception representing another Exception that could not be pickled.
-    """
-
-    @staticmethod
-    def dump(type, exc):
-        """
-        Always return a dumped (pickled) type and exc. If exc can't be pickled,
-        wrap it in UnpickleableException first.
-        """
-        try:
-            return pickle.dumps(type), pickle.dumps(exc)
-        except Exception:
-            # get UnpickleableException inside the sandbox
-            from setuptools.sandbox import UnpickleableException as cls
-
-            return cls.dump(cls, cls(repr(exc)))
-
-
-class ExceptionSaver:
-    """
-    A Context Manager that will save an exception, serialized, and restore it
-    later.
-    """
-
-    def __enter__(self):
-        return self
-
-    def __exit__(self, type, exc, tb):
-        if not exc:
-            return
-
-        # dump the exception
-        self._saved = UnpickleableException.dump(type, exc)
-        self._tb = tb
-
-        # suppress the exception
-        return True
-
-    def resume(self):
-        "restore and re-raise any exception"
-
-        if '_saved' not in vars(self):
-            return
-
-        type, exc = map(pickle.loads, self._saved)
-        raise exc.with_traceback(self._tb)
-
-
-@contextlib.contextmanager
-def save_modules():
-    """
-    Context in which imported modules are saved.
-
-    Translates exceptions internal to the context into the equivalent exception
-    outside the context.
-    """
-    saved = sys.modules.copy()
-    with ExceptionSaver() as saved_exc:
-        yield saved
-
-    sys.modules.update(saved)
-    # remove any modules imported since
-    del_modules = (
-        mod_name
-        for mod_name in sys.modules
-        if mod_name not in saved
-        # exclude any encodings modules. See #285
-        and not mod_name.startswith('encodings.')
-    )
-    _clear_modules(del_modules)
-
-    saved_exc.resume()
-
-
-def _clear_modules(module_names):
-    for mod_name in list(module_names):
-        del sys.modules[mod_name]
-
-
-@contextlib.contextmanager
-def save_pkg_resources_state():
-    saved = pkg_resources.__getstate__()
-    try:
-        yield saved
-    finally:
-        pkg_resources.__setstate__(saved)
-
-
-@contextlib.contextmanager
-def setup_context(setup_dir):
-    temp_dir = os.path.join(setup_dir, 'temp')
-    with save_pkg_resources_state():
-        with save_modules():
-            with save_path():
-                hide_setuptools()
-                with save_argv():
-                    with override_temp(temp_dir):
-                        with pushd(setup_dir):
-                            # ensure setuptools commands are available
-                            __import__('setuptools')
-                            yield
-
-
-_MODULES_TO_HIDE = {
-    'setuptools',
-    'distutils',
-    'pkg_resources',
-    'Cython',
-    '_distutils_hack',
-}
-
-
-def _needs_hiding(mod_name):
-    """
-    >>> _needs_hiding('setuptools')
-    True
-    >>> _needs_hiding('pkg_resources')
-    True
-    >>> _needs_hiding('setuptools_plugin')
-    False
-    >>> _needs_hiding('setuptools.__init__')
-    True
-    >>> _needs_hiding('distutils')
-    True
-    >>> _needs_hiding('os')
-    False
-    >>> _needs_hiding('Cython')
-    True
-    """
-    base_module = mod_name.split('.', 1)[0]
-    return base_module in _MODULES_TO_HIDE
-
-
-def hide_setuptools():
-    """
-    Remove references to setuptools' modules from sys.modules to allow the
-    invocation to import the most appropriate setuptools. This technique is
-    necessary to avoid issues such as #315 where setuptools upgrading itself
-    would fail to find a function declared in the metadata.
-    """
-    _distutils_hack = sys.modules.get('_distutils_hack', None)
-    if _distutils_hack is not None:
-        _distutils_hack._remove_shim()
-
-    modules = filter(_needs_hiding, sys.modules)
-    _clear_modules(modules)
-
-
-def run_setup(setup_script, args):
-    """Run a distutils setup script, sandboxed in its directory"""
-    setup_dir = os.path.abspath(os.path.dirname(setup_script))
-    with setup_context(setup_dir):
-        try:
-            sys.argv[:] = [setup_script] + list(args)
-            sys.path.insert(0, setup_dir)
-            # reset to include setup dir, w/clean callback list
-            working_set.__init__()
-            working_set.callbacks.append(lambda dist: dist.activate())
-
-            with DirectorySandbox(setup_dir):
-                ns = dict(__file__=setup_script, __name__='__main__')
-                _execfile(setup_script, ns)
-        except SystemExit as v:
-            if v.args and v.args[0]:
-                raise
-            # Normal exit, just return
-
-
-class AbstractSandbox:
-    """Wrap 'os' module and 'open()' builtin for virtualizing setup scripts"""
-
-    _active = False
-
-    def __init__(self):
-        self._attrs = [
-            name
-            for name in dir(_os)
-            if not name.startswith('_') and hasattr(self, name)
-        ]
-
-    def _copy(self, source):
-        for name in self._attrs:
-            setattr(os, name, getattr(source, name))
-
-    def __enter__(self):
-        self._copy(self)
-        if _file:
-            builtins.file = self._file
-        builtins.open = self._open
-        self._active = True
-
-    def __exit__(self, exc_type, exc_value, traceback):
-        self._active = False
-        if _file:
-            builtins.file = _file
-        builtins.open = _open
-        self._copy(_os)
-
-    def run(self, func):
-        """Run 'func' under os sandboxing"""
-        with self:
-            return func()
-
-    def _mk_dual_path_wrapper(name):
-        original = getattr(_os, name)
-
-        def wrap(self, src, dst, *args, **kw):
-            if self._active:
-                src, dst = self._remap_pair(name, src, dst, *args, **kw)
-            return original(src, dst, *args, **kw)
-
-        return wrap
-
-    for name in ["rename", "link", "symlink"]:
-        if hasattr(_os, name):
-            locals()[name] = _mk_dual_path_wrapper(name)
-
-    def _mk_single_path_wrapper(name, original=None):
-        original = original or getattr(_os, name)
-
-        def wrap(self, path, *args, **kw):
-            if self._active:
-                path = self._remap_input(name, path, *args, **kw)
-            return original(path, *args, **kw)
-
-        return wrap
-
-    if _file:
-        _file = _mk_single_path_wrapper('file', _file)
-    _open = _mk_single_path_wrapper('open', _open)
-    for name in [
-        "stat",
-        "listdir",
-        "chdir",
-        "open",
-        "chmod",
-        "chown",
-        "mkdir",
-        "remove",
-        "unlink",
-        "rmdir",
-        "utime",
-        "lchown",
-        "chroot",
-        "lstat",
-        "startfile",
-        "mkfifo",
-        "mknod",
-        "pathconf",
-        "access",
-    ]:
-        if hasattr(_os, name):
-            locals()[name] = _mk_single_path_wrapper(name)
-
-    def _mk_single_with_return(name):
-        original = getattr(_os, name)
-
-        def wrap(self, path, *args, **kw):
-            if self._active:
-                path = self._remap_input(name, path, *args, **kw)
-                return self._remap_output(name, original(path, *args, **kw))
-            return original(path, *args, **kw)
-
-        return wrap
-
-    for name in ['readlink', 'tempnam']:
-        if hasattr(_os, name):
-            locals()[name] = _mk_single_with_return(name)
-
-    def _mk_query(name):
-        original = getattr(_os, name)
-
-        def wrap(self, *args, **kw):
-            retval = original(*args, **kw)
-            if self._active:
-                return self._remap_output(name, retval)
-            return retval
-
-        return wrap
-
-    for name in ['getcwd', 'tmpnam']:
-        if hasattr(_os, name):
-            locals()[name] = _mk_query(name)
-
-    def _validate_path(self, path):
-        """Called to remap or validate any path, whether input or output"""
-        return path
-
-    def _remap_input(self, operation, path, *args, **kw):
-        """Called for path inputs"""
-        return self._validate_path(path)
-
-    def _remap_output(self, operation, path):
-        """Called for path outputs"""
-        return self._validate_path(path)
-
-    def _remap_pair(self, operation, src, dst, *args, **kw):
-        """Called for path pairs like rename, link, and symlink operations"""
-        return (
-            self._remap_input(operation + '-from', src, *args, **kw),
-            self._remap_input(operation + '-to', dst, *args, **kw),
-        )
-
-
-if hasattr(os, 'devnull'):
-    _EXCEPTIONS = [os.devnull]
-else:
-    _EXCEPTIONS = []
-
-
-class DirectorySandbox(AbstractSandbox):
-    """Restrict operations to a single subdirectory - pseudo-chroot"""
-
-    write_ops = dict.fromkeys(
-        [
-            "open",
-            "chmod",
-            "chown",
-            "mkdir",
-            "remove",
-            "unlink",
-            "rmdir",
-            "utime",
-            "lchown",
-            "chroot",
-            "mkfifo",
-            "mknod",
-            "tempnam",
-        ]
-    )
-
-    _exception_patterns = []
-    "exempt writing to paths that match the pattern"
-
-    def __init__(self, sandbox, exceptions=_EXCEPTIONS):
-        self._sandbox = os.path.normcase(os.path.realpath(sandbox))
-        self._prefix = os.path.join(self._sandbox, '')
-        self._exceptions = [
-            os.path.normcase(os.path.realpath(path)) for path in exceptions
-        ]
-        AbstractSandbox.__init__(self)
-
-    def _violation(self, operation, *args, **kw):
-        from setuptools.sandbox import SandboxViolation
-
-        raise SandboxViolation(operation, args, kw)
-
-    if _file:
-
-        def _file(self, path, mode='r', *args, **kw):
-            if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
-                self._violation("file", path, mode, *args, **kw)
-            return _file(path, mode, *args, **kw)
-
-    def _open(self, path, mode='r', *args, **kw):
-        if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
-            self._violation("open", path, mode, *args, **kw)
-        return _open(path, mode, *args, **kw)
-
-    def tmpnam(self):
-        self._violation("tmpnam")
-
-    def _ok(self, path):
-        active = self._active
-        try:
-            self._active = False
-            realpath = os.path.normcase(os.path.realpath(path))
-            return (
-                self._exempted(realpath)
-                or realpath == self._sandbox
-                or realpath.startswith(self._prefix)
-            )
-        finally:
-            self._active = active
-
-    def _exempted(self, filepath):
-        start_matches = (
-            filepath.startswith(exception) for exception in self._exceptions
-        )
-        pattern_matches = (
-            re.match(pattern, filepath) for pattern in self._exception_patterns
-        )
-        candidates = itertools.chain(start_matches, pattern_matches)
-        return any(candidates)
-
-    def _remap_input(self, operation, path, *args, **kw):
-        """Called for path inputs"""
-        if operation in self.write_ops and not self._ok(path):
-            self._violation(operation, os.path.realpath(path), *args, **kw)
-        return path
-
-    def _remap_pair(self, operation, src, dst, *args, **kw):
-        """Called for path pairs like rename, link, and symlink operations"""
-        if not self._ok(src) or not self._ok(dst):
-            self._violation(operation, src, dst, *args, **kw)
-        return (src, dst)
-
-    def open(self, file, flags, mode=0o777, *args, **kw):
-        """Called for low-level os.open()"""
-        if flags & WRITE_FLAGS and not self._ok(file):
-            self._violation("os.open", file, flags, mode, *args, **kw)
-        return _os.open(file, flags, mode, *args, **kw)
-
-
-WRITE_FLAGS = functools.reduce(
-    operator.or_,
-    [
-        getattr(_os, a, 0)
-        for a in "O_WRONLY O_RDWR O_APPEND O_CREAT O_TRUNC O_TEMPORARY".split()
-    ],
-)
-
-
-class SandboxViolation(DistutilsError):
-    """A setup script attempted to modify the filesystem outside the sandbox"""
-
-    tmpl = textwrap.dedent(
-        """
-        SandboxViolation: {cmd}{args!r} {kwargs}
-
-        The package setup script has attempted to modify files on your system
-        that are not within the EasyInstall build area, and has been aborted.
-
-        This package cannot be safely installed by EasyInstall, and may not
-        support alternate installation locations even if you run its setup
-        script by hand.  Please inform the package's author and the EasyInstall
-        maintainers to find out if a fix or workaround is available.
-        """
-    ).lstrip()
-
-    def __str__(self):
-        cmd, args, kwargs = self.args
-        return self.tmpl.format(**locals())
diff --git a/setuptools/tests/__init__.py b/setuptools/tests/__init__.py
index 564adf2b0a..eb70bfb711 100644
--- a/setuptools/tests/__init__.py
+++ b/setuptools/tests/__init__.py
@@ -1,10 +1,13 @@
 import locale
+import sys
 
 import pytest
 
-
 __all__ = ['fail_on_ascii']
 
-
-is_ascii = locale.getpreferredencoding() == 'ANSI_X3.4-1968'
+if sys.version_info >= (3, 11):
+    locale_encoding = locale.getencoding()
+else:
+    locale_encoding = locale.getpreferredencoding(False)
+is_ascii = locale_encoding == 'ANSI_X3.4-1968'
 fail_on_ascii = pytest.mark.xfail(is_ascii, reason="Test fails in this locale")
diff --git a/pkg_resources/_vendor/importlib_resources/tests/data02/one/__init__.py b/setuptools/tests/compat/__init__.py
similarity index 100%
rename from pkg_resources/_vendor/importlib_resources/tests/data02/one/__init__.py
rename to setuptools/tests/compat/__init__.py
diff --git a/setuptools/tests/compat/py39.py b/setuptools/tests/compat/py39.py
new file mode 100644
index 0000000000..1fdb9dac1f
--- /dev/null
+++ b/setuptools/tests/compat/py39.py
@@ -0,0 +1,3 @@
+from jaraco.test.cpython import from_test_support, try_import
+
+os_helper = try_import('os_helper') or from_test_support('can_symlink')
diff --git a/setuptools/tests/config/downloads/__init__.py b/setuptools/tests/config/downloads/__init__.py
index 9fb9b14b02..00a16423f4 100644
--- a/setuptools/tests/config/downloads/__init__.py
+++ b/setuptools/tests/config/downloads/__init__.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
 import re
 import time
 from pathlib import Path
@@ -16,14 +18,14 @@
 # ----------------------------------------------------------------------
 
 
-def output_file(url: str, download_dir: Path = DOWNLOAD_DIR):
+def output_file(url: str, download_dir: Path = DOWNLOAD_DIR) -> Path:
     file_name = url.strip()
     for part in NAME_REMOVE:
         file_name = file_name.replace(part, '').strip().strip('/:').strip()
     return Path(download_dir, re.sub(r"[^\-_\.\w\d]+", "_", file_name))
 
 
-def retrieve_file(url: str, download_dir: Path = DOWNLOAD_DIR, wait: float = 5):
+def retrieve_file(url: str, download_dir: Path = DOWNLOAD_DIR, wait: float = 5) -> Path:
     path = output_file(url, download_dir)
     if path.exists():
         print(f"Skipping {url} (already exists: {path})")
@@ -38,7 +40,7 @@ def retrieve_file(url: str, download_dir: Path = DOWNLOAD_DIR, wait: float = 5):
     return path
 
 
-def urls_from_file(list_file: Path):
+def urls_from_file(list_file: Path) -> list[str]:
     """``list_file`` should be a text file where each line corresponds to a URL to
     download.
     """
diff --git a/setuptools/tests/config/downloads/preload.py b/setuptools/tests/config/downloads/preload.py
index 64b3f1c8d5..8eeb5dd75d 100644
--- a/setuptools/tests/config/downloads/preload.py
+++ b/setuptools/tests/config/downloads/preload.py
@@ -7,12 +7,12 @@
 
 to make sure the `setup.cfg` examples are downloaded before starting the tests.
 """
+
 import sys
 from pathlib import Path
 
 from . import retrieve_file, urls_from_file
 
-
 if __name__ == "__main__":
     urls = urls_from_file(Path(sys.argv[1]))
     list(map(retrieve_file, urls))
diff --git a/setuptools/tests/config/setupcfg_examples.txt b/setuptools/tests/config/setupcfg_examples.txt
index 5db3565464..6aab887ff1 100644
--- a/setuptools/tests/config/setupcfg_examples.txt
+++ b/setuptools/tests/config/setupcfg_examples.txt
@@ -15,7 +15,6 @@ https://github.com/pallets/click/raw/6411f425fae545f42795665af4162006b36c5e4a/se
 https://github.com/sqlalchemy/sqlalchemy/raw/533f5718904b620be8d63f2474229945d6f8ba5d/setup.cfg
 https://github.com/pytest-dev/pluggy/raw/461ef63291d13589c4e21aa182cd1529257e9a0a/setup.cfg
 https://github.com/pytest-dev/pytest/raw/c7be96dae487edbd2f55b561b31b68afac1dabe6/setup.cfg
-https://github.com/tqdm/tqdm/raw/fc69d5dcf578f7c7986fa76841a6b793f813df35/setup.cfg
 https://github.com/platformdirs/platformdirs/raw/7b7852128dd6f07511b618d6edea35046bd0c6ff/setup.cfg
 https://github.com/pandas-dev/pandas/raw/bc17343f934a33dc231c8c74be95d8365537c376/setup.cfg
 https://github.com/django/django/raw/4e249d11a6e56ca8feb4b055b681cec457ef3a3d/setup.cfg
diff --git a/setuptools/tests/config/test_apply_pyprojecttoml.py b/setuptools/tests/config/test_apply_pyprojecttoml.py
index ffcbd318a2..b6b21a3e9b 100644
--- a/setuptools/tests/config/test_apply_pyprojecttoml.py
+++ b/setuptools/tests/config/test_apply_pyprojecttoml.py
@@ -3,29 +3,31 @@
 
 To run these tests offline, please have a look on ``./downloads/preload.py``
 """
+
+from __future__ import annotations
+
 import io
 import re
 import tarfile
 from inspect import cleandoc
 from pathlib import Path
 from unittest.mock import Mock
-from zipfile import ZipFile
 
 import pytest
-from ini2toml.api import Translator
+from ini2toml.api import LiteTranslator
 from packaging.metadata import Metadata
 
-import setuptools  # noqa ensure monkey patch to metadata
-from setuptools.dist import Distribution
-from setuptools.config import setupcfg, pyprojecttoml
-from setuptools.config import expand
-from setuptools.config._apply_pyprojecttoml import _WouldIgnoreField, _some_attrgetter
+import setuptools  # noqa: F401 # ensure monkey patch to metadata
+from setuptools._static import is_static
 from setuptools.command.egg_info import write_requirements
-from setuptools.warnings import SetuptoolsDeprecationWarning
+from setuptools.config import expand, pyprojecttoml, setupcfg
+from setuptools.config._apply_pyprojecttoml import _MissingDynamic, _some_attrgetter
+from setuptools.dist import Distribution
+from setuptools.errors import InvalidConfigError, RemovedConfigError
+from setuptools.warnings import InformationOnly, SetuptoolsDeprecationWarning
 
 from .downloads import retrieve_file, urls_from_file
 
-
 HERE = Path(__file__).parent
 EXAMPLES_FILE = "setupcfg_examples.txt"
 
@@ -34,19 +36,32 @@ def makedist(path, **attrs):
     return Distribution({"src_root": path, **attrs})
 
 
+def _mock_expand_patterns(patterns, *_, **__):
+    """
+    Allow comparing the given patterns for 2 dist objects.
+    We need to strip special chars to avoid errors when validating.
+    """
+    return [
+        re.sub("[^a-z0-9]+", "", p, flags=re.IGNORECASE) or "empty" for p in patterns
+    ]
+
+
 @pytest.mark.parametrize("url", urls_from_file(HERE / EXAMPLES_FILE))
 @pytest.mark.filterwarnings("ignore")
 @pytest.mark.uses_network
 def test_apply_pyproject_equivalent_to_setupcfg(url, monkeypatch, tmp_path):
     monkeypatch.setattr(expand, "read_attr", Mock(return_value="0.0.1"))
+    monkeypatch.setattr(
+        Distribution, "_expand_patterns", Mock(side_effect=_mock_expand_patterns)
+    )
     setupcfg_example = retrieve_file(url)
     pyproject_example = Path(tmp_path, "pyproject.toml")
-    toml_config = Translator().translate(setupcfg_example.read_text(), "setup.cfg")
-    pyproject_example.write_text(toml_config)
+    setupcfg_text = setupcfg_example.read_text(encoding="utf-8")
+    toml_config = LiteTranslator().translate(setupcfg_text, "setup.cfg")
+    pyproject_example.write_text(toml_config, encoding="utf-8")
 
     dist_toml = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject_example)
     dist_cfg = setupcfg.apply_configuration(makedist(tmp_path), setupcfg_example)
-    _port_tests_require(dist_cfg)
 
     pkg_info_toml = core_metadata(dist_toml)
     pkg_info_cfg = core_metadata(dist_cfg)
@@ -79,12 +94,6 @@ def test_apply_pyproject_equivalent_to_setupcfg(url, monkeypatch, tmp_path):
 
     assert set(dist_toml.install_requires) == set(dist_cfg.install_requires)
     if any(getattr(d, "extras_require", None) for d in (dist_toml, dist_cfg)):
-        if (
-            "testing" in dist_toml.extras_require
-            and "testing" not in dist_cfg.extras_require
-        ):
-            # ini2toml can automatically convert `tests_require` to `testing` extra
-            dist_toml.extras_require.pop("testing")
         extra_req_toml = {(k, *sorted(v)) for k, v in dist_toml.extras_require.items()}
         extra_req_cfg = {(k, *sorted(v)) for k, v in dist_cfg.extras_require.items()}
         assert extra_req_toml == extra_req_cfg
@@ -97,7 +106,7 @@ def test_apply_pyproject_equivalent_to_setupcfg(url, monkeypatch, tmp_path):
 description = "Lovely Spam! Wonderful Spam!"
 readme = "README.rst"
 requires-python = ">=3.8"
-license = {file = "LICENSE.txt"}
+license-files = ["LICENSE.txt"]  # Updated to be PEP 639 compliant
 keywords = ["egg", "bacon", "sausage", "tomatoes", "Lobster Thermidor"]
 authors = [
   {email = "hi@pradyunsg.me"},
@@ -151,7 +160,7 @@ def test_apply_pyproject_equivalent_to_setupcfg(url, monkeypatch, tmp_path):
   {name = "Tzu-Ping Chung"}
 ]
 maintainers = [
-  {name = "Степан Бандера", email = "криївка@оун-упа.укр"},
+  {name = "अंकित अहलावत", email = "ankit@example.com"},
 ]
 """
 
@@ -161,6 +170,32 @@ def main_gui(): pass
 def main_tomatoes(): pass
 """
 
+PEP639_LICENSE_TEXT = """\
+[project]
+name = "spam"
+version = "2020.0.0"
+authors = [
+  {email = "hi@pradyunsg.me"},
+  {name = "Tzu-Ping Chung"}
+]
+license = {text = "MIT"}
+"""
+
+PEP639_LICENSE_EXPRESSION = """\
+[project]
+name = "spam"
+version = "2020.0.0"
+authors = [
+  {email = "hi@pradyunsg.me"},
+  {name = "Tzu-Ping Chung"}
+]
+license = "mit or apache-2.0"  # should be normalized in metadata
+classifiers = [
+    "Development Status :: 5 - Production/Stable",
+    "Programming Language :: Python",
+]
+"""
+
 
 def _pep621_example_project(
     tmp_path,
@@ -174,9 +209,9 @@ def _pep621_example_project(
         text = text.replace(orig, subst)
     pyproject.write_text(text, encoding="utf-8")
 
-    (tmp_path / readme).write_text("hello world")
-    (tmp_path / "LICENSE.txt").write_text("--- LICENSE stub ---")
-    (tmp_path / "spam.py").write_text(PEP621_EXAMPLE_SCRIPT)
+    (tmp_path / readme).write_text("hello world", encoding="utf-8")
+    (tmp_path / "LICENSE.txt").write_text("--- LICENSE stub ---", encoding="utf-8")
+    (tmp_path / "spam.py").write_text(PEP621_EXAMPLE_SCRIPT, encoding="utf-8")
     return pyproject
 
 
@@ -184,12 +219,11 @@ def test_pep621_example(tmp_path):
     """Make sure the example in PEP 621 works"""
     pyproject = _pep621_example_project(tmp_path)
     dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
-    assert dist.metadata.license == "--- LICENSE stub ---"
     assert set(dist.metadata.license_files) == {"LICENSE.txt"}
 
 
 @pytest.mark.parametrize(
-    "readme, ctype",
+    ("readme", "ctype"),
     [
         ("Readme.txt", "text/plain"),
         ("readme.md", "text/markdown"),
@@ -215,7 +249,7 @@ def test_no_explicit_content_type_for_missing_extension(tmp_path):
 
 
 @pytest.mark.parametrize(
-    ('pyproject_text', 'expected_maintainers_meta_value'),
+    ("pyproject_text", "expected_maintainers_meta_value"),
     (
         pytest.param(
             PEP621_EXAMPLE,
@@ -227,10 +261,10 @@ def test_no_explicit_content_type_for_missing_extension(tmp_path):
         ),
         pytest.param(
             PEP621_INTERNATIONAL_EMAIL_EXAMPLE,
-            'Степан Бандера <криївка@оун-упа.укр>',
+            'Ankit Ahlawat <अंकित@उदाहरण.भारत>',
             marks=pytest.mark.xfail(
                 reason="CPython's `email.headerregistry.Address` only supports "
-                'RFC 5322, as of Nov 10, 2022 and latest Python 3.11.0',
+                'RFC 5322, as of Oct 20, 2025 and latest Python 3.13.0',
                 strict=True,
             ),
             id='international-email',
@@ -256,22 +290,132 @@ def test_utf8_maintainer_in_metadata(  # issue-3663
     assert f"Maintainer-email: {expected_maintainers_meta_value}" in content
 
 
-class TestLicenseFiles:
-    # TODO: After PEP 639 is accepted, we have to move the license-files
-    #       to the `project` table instead of `tool.setuptools`
+@pytest.mark.parametrize(
+    (
+        'pyproject_text',
+        'license',
+        'license_expression',
+        'content_str',
+        'not_content_str',
+    ),
+    (
+        pytest.param(
+            PEP639_LICENSE_TEXT,
+            'MIT',
+            None,
+            'License: MIT',
+            'License-Expression: ',
+            id='license-text',
+            marks=[
+                pytest.mark.filterwarnings(
+                    "ignore:.project.license. as a TOML table is deprecated",
+                )
+            ],
+        ),
+        pytest.param(
+            PEP639_LICENSE_EXPRESSION,
+            None,
+            'MIT OR Apache-2.0',
+            'License-Expression: MIT OR Apache-2.0',
+            'License: ',
+            id='license-expression',
+        ),
+    ),
+)
+def test_license_in_metadata(
+    license,
+    license_expression,
+    content_str,
+    not_content_str,
+    pyproject_text,
+    tmp_path,
+):
+    pyproject = _pep621_example_project(
+        tmp_path,
+        "README",
+        pyproject_text=pyproject_text,
+    )
+    dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+    assert dist.metadata.license == license
+    assert dist.metadata.license_expression == license_expression
+    pkg_file = tmp_path / "PKG-FILE"
+    with open(pkg_file, "w", encoding="utf-8") as fh:
+        dist.metadata.write_pkg_file(fh)
+    content = pkg_file.read_text(encoding="utf-8")
+    assert "Metadata-Version: 2.4" in content
+    assert content_str in content
+    assert not_content_str not in content
+
+
+def test_license_classifier_with_license_expression(tmp_path):
+    text = PEP639_LICENSE_EXPRESSION.rsplit("\n", 2)[0]
+    pyproject = _pep621_example_project(
+        tmp_path,
+        "README",
+        f"{text}\n    \"License :: OSI Approved :: MIT License\"\n]",
+    )
+    msg = "License classifiers have been superseded by license expressions"
+    with pytest.raises(InvalidConfigError, match=msg) as exc:
+        pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+    assert "License :: OSI Approved :: MIT License" in str(exc.value)
+
+
+def test_license_classifier_without_license_expression(tmp_path):
+    text = """\
+    [project]
+    name = "spam"
+    version = "2020.0.0"
+    license = {text = "mit or apache-2.0"}
+    classifiers = ["License :: OSI Approved :: MIT License"]
+    """
+    pyproject = _pep621_example_project(tmp_path, "README", text)
+
+    msg1 = "License classifiers are deprecated(?:.|\n)*MIT License"
+    msg2 = ".project.license. as a TOML table is deprecated"
+    with (
+        pytest.warns(SetuptoolsDeprecationWarning, match=msg1),
+        pytest.warns(SetuptoolsDeprecationWarning, match=msg2),
+    ):
+        dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+    # Check license classifier is still included
+    assert dist.metadata.get_classifiers() == ["License :: OSI Approved :: MIT License"]
 
-    def base_pyproject(self, tmp_path, additional_text):
-        pyproject = _pep621_example_project(tmp_path, "README")
-        text = pyproject.read_text(encoding="utf-8")
+
+class TestLicenseFiles:
+    def base_pyproject(
+        self,
+        tmp_path,
+        additional_text="",
+        license_toml='license = {file = "LICENSE.txt"}\n',
+    ):
+        text = PEP639_LICENSE_EXPRESSION
 
         # Sanity-check
-        assert 'license = {file = "LICENSE.txt"}' in text
+        assert 'license = "mit or apache-2.0"' in text
+        assert 'license-files' not in text
         assert "[tool.setuptools]" not in text
 
+        text = re.sub(
+            r"(license = .*)\n",
+            license_toml,
+            text,
+            count=1,
+        )
+        assert license_toml in text  # sanity check
         text = f"{text}\n{additional_text}\n"
-        pyproject.write_text(text, encoding="utf-8")
+        pyproject = _pep621_example_project(tmp_path, "README", pyproject_text=text)
         return pyproject
 
+    def base_pyproject_license_pep639(self, tmp_path, additional_text=""):
+        return self.base_pyproject(
+            tmp_path,
+            additional_text=additional_text,
+            license_toml='license = "licenseref-Proprietary"'
+            '\nlicense-files = ["_FILE*"]\n',
+        )
+
     def test_both_license_and_license_files_defined(self, tmp_path):
         setuptools_config = '[tool.setuptools]\nlicense-files = ["_FILE*"]'
         pyproject = self.base_pyproject(tmp_path, setuptools_config)
@@ -284,14 +428,44 @@ def test_both_license_and_license_files_defined(self, tmp_path):
         license = tmp_path / "LICENSE.txt"
         license.write_text("LicenseRef-Proprietary\n", encoding="utf-8")
 
-        dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+        msg1 = "'tool.setuptools.license-files' is deprecated in favor of 'project.license-files'"
+        msg2 = ".project.license. as a TOML table is deprecated"
+        with (
+            pytest.warns(SetuptoolsDeprecationWarning, match=msg1),
+            pytest.warns(SetuptoolsDeprecationWarning, match=msg2),
+        ):
+            dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
         assert set(dist.metadata.license_files) == {"_FILE.rst", "_FILE.txt"}
         assert dist.metadata.license == "LicenseRef-Proprietary\n"
 
+    def test_both_license_and_license_files_defined_pep639(self, tmp_path):
+        # Set license and license-files
+        pyproject = self.base_pyproject_license_pep639(tmp_path)
+
+        (tmp_path / "_FILE.txt").touch()
+        (tmp_path / "_FILE.rst").touch()
+
+        msg = "Normalizing.*LicenseRef"
+        with pytest.warns(InformationOnly, match=msg):
+            dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+        assert set(dist.metadata.license_files) == {"_FILE.rst", "_FILE.txt"}
+        assert dist.metadata.license is None
+        assert dist.metadata.license_expression == "LicenseRef-Proprietary"
+
+    def test_license_files_defined_twice(self, tmp_path):
+        # Set project.license-files and tools.setuptools.license-files
+        setuptools_config = '[tool.setuptools]\nlicense-files = ["_FILE*"]'
+        pyproject = self.base_pyproject_license_pep639(tmp_path, setuptools_config)
+
+        msg = "'project.license-files' is defined already. Remove 'tool.setuptools.license-files'"
+        with pytest.raises(InvalidConfigError, match=msg):
+            pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
     def test_default_patterns(self, tmp_path):
         setuptools_config = '[tool.setuptools]\nzip-safe = false'
         # ^ used just to trigger section validation
-        pyproject = self.base_pyproject(tmp_path, setuptools_config)
+        pyproject = self.base_pyproject(tmp_path, setuptools_config, license_toml="")
 
         license_files = "LICENCE-a.html COPYING-abc.txt AUTHORS-xyz NOTICE,def".split()
 
@@ -299,9 +473,107 @@ def test_default_patterns(self, tmp_path):
             (tmp_path / fname).write_text(f"{fname}\n", encoding="utf-8")
 
         dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
         assert (tmp_path / "LICENSE.txt").exists()  # from base example
         assert set(dist.metadata.license_files) == {*license_files, "LICENSE.txt"}
 
+    def test_missing_patterns(self, tmp_path):
+        pyproject = self.base_pyproject_license_pep639(tmp_path)
+        assert list(tmp_path.glob("_FILE*")) == []  # sanity check
+
+        msg1 = "Cannot find any files for the given pattern.*"
+        msg2 = "Normalizing 'licenseref-Proprietary' to 'LicenseRef-Proprietary'"
+        with (
+            pytest.warns(SetuptoolsDeprecationWarning, match=msg1),
+            pytest.warns(InformationOnly, match=msg2),
+        ):
+            pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+    def test_deprecated_file_expands_to_text(self, tmp_path):
+        """Make sure the old example with ``license = {text = ...}`` works"""
+
+        assert 'license-files = ["LICENSE.txt"]' in PEP621_EXAMPLE  # sanity check
+        text = PEP621_EXAMPLE.replace(
+            'license-files = ["LICENSE.txt"]',
+            'license = {file = "LICENSE.txt"}',
+        )
+        pyproject = _pep621_example_project(tmp_path, pyproject_text=text)
+
+        msg = ".project.license. as a TOML table is deprecated"
+        with pytest.warns(SetuptoolsDeprecationWarning, match=msg):
+            dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+        assert dist.metadata.license == "--- LICENSE stub ---"
+        assert set(dist.metadata.license_files) == {"LICENSE.txt"}  # auto-filled
+
+
+class TestPyModules:
+    # https://github.com/pypa/setuptools/issues/4316
+
+    def dist(self, name):
+        toml_config = f"""
+        [project]
+        name = "test"
+        version = "42.0"
+        [tool.setuptools]
+        py-modules = [{name!r}]
+        """
+        pyproject = Path("pyproject.toml")
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        return pyprojecttoml.apply_configuration(Distribution({}), pyproject)
+
+    @pytest.mark.parametrize("module", ["pip-run", "abc-d.λ-xyz-e"])
+    def test_valid_module_name(self, tmp_path, monkeypatch, module):
+        monkeypatch.chdir(tmp_path)
+        assert module in self.dist(module).py_modules
+
+    @pytest.mark.parametrize("module", ["pip run", "-pip-run", "pip-run-stubs"])
+    def test_invalid_module_name(self, tmp_path, monkeypatch, module):
+        monkeypatch.chdir(tmp_path)
+        with pytest.raises(ValueError, match="py-modules"):
+            self.dist(module).py_modules
+
+
+class TestExtModules:
+    def make_dist(self, toml_config):
+        pyproject = Path("pyproject.toml")
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        with pytest.warns(pyprojecttoml._ExperimentalConfiguration):
+            return pyprojecttoml.apply_configuration(Distribution({}), pyproject)
+
+    def test_pyproject_sets_attribute(self, tmp_path, monkeypatch):
+        monkeypatch.chdir(tmp_path)
+        toml_config = """
+        [project]
+        name = "test"
+        version = "42.0"
+        [tool.setuptools]
+        ext-modules = [
+          {name = "my.ext", sources = ["hello.c", "world.c"]}
+        ]
+        """
+        dist = self.make_dist(toml_config)
+        assert len(dist.ext_modules) == 1
+        assert dist.ext_modules[0].name == "my.ext"
+        assert set(dist.ext_modules[0].sources) == {"hello.c", "world.c"}
+
+    def test_pyproject_define_macros_as_tuples(self, tmp_path, monkeypatch):
+        # https://github.com/pypa/setuptools/issues/4810
+        monkeypatch.chdir(tmp_path)
+        toml_config = """
+        [project]
+        name = "test"
+        version = "42.0"
+        [[tool.setuptools.ext-modules]]
+        name = "my.ext"
+        sources = ["hello.c", "world.c"]
+        define-macros = [["FIRST_SINGLE"], ["SECOND_TWO", "1"]]
+        """
+        dist = self.make_dist(toml_config)
+        assert isinstance(dist.ext_modules[0].define_macros[0], tuple)
+        assert dist.ext_modules[0].define_macros[0] == ("FIRST_SINGLE",)
+        assert dist.ext_modules[0].define_macros[1] == ("SECOND_TWO", "1")
+
 
 class TestDeprecatedFields:
     def test_namespace_packages(self, tmp_path):
@@ -314,7 +586,7 @@ def test_namespace_packages(self, tmp_path):
         namespace-packages = ["myproj.pkg"]
         """
         pyproject.write_text(cleandoc(config), encoding="utf-8")
-        with pytest.warns(SetuptoolsDeprecationWarning, match="namespace_packages"):
+        with pytest.raises(RemovedConfigError, match="namespace-packages"):
             pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
 
 
@@ -328,31 +600,39 @@ def pyproject(self, tmp_path, dynamic, extra_content=""):
         return file
 
     @pytest.mark.parametrize(
-        "attr, field, value",
+        ("attr", "field", "value"),
         [
-            ("install_requires", "dependencies", ["six"]),
+            ("license_expression", "license", "MIT"),
+            pytest.param(
+                *("license", "license", "Not SPDX"),
+                marks=[pytest.mark.filterwarnings("ignore:.*license. overwritten")],
+            ),
             ("classifiers", "classifiers", ["Private :: Classifier"]),
             ("entry_points", "scripts", {"console_scripts": ["foobar=foobar:main"]}),
             ("entry_points", "gui-scripts", {"gui_scripts": ["bazquux=bazquux:main"]}),
+            pytest.param(
+                *("install_requires", "dependencies", ["six"]),
+                marks=[
+                    pytest.mark.filterwarnings("ignore:.*install_requires. overwritten")
+                ],
+            ),
         ],
     )
     def test_not_listed_in_dynamic(self, tmp_path, attr, field, value):
-        """For the time being we just warn if the user pre-set values (e.g. via
-        ``setup.py``) but do not include them in ``dynamic``.
-        """
+        """Setuptools cannot set a field if not listed in ``dynamic``"""
         pyproject = self.pyproject(tmp_path, [])
         dist = makedist(tmp_path, **{attr: value})
-        msg = re.compile(f"defined outside of `pyproject.toml`:.*{field}", re.S)
-        with pytest.warns(_WouldIgnoreField, match=msg):
+        msg = re.compile(f"defined outside of `pyproject.toml`:.*{field}", re.DOTALL)
+        with pytest.warns(_MissingDynamic, match=msg):
             dist = pyprojecttoml.apply_configuration(dist, pyproject)
 
-        # TODO: Once support for pyproject.toml config stabilizes attr should be None
         dist_value = _some_attrgetter(f"metadata.{attr}", attr)(dist)
-        assert dist_value == value
+        assert not dist_value
 
     @pytest.mark.parametrize(
-        "attr, field, value",
+        ("attr", "field", "value"),
         [
+            ("license_expression", "license", "MIT"),
             ("install_requires", "dependencies", []),
             ("extras_require", "optional-dependencies", {}),
             ("install_requires", "dependencies", ["six"]),
@@ -366,6 +646,26 @@ def test_listed_in_dynamic(self, tmp_path, attr, field, value):
         dist_value = _some_attrgetter(f"metadata.{attr}", attr)(dist)
         assert dist_value == value
 
+    def test_license_files_exempt_from_dynamic(self, monkeypatch, tmp_path):
+        """
+        license-file is currently not considered in the context of dynamic.
+        As per 2025-02-19, https://packaging.python.org/en/latest/specifications/pyproject-toml/#license-files
+        allows setuptools to fill-in `license-files` the way it sees fit:
+
+        > If the license-files key is not defined, tools can decide how to handle license files.
+        > For example they can choose not to include any files or use their own
+        > logic to discover the appropriate files in the distribution.
+
+        Using license_files from setup.py to fill-in the value is in accordance
+        with this rule.
+        """
+        monkeypatch.chdir(tmp_path)
+        pyproject = self.pyproject(tmp_path, [])
+        dist = makedist(tmp_path, license_files=["LIC*"])
+        (tmp_path / "LIC1").write_text("42", encoding="utf-8")
+        dist = pyprojecttoml.apply_configuration(dist, pyproject)
+        assert dist.metadata.license_files == ["LIC1"]
+
     def test_warning_overwritten_dependencies(self, tmp_path):
         src = "[project]\nname='pkg'\nversion='0.1'\ndependencies=['click']\n"
         pyproject = tmp_path / "pyproject.toml"
@@ -398,7 +698,8 @@ def test_optional_dependencies_dont_remove_env_markers(self, tmp_path):
         assert ':python_version < "3.7"' in reqs
 
     @pytest.mark.parametrize(
-        "field,group", [("scripts", "console_scripts"), ("gui-scripts", "gui_scripts")]
+        ("field", "group"),
+        [("scripts", "console_scripts"), ("gui-scripts", "gui_scripts")],
     )
     @pytest.mark.filterwarnings("error")
     def test_scripts_dont_require_dynamic_entry_points(self, tmp_path, field, group):
@@ -415,10 +716,50 @@ def test_example_file_in_sdist(self, setuptools_sdist):
         with tarfile.open(setuptools_sdist) as tar:
             assert any(name.endswith(EXAMPLES_FILE) for name in tar.getnames())
 
-    def test_example_file_not_in_wheel(self, setuptools_wheel):
-        """Meta test to ensure auxiliary test files are not in wheel"""
-        with ZipFile(setuptools_wheel) as zipfile:
-            assert not any(name.endswith(EXAMPLES_FILE) for name in zipfile.namelist())
+
+class TestInteropCommandLineParsing:
+    def test_version(self, tmp_path, monkeypatch, capsys):
+        # See pypa/setuptools#4047
+        # This test can be removed once the CLI interface of setup.py is removed
+        monkeypatch.chdir(tmp_path)
+        toml_config = """
+        [project]
+        name = "test"
+        version = "42.0"
+        """
+        pyproject = Path(tmp_path, "pyproject.toml")
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        opts = {"script_args": ["--version"]}
+        dist = pyprojecttoml.apply_configuration(Distribution(opts), pyproject)
+        dist.parse_command_line()  # <-- there should be no exception here.
+        captured = capsys.readouterr()
+        assert "42.0" in captured.out
+
+
+class TestStaticConfig:
+    def test_mark_static_fields(self, tmp_path, monkeypatch):
+        monkeypatch.chdir(tmp_path)
+        toml_config = """
+        [project]
+        name = "test"
+        version = "42.0"
+        dependencies = ["hello"]
+        keywords = ["world"]
+        classifiers = ["private :: hello world"]
+        [tool.setuptools]
+        obsoletes = ["abcd"]
+        provides = ["abcd"]
+        platforms = ["abcd"]
+        """
+        pyproject = Path(tmp_path, "pyproject.toml")
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        dist = pyprojecttoml.apply_configuration(Distribution({}), pyproject)
+        assert is_static(dist.install_requires)
+        assert is_static(dist.metadata.keywords)
+        assert is_static(dist.metadata.classifiers)
+        assert is_static(dist.metadata.obsoletes)
+        assert is_static(dist.metadata.provides)
+        assert is_static(dist.metadata.platforms)
 
 
 # --- Auxiliary Functions ---
@@ -432,7 +773,7 @@ def core_metadata(dist) -> str:
     # Make sure core metadata is valid
     Metadata.from_email(pkg_file_txt, validate=True)  # can raise exceptions
 
-    skip_prefixes = ()
+    skip_prefixes: tuple[str, ...] = ()
     skip_lines = set()
     # ---- DIFF NORMALISATION ----
     # PEP 621 is very particular about author/maintainer metadata conversion, so skip
@@ -441,8 +782,6 @@ def core_metadata(dist) -> str:
     skip_prefixes += ("Project-URL: Homepage,", "Home-page:")
     # May be missing in original (relying on default) but backfilled in the TOML
     skip_prefixes += ("Description-Content-Type:",)
-    # ini2toml can automatically convert `tests_require` to `testing` extra
-    skip_lines.add("Provides-Extra: testing")
     # Remove empty lines
     skip_lines.add("")
 
@@ -453,15 +792,3 @@ def core_metadata(dist) -> str:
         result.append(line + "\n")
 
     return "".join(result)
-
-
-def _port_tests_require(dist):
-    """
-    ``ini2toml`` "forward fix" deprecated tests_require definitions by moving
-    them into an extra called ``testing``.
-    """
-    tests_require = getattr(dist, "tests_require", None) or []
-    if tests_require:
-        dist.tests_require = []
-        dist.extras_require.setdefault("testing", []).extend(tests_require)
-        dist._finalize_requires()
diff --git a/setuptools/tests/config/test_expand.py b/setuptools/tests/config/test_expand.py
index cdcbffc14c..c5710ec63d 100644
--- a/setuptools/tests/config/test_expand.py
+++ b/setuptools/tests/config/test_expand.py
@@ -1,18 +1,21 @@
 import os
+import sys
 from pathlib import Path
 
 import pytest
 
-from distutils.errors import DistutilsOptionError
+from setuptools._static import is_static
 from setuptools.config import expand
 from setuptools.discovery import find_package_path
 
+from distutils.errors import DistutilsOptionError
+
 
 def write_files(files, root_dir):
     for file, content in files.items():
         path = root_dir / file
         path.parent.mkdir(exist_ok=True, parents=True)
-        path.write_text(content)
+        path.write_text(content, encoding="utf-8")
 
 
 def test_glob_relative(tmp_path, monkeypatch):
@@ -83,7 +86,7 @@ def test_read_attr(self, tmp_path, monkeypatch):
             "pkg/__init__.py": "",
             "pkg/sub/__init__.py": "VERSION = '0.1.1'",
             "pkg/sub/mod.py": (
-                "VALUES = {'a': 0, 'b': {42}, 'c': (0, 1, 1)}\n" "raise SystemExit(1)"
+                "VALUES = {'a': 0, 'b': {42}, 'c': (0, 1, 1)}\nraise SystemExit(1)"
             ),
         }
         write_files(files, tmp_path)
@@ -91,11 +94,15 @@ def test_read_attr(self, tmp_path, monkeypatch):
         with monkeypatch.context() as m:
             m.chdir(tmp_path)
             # Make sure it can read the attr statically without evaluating the module
-            assert expand.read_attr('pkg.sub.VERSION') == '0.1.1'
+            version = expand.read_attr('pkg.sub.VERSION')
             values = expand.read_attr('lib.mod.VALUES', {'lib': 'pkg/sub'})
 
+        assert version == '0.1.1'
+        assert is_static(values)
+
         assert values['a'] == 0
         assert values['b'] == {42}
+        assert is_static(values)
 
         # Make sure the same APIs work outside cwd
         assert expand.read_attr('pkg.sub.VERSION', root_dir=tmp_path) == '0.1.1'
@@ -116,7 +123,28 @@ def test_read_annotated_attr(self, tmp_path, example):
         }
         write_files(files, tmp_path)
         # Make sure this attribute can be read statically
-        assert expand.read_attr('pkg.sub.VERSION', root_dir=tmp_path) == '0.1.1'
+        version = expand.read_attr('pkg.sub.VERSION', root_dir=tmp_path)
+        assert version == '0.1.1'
+        assert is_static(version)
+
+    @pytest.mark.parametrize(
+        "example",
+        [
+            "VERSION = (lambda: '0.1.1')()\n",
+            "def fn(): return '0.1.1'\nVERSION = fn()\n",
+            "VERSION: str = (lambda: '0.1.1')()\n",
+        ],
+    )
+    def test_read_dynamic_attr(self, tmp_path, monkeypatch, example):
+        files = {
+            "pkg/__init__.py": "",
+            "pkg/sub/__init__.py": example,
+        }
+        write_files(files, tmp_path)
+        monkeypatch.chdir(tmp_path)
+        version = expand.read_attr('pkg.sub.VERSION')
+        assert version == '0.1.1'
+        assert not is_static(version)
 
     def test_import_order(self, tmp_path):
         """
@@ -139,7 +167,7 @@ def test_import_order(self, tmp_path):
 
 
 @pytest.mark.parametrize(
-    'package_dir, file, module, return_value',
+    ("package_dir", "file", "module", "return_value"),
     [
         ({"": "src"}, "src/pkg/main.py", "pkg.main", 42),
         ({"pkg": "lib"}, "lib/main.py", "pkg.main", 13),
@@ -147,7 +175,8 @@ def test_import_order(self, tmp_path):
         ({}, "flat_layout/pkg.py", "flat_layout.pkg", 836),
     ],
 )
-def test_resolve_class(tmp_path, package_dir, file, module, return_value):
+def test_resolve_class(monkeypatch, tmp_path, package_dir, file, module, return_value):
+    monkeypatch.setattr(sys, "modules", {})  # reproducibility
     files = {file: f"class Custom:\n    def testing(self): return {return_value}"}
     write_files(files, tmp_path)
     cls = expand.resolve_class(f"{module}.Custom", package_dir, tmp_path)
@@ -155,7 +184,7 @@ def test_resolve_class(tmp_path, package_dir, file, module, return_value):
 
 
 @pytest.mark.parametrize(
-    'args, pkgs',
+    ("args", "pkgs"),
     [
         ({"where": ["."], "namespaces": False}, {"pkg", "other"}),
         ({"where": [".", "dir1"], "namespaces": False}, {"pkg", "other", "dir2"}),
@@ -189,7 +218,7 @@ def test_find_packages(tmp_path, args, pkgs):
 
 
 @pytest.mark.parametrize(
-    "files, where, expected_package_dir",
+    ("files", "where", "expected_package_dir"),
     [
         (["pkg1/__init__.py", "pkg1/other.py"], ["."], {}),
         (["pkg1/__init__.py", "pkg2/__init__.py"], ["."], {}),
diff --git a/setuptools/tests/config/test_pyprojecttoml.py b/setuptools/tests/config/test_pyprojecttoml.py
index 81ec949a42..e031ea810b 100644
--- a/setuptools/tests/config/test_pyprojecttoml.py
+++ b/setuptools/tests/config/test_pyprojecttoml.py
@@ -2,22 +2,22 @@
 from configparser import ConfigParser
 from inspect import cleandoc
 
+import jaraco.path
 import pytest
 import tomli_w
-from path import Path as _Path
+from path import Path
 
-from setuptools.config._apply_pyprojecttoml import _WouldIgnoreField
+import setuptools  # noqa: F401 # force distutils.core to be patched
 from setuptools.config.pyprojecttoml import (
-    read_configuration,
-    expand_configuration,
+    _ToolsTypoInMetadata,
     apply_configuration,
+    expand_configuration,
+    read_configuration,
     validate,
 )
 from setuptools.dist import Distribution
 from setuptools.errors import OptionError
 
-
-import setuptools  # noqa -- force distutils.core to be patched
 import distutils.core
 
 EXAMPLE = """
@@ -83,25 +83,32 @@
 
 
 def create_example(path, pkg_root):
-    pyproject = path / "pyproject.toml"
-
-    files = [
-        f"{pkg_root}/pkg/__init__.py",
-        "_files/file.txt",
-    ]
-    if pkg_root != ".":  # flat-layout will raise error for multi-package dist
-        # Ensure namespaces are discovered
-        files.append(f"{pkg_root}/other/nested/__init__.py")
+    files = {
+        "pyproject.toml": EXAMPLE,
+        "README.md": "hello world",
+        "_files": {
+            "file.txt": "",
+        },
+    }
+    packages = {
+        "pkg": {
+            "__init__.py": "",
+            "mod.py": "class CustomSdist: pass",
+            "__version__.py": "VERSION = (3, 10)",
+            "__main__.py": "def exec(): print('hello')",
+        },
+    }
+
+    assert pkg_root  # Meta-test: cannot be empty string.
 
-    for file in files:
-        (path / file).parent.mkdir(exist_ok=True, parents=True)
-        (path / file).touch()
+    if pkg_root == ".":
+        files = {**files, **packages}
+        # skip other files: flat-layout will raise error for multi-package dist
+    else:
+        # Use this opportunity to ensure namespaces are discovered
+        files[pkg_root] = {**packages, "other": {"nested": {"__init__.py": ""}}}
 
-    pyproject.write_text(EXAMPLE)
-    (path / "README.md").write_text("hello world")
-    (path / f"{pkg_root}/pkg/mod.py").write_text("class CustomSdist: pass")
-    (path / f"{pkg_root}/pkg/__version__.py").write_text("VERSION = (3, 10)")
-    (path / f"{pkg_root}/pkg/__main__.py").write_text("def exec(): print('hello')")
+    jaraco.path.build(files, prefix=path)
 
 
 def verify_example(config, path, pkg_root):
@@ -142,7 +149,7 @@ def test_read_configuration(tmp_path):
 
 
 @pytest.mark.parametrize(
-    "pkg_root, opts",
+    ("pkg_root", "opts"),
     [
         (".", {}),
         ("src", {}),
@@ -175,7 +182,7 @@ class TestEntryPoints:
     def write_entry_points(self, tmp_path):
         entry_points = ConfigParser()
         entry_points.read_dict(ENTRY_POINTS)
-        with open(tmp_path / "entry-points.txt", "w") as f:
+        with open(tmp_path / "entry-points.txt", "w", encoding="utf-8") as f:
             entry_points.write(f)
 
     def pyproject(self, dynamic=None):
@@ -200,14 +207,8 @@ def test_scripts_not_listed_in_dynamic(self, tmp_path, missing_dynamic):
         dynamic = {"scripts", "gui-scripts", "entry-points"} - {missing_dynamic}
 
         msg = f"defined outside of `pyproject.toml`:.*{missing_dynamic}"
-        with pytest.warns(_WouldIgnoreField, match=re.compile(msg, re.S)):
-            expanded = expand_configuration(self.pyproject(dynamic), tmp_path)
-
-        expanded_project = expanded["project"]
-        assert dynamic < set(expanded_project)
-        assert len(expanded_project["entry-points"]) == 1
-        # TODO: Test the following when pyproject.toml support stabilizes:
-        # >>> assert missing_dynamic not in expanded_project
+        with pytest.raises(OptionError, match=re.compile(msg, re.DOTALL)):
+            expand_configuration(self.pyproject(dynamic), tmp_path)
 
 
 class TestClassifiers:
@@ -215,11 +216,13 @@ def test_dynamic(self, tmp_path):
         # Let's create a project example that has dynamic classifiers
         # coming from a txt file.
         create_example(tmp_path, "src")
-        classifiers = """\
-        Framework :: Flask
-        Programming Language :: Haskell
-        """
-        (tmp_path / "classifiers.txt").write_text(cleandoc(classifiers))
+        classifiers = cleandoc(
+            """
+            Framework :: Flask
+            Programming Language :: Haskell
+            """
+        )
+        (tmp_path / "classifiers.txt").write_text(classifiers, encoding="utf-8")
 
         pyproject = tmp_path / "pyproject.toml"
         config = read_configuration(pyproject, expand=False)
@@ -247,7 +250,7 @@ def test_dynamic_without_config(self, tmp_path):
         """
 
         pyproject = tmp_path / "pyproject.toml"
-        pyproject.write_text(cleandoc(config))
+        pyproject.write_text(cleandoc(config), encoding="utf-8")
         with pytest.raises(OptionError, match="No configuration .* .classifiers."):
             read_configuration(pyproject)
 
@@ -259,7 +262,7 @@ def test_dynamic_readme_from_setup_script_args(self, tmp_path):
         dynamic = ["readme"]
         """
         pyproject = tmp_path / "pyproject.toml"
-        pyproject.write_text(cleandoc(config))
+        pyproject.write_text(cleandoc(config), encoding="utf-8")
         dist = Distribution(attrs={"long_description": "42"})
         # No error should occur because of missing `readme`
         dist = apply_configuration(dist, pyproject)
@@ -277,12 +280,35 @@ def test_dynamic_without_file(self, tmp_path):
         """
 
         pyproject = tmp_path / "pyproject.toml"
-        pyproject.write_text(cleandoc(config))
+        pyproject.write_text(cleandoc(config), encoding="utf-8")
         with pytest.warns(UserWarning, match="File .*classifiers.txt. cannot be found"):
             expanded = read_configuration(pyproject)
         assert "classifiers" not in expanded["project"]
 
 
+class TestImportNames:
+    EXAMPLES = [
+        'import-names = ["hello", "world"]',
+        'import-namespaces = ["hello", "world"]',
+        'dynamic = ["import-names"]',
+        'dynamic = ["import-namespaces"]',
+    ]
+
+    @pytest.mark.parametrize("example", EXAMPLES)
+    def test_not_implemented(self, monkeypatch, tmp_path, example):
+        monkeypatch.chdir(tmp_path)
+        pyproject = Path("pyproject.toml")
+        toml_config = f"""
+        [project]
+        name = 'proj'
+        version = '42'
+        {example}
+        """
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        with pytest.raises(NotImplementedError, match='import-names'):
+            apply_configuration(Distribution({}), pyproject)
+
+
 @pytest.mark.parametrize(
     "example",
     (
@@ -298,14 +324,14 @@ def test_dynamic_without_file(self, tmp_path):
 )
 def test_ignore_unrelated_config(tmp_path, example):
     pyproject = tmp_path / "pyproject.toml"
-    pyproject.write_text(cleandoc(example))
+    pyproject.write_text(cleandoc(example), encoding="utf-8")
 
     # Make sure no error is raised due to 3rd party configs in pyproject.toml
     assert read_configuration(pyproject) is not None
 
 
 @pytest.mark.parametrize(
-    "example, error_msg",
+    ("example", "error_msg"),
     [
         (
             """
@@ -320,9 +346,11 @@ def test_ignore_unrelated_config(tmp_path, example):
 )
 def test_invalid_example(tmp_path, example, error_msg):
     pyproject = tmp_path / "pyproject.toml"
-    pyproject.write_text(cleandoc(example))
+    pyproject.write_text(cleandoc(example), encoding="utf-8")
 
-    pattern = re.compile(f"invalid pyproject.toml.*{error_msg}.*", re.M | re.S)
+    pattern = re.compile(
+        f"invalid pyproject.toml.*{error_msg}.*", re.MULTILINE | re.DOTALL
+    )
     with pytest.raises(ValueError, match=pattern):
         read_configuration(pyproject)
 
@@ -330,7 +358,7 @@ def test_invalid_example(tmp_path, example, error_msg):
 @pytest.mark.parametrize("config", ("", "[tool.something]\nvalue = 42"))
 def test_empty(tmp_path, config):
     pyproject = tmp_path / "pyproject.toml"
-    pyproject.write_text(config)
+    pyproject.write_text(config, encoding="utf-8")
 
     # Make sure no error is raised
     assert read_configuration(pyproject) == {}
@@ -342,7 +370,7 @@ def test_include_package_data_by_default(tmp_path, config):
     default.
     """
     pyproject = tmp_path / "pyproject.toml"
-    pyproject.write_text(config)
+    pyproject.write_text(config, encoding="utf-8")
 
     config = read_configuration(pyproject)
     assert config["tool"]["setuptools"]["include-package-data"] is True
@@ -354,14 +382,40 @@ def test_include_package_data_in_setuppy(tmp_path):
 
     See https://github.com/pypa/setuptools/issues/3197#issuecomment-1079023889
     """
-    pyproject = tmp_path / "pyproject.toml"
-    pyproject.write_text("[project]\nname = 'myproj'\nversion='42'\n")
-    setuppy = tmp_path / "setup.py"
-    setuppy.write_text("__import__('setuptools').setup(include_package_data=False)")
+    files = {
+        "pyproject.toml": "[project]\nname = 'myproj'\nversion='42'\n",
+        "setup.py": "__import__('setuptools').setup(include_package_data=False)",
+    }
+    jaraco.path.build(files, prefix=tmp_path)
 
-    with _Path(tmp_path):
+    with Path(tmp_path):
         dist = distutils.core.run_setup("setup.py", {}, stop_after="config")
 
     assert dist.get_name() == "myproj"
     assert dist.get_version() == "42"
     assert dist.include_package_data is False
+
+
+def test_warn_tools_typo(tmp_path):
+    """Test that the common ``tools.setuptools`` typo in ``pyproject.toml`` issues a warning
+
+    See https://github.com/pypa/setuptools/issues/4150
+    """
+    config = """
+    [build-system]
+    requires = ["setuptools"]
+    build-backend = "setuptools.build_meta"
+
+    [project]
+    name = "myproj"
+    version = '42'
+
+    [tools.setuptools]
+    packages = ["package"]
+    """
+
+    pyproject = tmp_path / "pyproject.toml"
+    pyproject.write_text(cleandoc(config), encoding="utf-8")
+
+    with pytest.warns(_ToolsTypoInMetadata):
+        read_configuration(pyproject)
diff --git a/setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py b/setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py
index b6516227c0..9fc8050743 100644
--- a/setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py
+++ b/setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py
@@ -1,57 +1,60 @@
+from inspect import cleandoc
+
 import pytest
+from jaraco import path
 
 from setuptools.config.pyprojecttoml import apply_configuration
 from setuptools.dist import Distribution
-from setuptools.tests.textwrap import DALS
+from setuptools.warnings import SetuptoolsWarning
 
 
 def test_dynamic_dependencies(tmp_path):
-    (tmp_path / "requirements.txt").write_text("six\n  # comment\n")
-    pyproject = tmp_path / "pyproject.toml"
-    pyproject.write_text(
-        DALS(
+    files = {
+        "requirements.txt": "six\n  # comment\n",
+        "pyproject.toml": cleandoc(
             """
-    [project]
-    name = "myproj"
-    version = "1.0"
-    dynamic = ["dependencies"]
+            [project]
+            name = "myproj"
+            version = "1.0"
+            dynamic = ["dependencies"]
 
-    [build-system]
-    requires = ["setuptools", "wheel"]
-    build-backend = "setuptools.build_meta"
+            [build-system]
+            requires = ["setuptools", "wheel"]
+            build-backend = "setuptools.build_meta"
 
-    [tool.setuptools.dynamic.dependencies]
-    file = ["requirements.txt"]
-    """
-        )
-    )
+            [tool.setuptools.dynamic.dependencies]
+            file = ["requirements.txt"]
+            """
+        ),
+    }
+    path.build(files, prefix=tmp_path)
     dist = Distribution()
-    dist = apply_configuration(dist, pyproject)
+    dist = apply_configuration(dist, tmp_path / "pyproject.toml")
     assert dist.install_requires == ["six"]
 
 
 def test_dynamic_optional_dependencies(tmp_path):
-    (tmp_path / "requirements-docs.txt").write_text("sphinx\n  # comment\n")
-    pyproject = tmp_path / "pyproject.toml"
-    pyproject.write_text(
-        DALS(
+    files = {
+        "requirements-docs.txt": "sphinx\n  # comment\n",
+        "pyproject.toml": cleandoc(
             """
-    [project]
-    name = "myproj"
-    version = "1.0"
-    dynamic = ["optional-dependencies"]
+            [project]
+            name = "myproj"
+            version = "1.0"
+            dynamic = ["optional-dependencies"]
 
-    [tool.setuptools.dynamic.optional-dependencies.docs]
-    file = ["requirements-docs.txt"]
+            [tool.setuptools.dynamic.optional-dependencies.docs]
+            file = ["requirements-docs.txt"]
 
-    [build-system]
-    requires = ["setuptools", "wheel"]
-    build-backend = "setuptools.build_meta"
-    """
-        )
-    )
+            [build-system]
+            requires = ["setuptools", "wheel"]
+            build-backend = "setuptools.build_meta"
+            """
+        ),
+    }
+    path.build(files, prefix=tmp_path)
     dist = Distribution()
-    dist = apply_configuration(dist, pyproject)
+    dist = apply_configuration(dist, tmp_path / "pyproject.toml")
     assert dist.extras_require == {"docs": ["sphinx"]}
 
 
@@ -61,34 +64,48 @@ def test_mixed_dynamic_optional_dependencies(tmp_path):
     configurations in the case of fields containing sub-fields (groups),
     things would work out.
     """
-    (tmp_path / "requirements-images.txt").write_text("pillow~=42.0\n  # comment\n")
-    pyproject = tmp_path / "pyproject.toml"
-    pyproject.write_text(
-        DALS(
+    files = {
+        "requirements-images.txt": "pillow~=42.0\n  # comment\n",
+        "pyproject.toml": cleandoc(
             """
-    [project]
-    name = "myproj"
-    version = "1.0"
-    dynamic = ["optional-dependencies"]
+            [project]
+            name = "myproj"
+            version = "1.0"
+            dynamic = ["optional-dependencies"]
 
-    [project.optional-dependencies]
-    docs = ["sphinx"]
+            [project.optional-dependencies]
+            docs = ["sphinx"]
 
-    [tool.setuptools.dynamic.optional-dependencies.images]
-    file = ["requirements-images.txt"]
+            [tool.setuptools.dynamic.optional-dependencies.images]
+            file = ["requirements-images.txt"]
+            """
+        ),
+    }
 
-    [build-system]
-    requires = ["setuptools", "wheel"]
-    build-backend = "setuptools.build_meta"
-    """
-        )
-    )
-    # Test that the mix-and-match doesn't currently validate.
+    path.build(files, prefix=tmp_path)
+    pyproject = tmp_path / "pyproject.toml"
     with pytest.raises(ValueError, match="project.optional-dependencies"):
         apply_configuration(Distribution(), pyproject)
 
-    # Explicitly disable the validation and try again, to see that the mix-and-match
-    # result would be correct.
-    dist = Distribution()
-    dist = apply_configuration(dist, pyproject, ignore_option_errors=True)
-    assert dist.extras_require == {"docs": ["sphinx"], "images": ["pillow~=42.0"]}
+
+def test_mixed_extras_require_optional_dependencies(tmp_path):
+    files = {
+        "pyproject.toml": cleandoc(
+            """
+            [project]
+            name = "myproj"
+            version = "1.0"
+            optional-dependencies.docs = ["sphinx"]
+            """
+        ),
+    }
+
+    path.build(files, prefix=tmp_path)
+    pyproject = tmp_path / "pyproject.toml"
+
+    dist = Distribution({"extras_require": {"hello": ["world"]}})
+
+    with pytest.warns(SetuptoolsWarning, match=".extras_require. overwritten"):
+        dist = apply_configuration(dist, pyproject)
+
+    assert dist.extras_require == {"docs": ["sphinx"]}
diff --git a/setuptools/tests/config/test_setupcfg.py b/setuptools/tests/config/test_setupcfg.py
index fa16728ea7..495337a9a5 100644
--- a/setuptools/tests/config/test_setupcfg.py
+++ b/setuptools/tests/config/test_setupcfg.py
@@ -1,20 +1,26 @@
 import configparser
 import contextlib
 import inspect
+import re
+import sys
 from pathlib import Path
 from unittest.mock import Mock, patch
 
 import pytest
+from packaging.requirements import InvalidRequirement
 
-from distutils.errors import DistutilsOptionError, DistutilsFileError
+from setuptools.config.setupcfg import ConfigHandler, Target, read_configuration
 from setuptools.dist import Distribution, _Distribution
-from setuptools.config.setupcfg import ConfigHandler, read_configuration
-from setuptools.extern.packaging.requirements import InvalidRequirement
 from setuptools.warnings import SetuptoolsDeprecationWarning
+
 from ..textwrap import DALS
 
+from distutils.errors import DistutilsFileError, DistutilsOptionError
+
+IS_PYPY = '__pypy__' in sys.builtin_module_names
 
-class ErrConfigHandler(ConfigHandler):
+
+class ErrConfigHandler(ConfigHandler[Target]):
     """Erroneous handler. Fails to implement required methods."""
 
     section_prefix = "**err**"
@@ -35,7 +41,7 @@ def fake_env(
     tmpdir, setup_cfg, setup_py=None, encoding='ascii', package_path='fake_package'
 ):
     if setup_py is None:
-        setup_py = 'from setuptools import setup\n' 'setup()\n'
+        setup_py = 'from setuptools import setup\nsetup()\n'
 
     tmpdir.join('setup.py').write(setup_py)
     config = tmpdir.join('setup.cfg')
@@ -85,24 +91,24 @@ def test_basic(self, tmpdir):
             '[options]\n'
             'scripts = bin/a.py, bin/b.py\n',
         )
-        config_dict = read_configuration('%s' % config)
+        config_dict = read_configuration(str(config))
         assert config_dict['metadata']['version'] == '10.1.1'
         assert config_dict['metadata']['keywords'] == ['one', 'two']
         assert config_dict['options']['scripts'] == ['bin/a.py', 'bin/b.py']
 
     def test_no_config(self, tmpdir):
         with pytest.raises(DistutilsFileError):
-            read_configuration('%s' % tmpdir.join('setup.cfg'))
+            read_configuration(str(tmpdir.join('setup.cfg')))
 
     def test_ignore_errors(self, tmpdir):
         _, config = fake_env(
             tmpdir,
-            '[metadata]\n' 'version = attr: none.VERSION\n' 'keywords = one, two\n',
+            '[metadata]\nversion = attr: none.VERSION\nkeywords = one, two\n',
         )
         with pytest.raises(ImportError):
-            read_configuration('%s' % config)
+            read_configuration(str(config))
 
-        config_dict = read_configuration('%s' % config, ignore_option_errors=True)
+        config_dict = read_configuration(str(config), ignore_option_errors=True)
 
         assert config_dict['metadata']['keywords'] == ['one', 'two']
         assert 'version' not in config_dict['metadata']
@@ -171,7 +177,7 @@ def test_license_cfg(self, tmpdir):
     def test_file_mixed(self, tmpdir):
         fake_env(
             tmpdir,
-            '[metadata]\n' 'long_description = file: README.rst, CHANGES.rst\n' '\n',
+            '[metadata]\nlong_description = file: README.rst, CHANGES.rst\n\n',
         )
 
         tmpdir.join('README.rst').write('readme contents\nline2')
@@ -179,14 +185,14 @@ def test_file_mixed(self, tmpdir):
 
         with get_dist(tmpdir) as dist:
             assert dist.metadata.long_description == (
-                'readme contents\nline2\n' 'changelog contents\nand stuff'
+                'readme contents\nline2\nchangelog contents\nand stuff'
             )
 
     def test_file_sandboxed(self, tmpdir):
         tmpdir.ensure("README")
         project = tmpdir.join('depth1', 'depth2')
         project.ensure(dir=True)
-        fake_env(project, '[metadata]\n' 'long_description = file: ../../README\n')
+        fake_env(project, '[metadata]\nlong_description = file: ../../README\n')
 
         with get_dist(project, parse=False) as dist:
             with pytest.raises(DistutilsOptionError):
@@ -253,7 +259,7 @@ def test_dict(self, tmpdir):
 
     def test_version(self, tmpdir):
         package_dir, config = fake_env(
-            tmpdir, '[metadata]\n' 'version = attr: fake_package.VERSION\n'
+            tmpdir, '[metadata]\nversion = attr: fake_package.VERSION\n'
         )
 
         sub_a = package_dir.mkdir('subpkg_a')
@@ -263,36 +269,30 @@ def test_version(self, tmpdir):
         sub_b = package_dir.mkdir('subpkg_b')
         sub_b.join('__init__.py').write('')
         sub_b.join('mod.py').write(
-            'import third_party_module\n' 'VERSION = (2016, 11, 26)'
+            'import third_party_module\nVERSION = (2016, 11, 26)'
         )
 
         with get_dist(tmpdir) as dist:
             assert dist.metadata.version == '1.2.3'
 
-        config.write('[metadata]\n' 'version = attr: fake_package.get_version\n')
+        config.write('[metadata]\nversion = attr: fake_package.get_version\n')
         with get_dist(tmpdir) as dist:
             assert dist.metadata.version == '3.4.5.dev'
 
-        config.write('[metadata]\n' 'version = attr: fake_package.VERSION_MAJOR\n')
+        config.write('[metadata]\nversion = attr: fake_package.VERSION_MAJOR\n')
         with get_dist(tmpdir) as dist:
             assert dist.metadata.version == '1'
 
-        config.write(
-            '[metadata]\n' 'version = attr: fake_package.subpkg_a.mod.VERSION\n'
-        )
+        config.write('[metadata]\nversion = attr: fake_package.subpkg_a.mod.VERSION\n')
         with get_dist(tmpdir) as dist:
             assert dist.metadata.version == '2016.11.26'
 
-        config.write(
-            '[metadata]\n' 'version = attr: fake_package.subpkg_b.mod.VERSION\n'
-        )
+        config.write('[metadata]\nversion = attr: fake_package.subpkg_b.mod.VERSION\n')
         with get_dist(tmpdir) as dist:
             assert dist.metadata.version == '2016.11.26'
 
     def test_version_file(self, tmpdir):
-        _, config = fake_env(
-            tmpdir, '[metadata]\n' 'version = file: fake_package/version.txt\n'
-        )
+        fake_env(tmpdir, '[metadata]\nversion = file: fake_package/version.txt\n')
         tmpdir.join('fake_package', 'version.txt').write('1.2.3\n')
 
         with get_dist(tmpdir) as dist:
@@ -304,7 +304,7 @@ def test_version_file(self, tmpdir):
                 dist.metadata.version
 
     def test_version_with_package_dir_simple(self, tmpdir):
-        _, config = fake_env(
+        fake_env(
             tmpdir,
             '[metadata]\n'
             'version = attr: fake_package_simple.VERSION\n'
@@ -318,7 +318,7 @@ def test_version_with_package_dir_simple(self, tmpdir):
             assert dist.metadata.version == '1.2.3'
 
     def test_version_with_package_dir_rename(self, tmpdir):
-        _, config = fake_env(
+        fake_env(
             tmpdir,
             '[metadata]\n'
             'version = attr: fake_package_rename.VERSION\n'
@@ -332,7 +332,7 @@ def test_version_with_package_dir_rename(self, tmpdir):
             assert dist.metadata.version == '1.2.3'
 
     def test_version_with_package_dir_complex(self, tmpdir):
-        _, config = fake_env(
+        fake_env(
             tmpdir,
             '[metadata]\n'
             'version = attr: fake_package_complex.VERSION\n'
@@ -346,27 +346,25 @@ def test_version_with_package_dir_complex(self, tmpdir):
             assert dist.metadata.version == '1.2.3'
 
     def test_unknown_meta_item(self, tmpdir):
-        fake_env(tmpdir, '[metadata]\n' 'name = fake_name\n' 'unknown = some\n')
+        fake_env(tmpdir, '[metadata]\nname = fake_name\nunknown = some\n')
         with get_dist(tmpdir, parse=False) as dist:
             dist.parse_config_files()  # Skip unknown.
 
     def test_usupported_section(self, tmpdir):
-        fake_env(tmpdir, '[metadata.some]\n' 'key = val\n')
+        fake_env(tmpdir, '[metadata.some]\nkey = val\n')
         with get_dist(tmpdir, parse=False) as dist:
             with pytest.raises(DistutilsOptionError):
                 dist.parse_config_files()
 
     def test_classifiers(self, tmpdir):
-        expected = set(
-            [
-                'Framework :: Django',
-                'Programming Language :: Python :: 3',
-                'Programming Language :: Python :: 3.5',
-            ]
-        )
+        expected = set([
+            'Framework :: Django',
+            'Programming Language :: Python :: 3',
+            'Programming Language :: Python :: 3.5',
+        ])
 
         # From file.
-        _, config = fake_env(tmpdir, '[metadata]\n' 'classifiers = file: classifiers\n')
+        _, config = fake_env(tmpdir, '[metadata]\nclassifiers = file: classifiers\n')
 
         tmpdir.join('classifiers').write(
             'Framework :: Django\n'
@@ -388,43 +386,26 @@ def test_classifiers(self, tmpdir):
         with get_dist(tmpdir) as dist:
             assert set(dist.metadata.classifiers) == expected
 
-    def test_deprecated_config_handlers(self, tmpdir):
-        fake_env(
-            tmpdir,
-            '[metadata]\n'
-            'version = 10.1.1\n'
-            'description = Some description\n'
-            'requires = some, requirement\n',
-        )
-
-        with pytest.warns(SetuptoolsDeprecationWarning, match="requires"):
-            with get_dist(tmpdir) as dist:
-                metadata = dist.metadata
-
-                assert metadata.version == '10.1.1'
-                assert metadata.description == 'Some description'
-                assert metadata.requires == ['some', 'requirement']
-
     def test_interpolation(self, tmpdir):
-        fake_env(tmpdir, '[metadata]\n' 'description = %(message)s\n')
+        fake_env(tmpdir, '[metadata]\ndescription = %(message)s\n')
         with pytest.raises(configparser.InterpolationMissingOptionError):
             with get_dist(tmpdir):
                 pass
 
     def test_non_ascii_1(self, tmpdir):
-        fake_env(tmpdir, '[metadata]\n' 'description = éàïôñ\n', encoding='utf-8')
+        fake_env(tmpdir, '[metadata]\ndescription = éàïôñ\n', encoding='utf-8')
         with get_dist(tmpdir):
             pass
 
     def test_non_ascii_3(self, tmpdir):
-        fake_env(tmpdir, '\n' '# -*- coding: invalid\n')
+        fake_env(tmpdir, '\n# -*- coding: invalid\n')
         with get_dist(tmpdir):
             pass
 
     def test_non_ascii_4(self, tmpdir):
         fake_env(
             tmpdir,
-            '# -*- coding: utf-8\n' '[metadata]\n' 'description = éàïôñ\n',
+            '# -*- coding: utf-8\n[metadata]\ndescription = éàïôñ\n',
             encoding='utf-8',
         )
         with get_dist(tmpdir) as dist:
@@ -436,45 +417,55 @@ def test_not_utf8(self, tmpdir):
         """
         fake_env(
             tmpdir,
-            '# vim: set fileencoding=iso-8859-15 :\n'
-            '[metadata]\n'
-            'description = éàïôñ\n',
+            '# vim: set fileencoding=iso-8859-15 :\n[metadata]\ndescription = éàïôñ\n',
             encoding='iso-8859-15',
         )
         with pytest.raises(UnicodeDecodeError):
             with get_dist(tmpdir):
                 pass
 
-    def test_warn_dash_deprecation(self, tmpdir):
-        # warn_dash_deprecation() is a method in setuptools.dist
-        # remove this test and the method when no longer needed
-        fake_env(
-            tmpdir,
-            '[metadata]\n'
-            'author-email = test@test.com\n'
-            'maintainer_email = foo@foo.com\n',
-        )
-        msg = "Usage of dash-separated 'author-email' will not be supported"
-        with pytest.warns(SetuptoolsDeprecationWarning, match=msg):
-            with get_dist(tmpdir) as dist:
-                metadata = dist.metadata
-
-        assert metadata.author_email == 'test@test.com'
-        assert metadata.maintainer_email == 'foo@foo.com'
+    @pytest.mark.parametrize(
+        ("error_msg", "config", "invalid"),
+        [
+            (
+                "Invalid dash-separated key 'author-email' in 'metadata' (setup.cfg)",
+                DALS(
+                    """
+                    [metadata]
+                    author-email = test@test.com
+                    maintainer_email = foo@foo.com
+                    """
+                ),
+                {"author-email": "test@test.com"},
+            ),
+            (
+                "Invalid uppercase key 'Name' in 'metadata' (setup.cfg)",
+                DALS(
+                    """
+                    [metadata]
+                    Name = foo
+                    description = Some description
+                    """
+                ),
+                {"Name": "foo"},
+            ),
+        ],
+    )
+    def test_invalid_options_previously_deprecated(
+        self, tmpdir, error_msg, config, invalid
+    ):
+        # This test and related methods can be removed when no longer needed.
+        # Deprecation postponed due to push-back from the community in
+        # https://github.com/pypa/setuptools/issues/4910
+        fake_env(tmpdir, config)
+        with pytest.warns(SetuptoolsDeprecationWarning, match=re.escape(error_msg)):
+            dist = get_dist(tmpdir).__enter__()
 
-    def test_make_option_lowercase(self, tmpdir):
-        # remove this test and the method make_option_lowercase() in setuptools.dist
-        # when no longer needed
-        fake_env(
-            tmpdir, '[metadata]\n' 'Name = foo\n' 'description = Some description\n'
-        )
-        msg = "Usage of uppercase key 'Name' in 'metadata' will not be supported"
-        with pytest.warns(SetuptoolsDeprecationWarning, match=msg):
-            with get_dist(tmpdir) as dist:
-                metadata = dist.metadata
+        tmpdir.join('setup.cfg').remove()
 
-        assert metadata.name == 'foo'
-        assert metadata.description == 'Some description'
+        for field, value in invalid.items():
+            attr = field.replace("-", "_").lower()
+            assert getattr(dist.metadata, attr) == value
 
 
 class TestOptions:
@@ -490,7 +481,6 @@ def test_basic(self, tmpdir):
             'scripts = bin/one.py, bin/two.py\n'
             'eager_resources = bin/one.py, bin/two.py\n'
             'install_requires = docutils>=0.3; pack ==1.1, ==1.3; hey\n'
-            'tests_require = mock==0.7.2; pytest\n'
             'setup_requires = docutils>=0.3; spack ==1.1, ==1.3; there\n'
             'dependency_links = http://some.com/here/1, '
             'http://some.com/there/2\n'
@@ -505,16 +495,20 @@ def test_basic(self, tmpdir):
             assert dist.packages == ['pack_a', 'pack_b.subpack']
             assert dist.namespace_packages == ['pack1', 'pack2']
             assert dist.scripts == ['bin/one.py', 'bin/two.py']
-            assert dist.dependency_links == (
-                ['http://some.com/here/1', 'http://some.com/there/2']
-            )
-            assert dist.install_requires == (
-                ['docutils>=0.3', 'pack==1.1,==1.3', 'hey']
-            )
-            assert dist.setup_requires == (
-                ['docutils>=0.3', 'spack ==1.1, ==1.3', 'there']
-            )
-            assert dist.tests_require == ['mock==0.7.2', 'pytest']
+            assert dist.dependency_links == ([
+                'http://some.com/here/1',
+                'http://some.com/there/2',
+            ])
+            assert dist.install_requires == ([
+                'docutils>=0.3',
+                'pack==1.1,==1.3',
+                'hey',
+            ])
+            assert dist.setup_requires == ([
+                'docutils>=0.3',
+                'spack ==1.1, ==1.3',
+                'there',
+            ])
             assert dist.python_requires == '>=1.0, !=2.8'
             assert dist.py_modules == ['module1', 'module2']
 
@@ -541,9 +535,6 @@ def test_multiline(self, tmpdir):
             '  docutils>=0.3\n'
             '  pack ==1.1, ==1.3\n'
             '  hey\n'
-            'tests_require = \n'
-            '  mock==0.7.2\n'
-            '  pytest\n'
             'setup_requires = \n'
             '  docutils>=0.3\n'
             '  spack ==1.1, ==1.3\n'
@@ -558,19 +549,23 @@ def test_multiline(self, tmpdir):
             assert dist.packages == ['pack_a', 'pack_b.subpack']
             assert dist.namespace_packages == ['pack1', 'pack2']
             assert dist.scripts == ['bin/one.py', 'bin/two.py']
-            assert dist.dependency_links == (
-                ['http://some.com/here/1', 'http://some.com/there/2']
-            )
-            assert dist.install_requires == (
-                ['docutils>=0.3', 'pack==1.1,==1.3', 'hey']
-            )
-            assert dist.setup_requires == (
-                ['docutils>=0.3', 'spack ==1.1, ==1.3', 'there']
-            )
-            assert dist.tests_require == ['mock==0.7.2', 'pytest']
+            assert dist.dependency_links == ([
+                'http://some.com/here/1',
+                'http://some.com/there/2',
+            ])
+            assert dist.install_requires == ([
+                'docutils>=0.3',
+                'pack==1.1,==1.3',
+                'hey',
+            ])
+            assert dist.setup_requires == ([
+                'docutils>=0.3',
+                'spack ==1.1, ==1.3',
+                'there',
+            ])
 
     def test_package_dir_fail(self, tmpdir):
-        fake_env(tmpdir, '[options]\n' 'package_dir = a b\n')
+        fake_env(tmpdir, '[options]\npackage_dir = a b\n')
         with get_dist(tmpdir, parse=False) as dist:
             with pytest.raises(DistutilsOptionError):
                 dist.parse_config_files()
@@ -598,21 +593,23 @@ def test_package_data(self, tmpdir):
             }
 
     def test_packages(self, tmpdir):
-        fake_env(tmpdir, '[options]\n' 'packages = find:\n')
+        fake_env(tmpdir, '[options]\npackages = find:\n')
 
         with get_dist(tmpdir) as dist:
             assert dist.packages == ['fake_package']
 
     def test_find_directive(self, tmpdir):
-        dir_package, config = fake_env(tmpdir, '[options]\n' 'packages = find:\n')
+        dir_package, config = fake_env(tmpdir, '[options]\npackages = find:\n')
 
-        dir_sub_one, _ = make_package_dir('sub_one', dir_package)
-        dir_sub_two, _ = make_package_dir('sub_two', dir_package)
+        make_package_dir('sub_one', dir_package)
+        make_package_dir('sub_two', dir_package)
 
         with get_dist(tmpdir) as dist:
-            assert set(dist.packages) == set(
-                ['fake_package', 'fake_package.sub_two', 'fake_package.sub_one']
-            )
+            assert set(dist.packages) == set([
+                'fake_package',
+                'fake_package.sub_two',
+                'fake_package.sub_one',
+            ])
 
         config.write(
             '[options]\n'
@@ -640,11 +637,11 @@ def test_find_directive(self, tmpdir):
 
     def test_find_namespace_directive(self, tmpdir):
         dir_package, config = fake_env(
-            tmpdir, '[options]\n' 'packages = find_namespace:\n'
+            tmpdir, '[options]\npackages = find_namespace:\n'
         )
 
-        dir_sub_one, _ = make_package_dir('sub_one', dir_package)
-        dir_sub_two, _ = make_package_dir('sub_two', dir_package, ns=True)
+        make_package_dir('sub_one', dir_package)
+        make_package_dir('sub_two', dir_package, ns=True)
 
         with get_dist(tmpdir) as dist:
             assert set(dist.packages) == {
@@ -692,7 +689,7 @@ def test_extras_require(self, tmpdir):
                 'pdf': ['ReportLab>=1.2', 'RXP'],
                 'rest': ['docutils>=0.3', 'pack==1.1,==1.3'],
             }
-            assert dist.metadata.provides_extras == set(['pdf', 'rest'])
+            assert set(dist.metadata.provides_extras) == {'pdf', 'rest'}
 
     @pytest.mark.parametrize(
         "config",
@@ -707,6 +704,8 @@ def test_extras_require(self, tmpdir):
             "[options]\ninstall_requires = bar;os_name=='linux'\n",
         ],
     )
+    @pytest.mark.xfail(IS_PYPY, reason="Exceptions missing on PyPy")
+    # TODO: investigate PyPy problem
     def test_raises_accidental_env_marker_misconfig(self, config, tmpdir):
         fake_env(tmpdir, config)
         match = (
@@ -726,6 +725,8 @@ def test_raises_accidental_env_marker_misconfig(self, config, tmpdir):
             "[options]\ninstall_requires = bar;python_version<3\n",
         ],
     )
+    @pytest.mark.xfail(IS_PYPY, reason="Warnings missing on PyPy (minor issue)")
+    # TODO: investigate PyPy problem
     def test_warn_accidental_env_marker_misconfig(self, config, tmpdir):
         fake_env(tmpdir, config)
         match = (
@@ -761,7 +762,7 @@ def test_nowarn_accidental_env_marker_misconfig(self, config, tmpdir, recwarn):
         assert len(recwarn) == num_warnings
 
     def test_dash_preserved_extras_require(self, tmpdir):
-        fake_env(tmpdir, '[options.extras_require]\n' 'foo-a = foo\n' 'foo_b = test\n')
+        fake_env(tmpdir, '[options.extras_require]\nfoo-a = foo\nfoo_b = test\n')
 
         with get_dist(tmpdir) as dist:
             assert dist.extras_require == {'foo-a': ['foo'], 'foo_b': ['test']}
@@ -792,13 +793,13 @@ def test_entry_points(self, tmpdir):
         tmpdir.join('entry_points').write(expected)
 
         # From file.
-        config.write('[options]\n' 'entry_points = file: entry_points\n')
+        config.write('[options]\nentry_points = file: entry_points\n')
 
         with get_dist(tmpdir) as dist:
             assert dist.entry_points == expected
 
     def test_case_sensitive_entry_points(self, tmpdir):
-        _, config = fake_env(
+        fake_env(
             tmpdir,
             '[options.entry_points]\n'
             'GROUP1 = point1 = pack.module:func, '
@@ -911,7 +912,8 @@ def test_cmdclass(self, tmpdir):
         module_path = Path(tmpdir, "src/custom_build.py")  # auto discovery for src
         module_path.parent.mkdir(parents=True, exist_ok=True)
         module_path.write_text(
-            "from distutils.core import Command\n" "class CustomCmd(Command): pass\n"
+            "from distutils.core import Command\nclass CustomCmd(Command): pass\n",
+            encoding="utf-8",
         )
 
         setup_cfg = """
@@ -964,18 +966,13 @@ class TestExternalSetters:
     # pbr or something else setting these values.
     def _fake_distribution_init(self, dist, attrs):
         saved_dist_init(dist, attrs)
-        # see self._DISTUTUILS_UNSUPPORTED_METADATA
-        setattr(dist.metadata, 'long_description_content_type', 'text/something')
+        # see self._DISTUTILS_UNSUPPORTED_METADATA
+        dist.metadata.long_description_content_type = 'text/something'
         # Test overwrite setup() args
-        setattr(
-            dist.metadata,
-            'project_urls',
-            {
-                'Link One': 'https://example.com/one/',
-                'Link Two': 'https://example.com/two/',
-            },
-        )
-        return None
+        dist.metadata.project_urls = {
+            'Link One': 'https://example.com/one/',
+            'Link Two': 'https://example.com/two/',
+        }
 
     @patch.object(_Distribution, '__init__', autospec=True)
     def test_external_setters(self, mock_parent_init, tmpdir):
diff --git a/setuptools/tests/contexts.py b/setuptools/tests/contexts.py
index 112cdf4b28..3c931bbd4f 100644
--- a/setuptools/tests/contexts.py
+++ b/setuptools/tests/contexts.py
@@ -1,10 +1,10 @@
-import tempfile
+import contextlib
+import io
 import os
 import shutil
-import sys
-import contextlib
 import site
-import io
+import sys
+import tempfile
 
 from filelock import FileLock
 
@@ -74,20 +74,6 @@ def save_user_site_setting():
         site.ENABLE_USER_SITE = saved
 
 
-@contextlib.contextmanager
-def save_pkg_resources_state():
-    import pkg_resources
-
-    pr_state = pkg_resources.__getstate__()
-    # also save sys.path
-    sys_path = sys.path[:]
-    try:
-        yield pr_state, sys_path
-    finally:
-        sys.path[:] = sys_path
-        pkg_resources.__setstate__(pr_state)
-
-
 @contextlib.contextmanager
 def suppress_exceptions(*excs):
     try:
diff --git a/setuptools/tests/environment.py b/setuptools/tests/environment.py
index 78d73fb705..ed5499ef7d 100644
--- a/setuptools/tests/environment.py
+++ b/setuptools/tests/environment.py
@@ -1,8 +1,8 @@
 import os
-import sys
 import subprocess
+import sys
 import unicodedata
-from subprocess import Popen as _Popen, PIPE as _PIPE
+from subprocess import PIPE as _PIPE, Popen as _Popen
 
 import jaraco.envs
 
@@ -17,7 +17,7 @@ class VirtualEnv(jaraco.envs.VirtualEnv):
 
     def run(self, cmd, *args, **kwargs):
         cmd = [self.exe(cmd[0])] + cmd[1:]
-        kwargs = {"cwd": self.root, **kwargs}  # Allow overriding
+        kwargs = {"cwd": self.root, "encoding": "utf-8", **kwargs}  # Allow overriding
         # In some environments (eg. downstream distro packaging), where:
         # - tox isn't used to run tests and
         # - PYTHONPATH is set to point to a specific setuptools codebase and
@@ -66,7 +66,7 @@ def run_setup_py(cmd, pypath=None, path=None, data_stream=0, env=None):
 
     cmd = [sys.executable, "setup.py"] + list(cmd)
 
-    # http://bugs.python.org/issue8557
+    # https://bugs.python.org/issue8557
     shell = sys.platform == 'win32'
 
     try:
@@ -76,6 +76,7 @@ def run_setup_py(cmd, pypath=None, path=None, data_stream=0, env=None):
             stderr=_PIPE,
             shell=shell,
             env=env,
+            encoding="utf-8",
         )
 
         if isinstance(data_stream, tuple):
diff --git a/setuptools/tests/fixtures.py b/setuptools/tests/fixtures.py
index 524c6cbd24..20b31d4681 100644
--- a/setuptools/tests/fixtures.py
+++ b/setuptools/tests/fixtures.py
@@ -1,13 +1,20 @@
-import os
 import contextlib
-import sys
+import io
+import os
 import subprocess
+import sys
+import tarfile
+import time
 from pathlib import Path
 
-import pytest
+import jaraco.path
 import path
+import pytest
+
+from setuptools._normalization import safer_name
 
 from . import contexts, environment
+from .textwrap import DALS
 
 
 @pytest.fixture
@@ -60,60 +67,65 @@ def sample_project(tmp_path):
     return tmp_path / 'sampleproject'
 
 
+@pytest.fixture
+def sample_project_cwd(sample_project):
+    with path.Path(sample_project):
+        yield
+
+
 # sdist and wheel artifacts should be stable across a round of tests
 # so we can build them once per session and use the files as "readonly"
 
+# In the case of setuptools, building the wheel without sdist may cause
+# it to contain the `build` directory, and therefore create situations with
+# `setuptools/build/lib/build/lib/...`. To avoid that, build both artifacts at once.
+
+
+def _build_distributions(tmp_path_factory, request):
+    with contexts.session_locked_tmp_dir(
+        request, tmp_path_factory, "dist_build"
+    ) as tmp:  # pragma: no cover
+        sdist = next(tmp.glob("*.tar.gz"), None)
+        wheel = next(tmp.glob("*.whl"), None)
+        if sdist and wheel:
+            return (sdist, wheel)
+
+        # Sanity check: should not create recursive setuptools/build/lib/build/lib/...
+        assert not Path(request.config.rootdir, "build/lib/build").exists()
+
+        subprocess.check_output([
+            sys.executable,
+            "-m",
+            "build",
+            "--outdir",
+            str(tmp),
+            str(request.config.rootdir),
+        ])
+
+        # Sanity check: should not create recursive setuptools/build/lib/build/lib/...
+        assert not Path(request.config.rootdir, "build/lib/build").exists()
+
+        return next(tmp.glob("*.tar.gz")), next(tmp.glob("*.whl"))
+
 
 @pytest.fixture(scope="session")
 def setuptools_sdist(tmp_path_factory, request):
-    if os.getenv("PRE_BUILT_SETUPTOOLS_SDIST"):
-        return Path(os.getenv("PRE_BUILT_SETUPTOOLS_SDIST")).resolve()
+    prebuilt = os.getenv("PRE_BUILT_SETUPTOOLS_SDIST")
+    if prebuilt and os.path.exists(prebuilt):  # pragma: no cover
+        return Path(prebuilt).resolve()
 
-    with contexts.session_locked_tmp_dir(
-        request, tmp_path_factory, "sdist_build"
-    ) as tmp:
-        dist = next(tmp.glob("*.tar.gz"), None)
-        if dist:
-            return dist
-
-        subprocess.check_call(
-            [
-                sys.executable,
-                "-m",
-                "build",
-                "--sdist",
-                "--outdir",
-                str(tmp),
-                str(request.config.rootdir),
-            ]
-        )
-        return next(tmp.glob("*.tar.gz"))
+    sdist, _ = _build_distributions(tmp_path_factory, request)
+    return sdist
 
 
 @pytest.fixture(scope="session")
 def setuptools_wheel(tmp_path_factory, request):
-    if os.getenv("PRE_BUILT_SETUPTOOLS_WHEEL"):
-        return Path(os.getenv("PRE_BUILT_SETUPTOOLS_WHEEL")).resolve()
+    prebuilt = os.getenv("PRE_BUILT_SETUPTOOLS_WHEEL")
+    if prebuilt and os.path.exists(prebuilt):  # pragma: no cover
+        return Path(prebuilt).resolve()
 
-    with contexts.session_locked_tmp_dir(
-        request, tmp_path_factory, "wheel_build"
-    ) as tmp:
-        dist = next(tmp.glob("*.whl"), None)
-        if dist:
-            return dist
-
-        subprocess.check_call(
-            [
-                sys.executable,
-                "-m",
-                "build",
-                "--wheel",
-                "--outdir",
-                str(tmp),
-                str(request.config.rootdir),
-            ]
-        )
-        return next(tmp.glob("*.whl"))
+    _, wheel = _build_distributions(tmp_path_factory, request)
+    return wheel
 
 
 @pytest.fixture
@@ -156,3 +168,239 @@ def bare_venv(tmp_path):
     env.create_opts = ['--no-setuptools', '--no-pip', '--no-wheel', '--no-seed']
     env.ensure_env()
     return env
+
+
+def make_sdist(dist_path, files):
+    """
+    Create a simple sdist tarball at dist_path, containing the files
+    listed in ``files`` as ``(filename, content)`` tuples.
+    """
+
+    # Distributions with only one file don't play well with pip.
+    assert len(files) > 1
+    with tarfile.open(dist_path, 'w:gz') as dist:
+        for filename, content in files:
+            file_bytes = io.BytesIO(content.encode('utf-8'))
+            file_info = tarfile.TarInfo(name=filename)
+            file_info.size = len(file_bytes.getvalue())
+            file_info.mtime = int(time.time())
+            dist.addfile(file_info, fileobj=file_bytes)
+
+
+def make_trivial_sdist(dist_path, distname, version, setuptools_wheel=None):
+    """
+    Create a simple sdist tarball at dist_path, containing just a simple
+    setup.py.
+
+    If ``setuptools_wheel`` is passed, a ``pyproject.toml`` file will also
+    be generated and the passed value will be used as location for
+    setuptools (as build dependency).
+    """
+    files = [
+        (
+            'setup.py',
+            DALS(
+                f"""\
+                 import setuptools
+                 setuptools.setup(
+                     name={distname!r},
+                     version={version!r}
+                 )
+                 """
+            ),
+        ),
+        ('setup.cfg', ''),
+    ]
+
+    if setuptools_wheel:
+        files.append((
+            "pyproject.toml",
+            DALS(
+                f"""\
+                [build-system]
+                requires = ["setuptools @ {setuptools_wheel.as_uri()}"]
+                build-backend = "setuptools.build_meta"
+                """
+            ),
+        ))
+
+    make_sdist(dist_path, files)
+
+
+def make_nspkg_sdist(dist_path, distname, version):
+    """
+    Make an sdist tarball with distname and version which also contains one
+    package with the same name as distname.  The top-level package is
+    designated a namespace package).
+    """
+    # Assert that the distname contains at least one period
+    assert '.' in distname
+
+    parts = distname.split('.')
+    nspackage = parts[0]
+
+    packages = ['.'.join(parts[:idx]) for idx in range(1, len(parts) + 1)]
+
+    setup_py = DALS(
+        f"""\
+        import setuptools
+        setuptools.setup(
+            name={distname!r},
+            version={version!r},
+            packages={packages!r},
+            namespace_packages=[{nspackage!r}]
+        )
+    """
+    )
+
+    init = "__import__('pkg_resources').declare_namespace(__name__)"
+
+    files = [('setup.py', setup_py), (os.path.join(nspackage, '__init__.py'), init)]
+    for package in packages[1:]:
+        filename = os.path.join(*(package.split('.') + ['__init__.py']))
+        files.append((filename, ''))
+
+    make_sdist(dist_path, files)
+
+
+def make_python_requires_sdist(dist_path, distname, version, python_requires):
+    make_sdist(
+        dist_path,
+        [
+            (
+                'setup.py',
+                DALS(
+                    """\
+                import setuptools
+                setuptools.setup(
+                  name={name!r},
+                  version={version!r},
+                  python_requires={python_requires!r},
+                )
+                """
+                ).format(
+                    name=distname, version=version, python_requires=python_requires
+                ),
+            ),
+            ('setup.cfg', ''),
+        ],
+    )
+
+
+def create_setup_requires_package(
+    path,
+    distname='foobar',
+    version='0.1',
+    make_package=make_trivial_sdist,
+    setup_py_template=None,
+    setup_attrs=None,
+    use_setup_cfg=(),
+):
+    """Creates a source tree under path for a trivial test package that has a
+    single requirement in setup_requires--a tarball for that requirement is
+    also created and added to the dependency_links argument.
+
+    ``distname`` and ``version`` refer to the name/version of the package that
+    the test package requires via ``setup_requires``.  The name of the test
+    package itself is just 'test_pkg'.
+    """
+
+    normalized_distname = safer_name(distname)
+    test_setup_attrs = {
+        'name': 'test_pkg',
+        'version': '0.0',
+        'setup_requires': [f'{normalized_distname}=={version}'],
+        'dependency_links': [os.path.abspath(path)],
+    }
+    if setup_attrs:
+        test_setup_attrs.update(setup_attrs)
+
+    test_pkg = os.path.join(path, 'test_pkg')
+    os.mkdir(test_pkg)
+
+    # setup.cfg
+    if use_setup_cfg:
+        options = []
+        metadata = []
+        for name in use_setup_cfg:
+            value = test_setup_attrs.pop(name)
+            if name in 'name version'.split():
+                section = metadata
+            else:
+                section = options
+            if isinstance(value, (tuple, list)):
+                value = ';'.join(value)
+            section.append(f'{name}: {value}')
+        test_setup_cfg_contents = DALS(
+            """
+            [metadata]
+            {metadata}
+            [options]
+            {options}
+            """
+        ).format(
+            options='\n'.join(options),
+            metadata='\n'.join(metadata),
+        )
+    else:
+        test_setup_cfg_contents = ''
+    with open(os.path.join(test_pkg, 'setup.cfg'), 'w', encoding="utf-8") as f:
+        f.write(test_setup_cfg_contents)
+
+    # setup.py
+    if setup_py_template is None:
+        setup_py_template = DALS(
+            """\
+            import setuptools
+            setuptools.setup(**%r)
+        """
+        )
+    with open(os.path.join(test_pkg, 'setup.py'), 'w', encoding="utf-8") as f:
+        f.write(setup_py_template % test_setup_attrs)
+
+    foobar_path = os.path.join(path, f'{normalized_distname}-{version}.tar.gz')
+    make_package(foobar_path, distname, version)
+
+    return test_pkg
+
+
+@pytest.fixture
+def pbr_package(tmp_path, monkeypatch, venv):
+    files = {
+        "pyproject.toml": DALS(
+            """
+            [build-system]
+            requires = ["setuptools"]
+            build-backend = "setuptools.build_meta"
+            """
+        ),
+        "setup.py": DALS(
+            """
+            __import__('setuptools').setup(
+                pbr=True,
+                setup_requires=["pbr"],
+            )
+            """
+        ),
+        "setup.cfg": DALS(
+            """
+            [metadata]
+            name = mypkg
+
+            [files]
+            packages =
+                mypkg
+            """
+        ),
+        "mypkg": {
+            "__init__.py": "",
+            "hello.py": "print('Hello world!')",
+        },
+        "other": {"test.txt": "Another file in here."},
+    }
+    venv.run(["python", "-m", "pip", "install", "pbr"])
+    prefix = tmp_path / 'mypkg'
+    prefix.mkdir()
+    jaraco.path.build(files, prefix=prefix)
+    monkeypatch.setenv('PBR_VERSION', "0.42")
+    return prefix
diff --git a/setuptools/tests/integration/helpers.py b/setuptools/tests/integration/helpers.py
index d7d43bd606..16b1302291 100644
--- a/setuptools/tests/integration/helpers.py
+++ b/setuptools/tests/integration/helpers.py
@@ -4,20 +4,24 @@
 with setuptools, and ``run`` will always try to be as verbose as possible to
 facilitate debugging.
 """
+
+from __future__ import annotations
+
 import os
 import subprocess
 import tarfile
-from zipfile import ZipFile
+from collections.abc import Iterator
 from pathlib import Path
+from zipfile import ZipFile, ZipInfo
 
 
 def run(cmd, env=None):
     r = subprocess.run(
         cmd,
-        stdout=subprocess.PIPE,
-        stderr=subprocess.PIPE,
-        universal_newlines=True,
-        env={**os.environ, **(env or {})}
+        capture_output=True,
+        text=True,
+        encoding="utf-8",
+        env={**os.environ, **(env or {})},
         # ^-- allow overwriting instead of discarding the current env
     )
 
@@ -34,16 +38,16 @@ def run(cmd, env=None):
 class Archive:
     """Compatibility layer for ZipFile/Info and TarFile/Info"""
 
-    def __init__(self, filename):
+    def __init__(self, filename) -> None:
         self._filename = filename
         if filename.endswith("tar.gz"):
-            self._obj = tarfile.open(filename, "r:gz")
+            self._obj: tarfile.TarFile | ZipFile = tarfile.open(filename, "r:gz")
         elif filename.endswith("zip"):
             self._obj = ZipFile(filename)
         else:
             raise ValueError(f"{filename} doesn't seem to be a zip or tar.gz")
 
-    def __iter__(self):
+    def __iter__(self) -> Iterator[ZipInfo] | Iterator[tarfile.TarInfo]:
         if hasattr(self._obj, "infolist"):
             return iter(self._obj.infolist())
         return iter(self._obj)
diff --git a/setuptools/tests/integration/test_pbr.py b/setuptools/tests/integration/test_pbr.py
new file mode 100644
index 0000000000..f89e5b8b21
--- /dev/null
+++ b/setuptools/tests/integration/test_pbr.py
@@ -0,0 +1,20 @@
+import subprocess
+
+import pytest
+
+
+@pytest.mark.uses_network
+def test_pbr_integration(pbr_package, venv):
+    """Ensure pbr packages install."""
+    cmd = [
+        'python',
+        '-m',
+        'pip',
+        '-v',
+        'install',
+        '--no-build-isolation',
+        pbr_package,
+    ]
+    venv.run(cmd, stderr=subprocess.STDOUT)
+    out = venv.run(["python", "-c", "import mypkg.hello"])
+    assert "Hello world!" in out
diff --git a/setuptools/tests/integration/test_pip_install_sdist.py b/setuptools/tests/integration/test_pip_install_sdist.py
index e0e892cdb8..4e84f21832 100644
--- a/setuptools/tests/integration/test_pip_install_sdist.py
+++ b/setuptools/tests/integration/test_pip_install_sdist.py
@@ -1,3 +1,5 @@
+# https://github.com/python/mypy/issues/16936
+# mypy: disable-error-code="has-type"
 """Integration tests for setuptools that focus on building packages via pip.
 
 The idea behind these tests is not to exhaustively check all the possible
@@ -10,6 +12,7 @@
 and the associated maintenance cost (changes in the way these packages define
 their build process may require changes in the tests).
 """
+
 import json
 import os
 import shutil
@@ -24,10 +27,10 @@
 
 from .helpers import Archive, run
 
-
 pytestmark = pytest.mark.integration
 
-(LATEST,) = Enum("v", "LATEST")
+
+(LATEST,) = Enum("v", "LATEST")  # type: ignore[misc] # https://github.com/python/mypy/issues/16936
 """Default version to be checked"""
 # There are positive and negative aspects of checking the latest version of the
 # packages.
@@ -51,6 +54,8 @@
     ("pyyaml", LATEST),  # cython + custom build_ext + custom distclass
     ("charset-normalizer", LATEST),  # uses mypyc, used by aiohttp
     ("protobuf", LATEST),
+    # ("requests", LATEST),  # XXX: https://github.com/psf/requests/pull/6920
+    ("celery", LATEST),
     # When adding packages to this list, make sure they expose a `__version__`
     # attribute, or modify the tests below
 ]
@@ -99,26 +104,25 @@ def venv_python(tmp_path):
 
 
 @pytest.fixture(autouse=True)
-def _prepare(tmp_path, venv_python, monkeypatch, request):
+def _prepare(tmp_path, venv_python, monkeypatch):
     download_path = os.getenv("DOWNLOAD_PATH", str(tmp_path))
     os.makedirs(download_path, exist_ok=True)
 
     # Environment vars used for building some of the packages
     monkeypatch.setenv("USE_MYPYC", "1")
 
-    def _debug_info():
-        # Let's provide the maximum amount of information possible in the case
-        # it is necessary to debug the tests directly from the CI logs.
-        print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
-        print("Temporary directory:")
-        map(print, tmp_path.glob("*"))
-        print("Virtual environment:")
-        run([venv_python, "-m", "pip", "freeze"])
+    yield
 
-    request.addfinalizer(_debug_info)
+    # Let's provide the maximum amount of information possible in the case
+    # it is necessary to debug the tests directly from the CI logs.
+    print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
+    print("Temporary directory:")
+    map(print, tmp_path.glob("*"))
+    print("Virtual environment:")
+    run([venv_python, "-m", "pip", "freeze"])
 
 
-@pytest.mark.parametrize('package, version', EXAMPLES)
+@pytest.mark.parametrize(("package", "version"), EXAMPLES)
 @pytest.mark.uses_network
 def test_install_sdist(package, version, tmp_path, venv_python, setuptools_wheel):
     venv_pip = (venv_python, "-m", "pip")
@@ -132,7 +136,7 @@ def test_install_sdist(package, version, tmp_path, venv_python, setuptools_wheel
     # Use a virtualenv to simulate PEP 517 isolation
     # but install fresh setuptools wheel to ensure the version under development
     env = EXTRA_ENV_VARS.get(package, {})
-    run([*venv_pip, "install", "wheel", "-I", setuptools_wheel])
+    run([*venv_pip, "install", "--force-reinstall", setuptools_wheel])
     run([*venv_pip, "install", *INSTALL_OPTIONS, sdist], env)
 
     # Execute a simple script to make sure the package was installed correctly
@@ -197,13 +201,12 @@ def build_deps(package, sdist_file):
     "Manually" install them, since pip will not install build
     deps with `--no-build-isolation`.
     """
-    import tomli as toml
-
     # delay importing, since pytest discovery phase may hit this file from a
     # testenv without tomli
+    from setuptools.compat.py310 import tomllib
 
     archive = Archive(sdist_file)
-    info = toml.loads(_read_pyproject(archive))
+    info = tomllib.loads(_read_pyproject(archive))
     deps = info.get("build-system", {}).get("requires", [])
     deps += EXTRA_BUILD_DEPS.get(package, [])
     # Remove setuptools from requirements (and deduplicate)
diff --git a/setuptools/tests/namespaces.py b/setuptools/tests/namespaces.py
index 20efc485d2..248db98f97 100644
--- a/setuptools/tests/namespaces.py
+++ b/setuptools/tests/namespaces.py
@@ -1,29 +1,54 @@
+import ast
+import json
 import textwrap
+from pathlib import Path
 
 
-def build_namespace_package(tmpdir, name):
+def iter_namespace_pkgs(namespace):
+    parts = namespace.split(".")
+    for i in range(len(parts)):
+        yield ".".join(parts[: i + 1])
+
+
+def build_namespace_package(tmpdir, name, version="1.0", impl="pkg_resources"):
     src_dir = tmpdir / name
     src_dir.mkdir()
     setup_py = src_dir / 'setup.py'
-    namespace, sep, rest = name.partition('.')
+    namespace, _, rest = name.rpartition('.')
+    namespaces = list(iter_namespace_pkgs(namespace))
+    setup_args = {
+        "name": name,
+        "version": version,
+        "packages": namespaces,
+    }
+
+    if impl == "pkg_resources":
+        tmpl = '__import__("pkg_resources").declare_namespace(__name__)'
+        setup_args["namespace_packages"] = namespaces
+    elif impl == "pkgutil":
+        tmpl = '__path__ = __import__("pkgutil").extend_path(__path__, __name__)'
+    else:
+        raise ValueError(f"Cannot recognise {impl=} when creating namespaces")
+
+    args = json.dumps(setup_args, indent=4)
+    assert ast.literal_eval(args)  # ensure it is valid Python
+
     script = textwrap.dedent(
-        """
+        """\
         import setuptools
-        setuptools.setup(
-            name={name!r},
-            version="1.0",
-            namespace_packages=[{namespace!r}],
-            packages=[{namespace!r}],
-        )
+        args = {args}
+        setuptools.setup(**args)
         """
-    ).format(**locals())
+    ).format(args=args)
     setup_py.write_text(script, encoding='utf-8')
-    ns_pkg_dir = src_dir / namespace
-    ns_pkg_dir.mkdir()
-    pkg_init = ns_pkg_dir / '__init__.py'
-    tmpl = '__import__("pkg_resources").declare_namespace({namespace!r})'
-    decl = tmpl.format(**locals())
-    pkg_init.write_text(decl, encoding='utf-8')
+
+    ns_pkg_dir = Path(src_dir, namespace.replace(".", "/"))
+    ns_pkg_dir.mkdir(parents=True)
+
+    for ns in namespaces:
+        pkg_init = src_dir / ns.replace(".", "/") / '__init__.py'
+        pkg_init.write_text(tmpl, encoding='utf-8')
+
     pkg_mod = ns_pkg_dir / (rest + '.py')
     some_functionality = 'name = {rest!r}'.format(**locals())
     pkg_mod.write_text(some_functionality, encoding='utf-8')
@@ -34,7 +59,7 @@ def build_pep420_namespace_package(tmpdir, name):
     src_dir = tmpdir / name
     src_dir.mkdir()
     pyproject = src_dir / "pyproject.toml"
-    namespace, sep, rest = name.rpartition(".")
+    namespace, _, rest = name.rpartition(".")
     script = f"""\
         [build-system]
         requires = ["setuptools"]
@@ -45,7 +70,7 @@ def build_pep420_namespace_package(tmpdir, name):
         version = "3.14159"
         """
     pyproject.write_text(textwrap.dedent(script), encoding='utf-8')
-    ns_pkg_dir = src_dir / namespace.replace(".", "/")
+    ns_pkg_dir = Path(src_dir, namespace.replace(".", "/"))
     ns_pkg_dir.mkdir(parents=True)
     pkg_mod = ns_pkg_dir / (rest + ".py")
     some_functionality = f"name = {rest!r}"
diff --git a/setuptools/tests/script-with-bom.py b/setuptools/tests/script-with-bom.py
index 93d28f1600..c074d263c4 100644
--- a/setuptools/tests/script-with-bom.py
+++ b/setuptools/tests/script-with-bom.py
@@ -1 +1 @@
-result = 'passed'
+result = 'passed'
diff --git a/setuptools/tests/server.py b/setuptools/tests/server.py
deleted file mode 100644
index 6b2787c0b6..0000000000
--- a/setuptools/tests/server.py
+++ /dev/null
@@ -1,88 +0,0 @@
-"""Basic http server for tests to simulate PyPI or custom indexes
-"""
-
-import os
-import time
-import threading
-import http.server
-import urllib.parse
-import urllib.request
-
-
-class IndexServer(http.server.HTTPServer):
-    """Basic single-threaded http server simulating a package index
-
-    You can use this server in unittest like this::
-        s = IndexServer()
-        s.start()
-        index_url = s.base_url() + 'mytestindex'
-        # do some test requests to the index
-        # The index files should be located in setuptools/tests/indexes
-        s.stop()
-    """
-
-    def __init__(
-        self,
-        server_address=('', 0),
-        RequestHandlerClass=http.server.SimpleHTTPRequestHandler,
-    ):
-        http.server.HTTPServer.__init__(self, server_address, RequestHandlerClass)
-        self._run = True
-
-    def start(self):
-        self.thread = threading.Thread(target=self.serve_forever)
-        self.thread.start()
-
-    def stop(self):
-        "Stop the server"
-
-        # Let the server finish the last request and wait for a new one.
-        time.sleep(0.1)
-
-        self.shutdown()
-        self.thread.join()
-        self.socket.close()
-
-    def base_url(self):
-        port = self.server_port
-        return 'http://127.0.0.1:%s/setuptools/tests/indexes/' % port
-
-
-class RequestRecorder(http.server.BaseHTTPRequestHandler):
-    def do_GET(self):
-        requests = vars(self.server).setdefault('requests', [])
-        requests.append(self)
-        self.send_response(200, 'OK')
-
-
-class MockServer(http.server.HTTPServer, threading.Thread):
-    """
-    A simple HTTP Server that records the requests made to it.
-    """
-
-    def __init__(self, server_address=('', 0), RequestHandlerClass=RequestRecorder):
-        http.server.HTTPServer.__init__(self, server_address, RequestHandlerClass)
-        threading.Thread.__init__(self)
-        self.daemon = True
-        self.requests = []
-
-    def run(self):
-        self.serve_forever()
-
-    @property
-    def netloc(self):
-        return 'localhost:%s' % self.server_port
-
-    @property
-    def url(self):
-        return 'http://%s/' % self.netloc
-
-
-def path_to_url(path, authority=None):
-    """Convert a path to a file: URL."""
-    path = os.path.normpath(os.path.abspath(path))
-    base = 'file:'
-    if authority is not None:
-        base += '//' + authority
-    url = urllib.parse.urljoin(base, urllib.request.pathname2url(path))
-    return url
diff --git a/setuptools/tests/test_archive_util.py b/setuptools/tests/test_archive_util.py
index 7f9962440c..e3efc62889 100644
--- a/setuptools/tests/test_archive_util.py
+++ b/setuptools/tests/test_archive_util.py
@@ -1,7 +1,5 @@
-# coding: utf-8
-
-import tarfile
 import io
+import tarfile
 
 import pytest
 
diff --git a/setuptools/tests/test_bdist_deprecations.py b/setuptools/tests/test_bdist_deprecations.py
index 1b69c41858..d9d67b0616 100644
--- a/setuptools/tests/test_bdist_deprecations.py
+++ b/setuptools/tests/test_bdist_deprecations.py
@@ -1,15 +1,16 @@
-"""develop tests
-"""
+"""develop tests"""
+
 import sys
 from unittest import mock
 
 import pytest
 
-from setuptools.dist import Distribution
 from setuptools import SetuptoolsDeprecationWarning
+from setuptools.dist import Distribution
 
 
 @pytest.mark.skipif(sys.platform == 'win32', reason='non-Windows only')
+@pytest.mark.xfail(reason="bdist_rpm is long deprecated, should we remove it? #1988")
 @mock.patch('distutils.command.bdist_rpm.bdist_rpm')
 def test_bdist_rpm_warning(distutils_cmd, tmpdir_cwd):
     dist = Distribution(
diff --git a/setuptools/tests/test_bdist_egg.py b/setuptools/tests/test_bdist_egg.py
index 45dd070967..036167dd95 100644
--- a/setuptools/tests/test_bdist_egg.py
+++ b/setuptools/tests/test_bdist_egg.py
@@ -1,5 +1,5 @@
-"""develop tests
-"""
+"""develop tests"""
+
 import os
 import re
 import zipfile
@@ -17,7 +17,7 @@
 """
 
 
-@pytest.fixture(scope='function')
+@pytest.fixture
 def setup_context(tmpdir):
     with (tmpdir / 'setup.py').open('w') as f:
         f.write(SETUP_PY)
@@ -28,7 +28,9 @@ def setup_context(tmpdir):
 
 
 class Test:
-    def test_bdist_egg(self, setup_context, user_override):
+    @pytest.mark.usefixtures("user_override")
+    @pytest.mark.usefixtures("setup_context")
+    def test_bdist_egg(self):
         dist = Distribution(
             dict(
                 script_name='setup.py',
@@ -47,10 +49,12 @@ def test_bdist_egg(self, setup_context, user_override):
         assert re.match(r'foo-0.0.0-py[23].\d+.egg$', content)
 
     @pytest.mark.xfail(
-        os.environ.get('PYTHONDONTWRITEBYTECODE'),
+        os.environ.get('PYTHONDONTWRITEBYTECODE', False),
         reason="Byte code disabled",
     )
-    def test_exclude_source_files(self, setup_context, user_override):
+    @pytest.mark.usefixtures("user_override")
+    @pytest.mark.usefixtures("setup_context")
+    def test_exclude_source_files(self):
         dist = Distribution(
             dict(
                 script_name='setup.py',
diff --git a/setuptools/tests/test_bdist_wheel.py b/setuptools/tests/test_bdist_wheel.py
new file mode 100644
index 0000000000..68cc0c4d36
--- /dev/null
+++ b/setuptools/tests/test_bdist_wheel.py
@@ -0,0 +1,708 @@
+from __future__ import annotations
+
+import builtins
+import importlib
+import os.path
+import platform
+import shutil
+import stat
+import struct
+import sys
+import sysconfig
+from contextlib import suppress
+from inspect import cleandoc
+from zipfile import ZipFile
+
+import jaraco.path
+import pytest
+from packaging import tags
+
+import setuptools
+from setuptools.command.bdist_wheel import bdist_wheel, get_abi_tag
+from setuptools.dist import Distribution
+from setuptools.warnings import SetuptoolsDeprecationWarning
+
+from distutils.core import run_setup
+
+DEFAULT_FILES = {
+    "dummy_dist-1.0.dist-info/top_level.txt",
+    "dummy_dist-1.0.dist-info/METADATA",
+    "dummy_dist-1.0.dist-info/WHEEL",
+    "dummy_dist-1.0.dist-info/RECORD",
+}
+DEFAULT_LICENSE_FILES = {
+    "LICENSE",
+    "LICENSE.txt",
+    "LICENCE",
+    "LICENCE.txt",
+    "COPYING",
+    "COPYING.md",
+    "NOTICE",
+    "NOTICE.rst",
+    "AUTHORS",
+    "AUTHORS.txt",
+}
+OTHER_IGNORED_FILES = {
+    "LICENSE~",
+    "AUTHORS~",
+}
+SETUPPY_EXAMPLE = """\
+from setuptools import setup
+
+setup(
+    name='dummy_dist',
+    version='1.0',
+)
+"""
+
+
+EXAMPLES = {
+    "dummy-dist": {
+        "setup.py": SETUPPY_EXAMPLE,
+        "licenses_dir": {"DUMMYFILE": ""},
+        **dict.fromkeys(DEFAULT_LICENSE_FILES | OTHER_IGNORED_FILES, ""),
+    },
+    "simple-dist": {
+        "setup.py": cleandoc(
+            """
+            from setuptools import setup
+
+            setup(
+                name="simple.dist",
+                version="0.1",
+                description="A testing distribution \N{SNOWMAN}",
+                extras_require={"voting": ["beaglevote"]},
+            )
+            """
+        ),
+        "simpledist": "",
+    },
+    "complex-dist": {
+        "setup.py": cleandoc(
+            """
+            from setuptools import setup
+
+            setup(
+                name="complex-dist",
+                version="0.1",
+                description="Another testing distribution \N{SNOWMAN}",
+                long_description="Another testing distribution \N{SNOWMAN}",
+                author="Illustrious Author",
+                author_email="illustrious@example.org",
+                url="http://example.org/exemplary",
+                packages=["complexdist"],
+                setup_requires=["setuptools"],
+                install_requires=["quux", "splort"],
+                extras_require={"simple": ["simple.dist"]},
+                entry_points={
+                    "console_scripts": [
+                        "complex-dist=complexdist:main",
+                        "complex-dist2=complexdist:main",
+                    ],
+                },
+            )
+            """
+        ),
+        "complexdist": {"__init__.py": "def main(): return"},
+    },
+    "headers-dist": {
+        "setup.py": cleandoc(
+            """
+            from setuptools import setup
+
+            setup(
+                name="headers.dist",
+                version="0.1",
+                description="A distribution with headers",
+                headers=["header.h"],
+            )
+            """
+        ),
+        "headersdist.py": "",
+        "header.h": "",
+    },
+    "commasinfilenames-dist": {
+        "setup.py": cleandoc(
+            """
+            from setuptools import setup
+
+            setup(
+                name="testrepo",
+                version="0.1",
+                packages=["mypackage"],
+                description="A test package with commas in file names",
+                include_package_data=True,
+                package_data={"mypackage.data": ["*"]},
+            )
+            """
+        ),
+        "mypackage": {
+            "__init__.py": "",
+            "data": {"__init__.py": "", "1,2,3.txt": ""},
+        },
+        "testrepo-0.1.0": {
+            "mypackage": {"__init__.py": ""},
+        },
+    },
+    "unicode-dist": {
+        "setup.py": cleandoc(
+            """
+            from setuptools import setup
+
+            setup(
+                name="unicode.dist",
+                version="0.1",
+                description="A testing distribution \N{SNOWMAN}",
+                packages=["unicodedist"],
+                zip_safe=True,
+            )
+            """
+        ),
+        "unicodedist": {"__init__.py": "", "åäö_日本語.py": ""},
+    },
+    "utf8-metadata-dist": {
+        "setup.cfg": cleandoc(
+            """
+            [metadata]
+            name = utf8-metadata-dist
+            version = 42
+            author_email = "John X. Ãørçeč" , Γαμα קּ 東 
+            long_description = file: README.rst
+            """
+        ),
+        "README.rst": "UTF-8 描述 説明",
+    },
+    "licenses-dist": {
+        "setup.cfg": cleandoc(
+            """
+            [metadata]
+            name = licenses-dist
+            version = 1.0
+            license_files = **/LICENSE
+            """
+        ),
+        "LICENSE": "",
+        "src": {
+            "vendor": {"LICENSE": ""},
+        },
+    },
+}
+
+
+if sys.platform != "win32":
+    # ABI3 extensions don't really work on Windows
+    EXAMPLES["abi3extension-dist"] = {
+        "setup.py": cleandoc(
+            """
+            from setuptools import Extension, setup
+
+            setup(
+                name="extension.dist",
+                version="0.1",
+                description="A testing distribution \N{SNOWMAN}",
+                ext_modules=[
+                    Extension(
+                        name="extension", sources=["extension.c"], py_limited_api=True
+                    )
+                ],
+            )
+            """
+        ),
+        "setup.cfg": "[bdist_wheel]\npy_limited_api=cp32",
+        "extension.c": "#define Py_LIMITED_API 0x03020000\n#include ",
+    }
+
+
+def bdist_wheel_cmd(**kwargs):
+    """Run command in the same process so that it is easier to collect coverage"""
+    dist_obj = (
+        run_setup("setup.py", stop_after="init")
+        if os.path.exists("setup.py")
+        else Distribution({"script_name": "%%build_meta%%"})
+    )
+    dist_obj.parse_config_files()
+    cmd = bdist_wheel(dist_obj)
+    for attr, value in kwargs.items():
+        setattr(cmd, attr, value)
+    cmd.finalize_options()
+    return cmd
+
+
+def mkexample(tmp_path_factory, name):
+    basedir = tmp_path_factory.mktemp(name)
+    jaraco.path.build(EXAMPLES[name], prefix=str(basedir))
+    return basedir
+
+
+@pytest.fixture(scope="session")
+def wheel_paths(tmp_path_factory):
+    build_base = tmp_path_factory.mktemp("build")
+    dist_dir = tmp_path_factory.mktemp("dist")
+    for name in EXAMPLES:
+        example_dir = mkexample(tmp_path_factory, name)
+        build_dir = build_base / name
+        with jaraco.path.DirectoryStack().context(example_dir):
+            bdist_wheel_cmd(bdist_dir=str(build_dir), dist_dir=str(dist_dir)).run()
+
+    return sorted(str(fname) for fname in dist_dir.glob("*.whl"))
+
+
+@pytest.fixture
+def dummy_dist(tmp_path_factory):
+    return mkexample(tmp_path_factory, "dummy-dist")
+
+
+@pytest.fixture
+def licenses_dist(tmp_path_factory):
+    return mkexample(tmp_path_factory, "licenses-dist")
+
+
+def test_no_scripts(wheel_paths):
+    """Make sure entry point scripts are not generated."""
+    path = next(path for path in wheel_paths if "complex_dist" in path)
+    for entry in ZipFile(path).infolist():
+        assert ".data/scripts/" not in entry.filename
+
+
+def test_unicode_record(wheel_paths):
+    path = next(path for path in wheel_paths if "unicode_dist" in path)
+    with ZipFile(path) as zf:
+        record = zf.read("unicode_dist-0.1.dist-info/RECORD")
+
+    assert "åäö_日本語.py".encode() in record
+
+
+UTF8_PKG_INFO = """\
+Metadata-Version: 2.1
+Name: helloworld
+Version: 42
+Author-email: "John X. Ãørçeč" , Γαμα קּ 東 
+
+
+UTF-8 描述 説明
+"""
+
+
+def test_preserve_unicode_metadata(monkeypatch, tmp_path):
+    monkeypatch.chdir(tmp_path)
+    egginfo = tmp_path / "dummy_dist.egg-info"
+    distinfo = tmp_path / "dummy_dist.dist-info"
+
+    egginfo.mkdir()
+    (egginfo / "PKG-INFO").write_text(UTF8_PKG_INFO, encoding="utf-8")
+    (egginfo / "dependency_links.txt").touch()
+
+    class simpler_bdist_wheel(bdist_wheel):
+        """Avoid messing with setuptools/distutils internals"""
+
+        def __init__(self) -> None:
+            pass
+
+        @property
+        def license_paths(self):
+            return []
+
+    cmd_obj = simpler_bdist_wheel()
+    cmd_obj.egg2dist(egginfo, distinfo)
+
+    metadata = (distinfo / "METADATA").read_text(encoding="utf-8")
+    assert 'Author-email: "John X. Ãørçeč"' in metadata
+    assert "Γαμα קּ 東 " in metadata
+    assert "UTF-8 描述 説明" in metadata
+
+
+def test_licenses_default(dummy_dist, monkeypatch, tmp_path):
+    monkeypatch.chdir(dummy_dist)
+    bdist_wheel_cmd(bdist_dir=str(tmp_path)).run()
+    with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
+        license_files = {
+            "dummy_dist-1.0.dist-info/licenses/" + fname
+            for fname in DEFAULT_LICENSE_FILES
+        }
+        assert set(wf.namelist()) == DEFAULT_FILES | license_files
+
+
+def test_licenses_deprecated(dummy_dist, monkeypatch, tmp_path):
+    dummy_dist.joinpath("setup.cfg").write_text(
+        "[metadata]\nlicense_file=licenses_dir/DUMMYFILE", encoding="utf-8"
+    )
+    monkeypatch.chdir(dummy_dist)
+
+    bdist_wheel_cmd(bdist_dir=str(tmp_path)).run()
+
+    with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
+        license_files = {"dummy_dist-1.0.dist-info/licenses/licenses_dir/DUMMYFILE"}
+        assert set(wf.namelist()) == DEFAULT_FILES | license_files
+
+
+@pytest.mark.parametrize(
+    ("config_file", "config"),
+    [
+        ("setup.cfg", "[metadata]\nlicense_files=licenses_dir/*\n  LICENSE"),
+        ("setup.cfg", "[metadata]\nlicense_files=licenses_dir/*, LICENSE"),
+        (
+            "setup.py",
+            SETUPPY_EXAMPLE.replace(
+                ")", "  license_files=['licenses_dir/DUMMYFILE', 'LICENSE'])"
+            ),
+        ),
+    ],
+)
+def test_licenses_override(dummy_dist, monkeypatch, tmp_path, config_file, config):
+    dummy_dist.joinpath(config_file).write_text(config, encoding="utf-8")
+    monkeypatch.chdir(dummy_dist)
+    bdist_wheel_cmd(bdist_dir=str(tmp_path)).run()
+    with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
+        license_files = {
+            "dummy_dist-1.0.dist-info/licenses/" + fname
+            for fname in {"licenses_dir/DUMMYFILE", "LICENSE"}
+        }
+        assert set(wf.namelist()) == DEFAULT_FILES | license_files
+        metadata = wf.read("dummy_dist-1.0.dist-info/METADATA").decode("utf8")
+        assert "License-File: licenses_dir/DUMMYFILE" in metadata
+        assert "License-File: LICENSE" in metadata
+
+
+def test_licenses_preserve_folder_structure(licenses_dist, monkeypatch, tmp_path):
+    monkeypatch.chdir(licenses_dist)
+    bdist_wheel_cmd(bdist_dir=str(tmp_path)).run()
+    print(os.listdir("dist"))
+    with ZipFile("dist/licenses_dist-1.0-py3-none-any.whl") as wf:
+        default_files = {name.replace("dummy_", "licenses_") for name in DEFAULT_FILES}
+        license_files = {
+            "licenses_dist-1.0.dist-info/licenses/LICENSE",
+            "licenses_dist-1.0.dist-info/licenses/src/vendor/LICENSE",
+        }
+        assert set(wf.namelist()) == default_files | license_files
+        metadata = wf.read("licenses_dist-1.0.dist-info/METADATA").decode("utf8")
+        assert "License-File: src/vendor/LICENSE" in metadata
+        assert "License-File: LICENSE" in metadata
+
+
+def test_licenses_disabled(dummy_dist, monkeypatch, tmp_path):
+    dummy_dist.joinpath("setup.cfg").write_text(
+        "[metadata]\nlicense_files=\n", encoding="utf-8"
+    )
+    monkeypatch.chdir(dummy_dist)
+    bdist_wheel_cmd(bdist_dir=str(tmp_path)).run()
+    with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
+        assert set(wf.namelist()) == DEFAULT_FILES
+
+
+def test_build_number(dummy_dist, monkeypatch, tmp_path):
+    monkeypatch.chdir(dummy_dist)
+    bdist_wheel_cmd(bdist_dir=str(tmp_path), build_number="2").run()
+    with ZipFile("dist/dummy_dist-1.0-2-py3-none-any.whl") as wf:
+        filenames = set(wf.namelist())
+        assert "dummy_dist-1.0.dist-info/RECORD" in filenames
+        assert "dummy_dist-1.0.dist-info/METADATA" in filenames
+
+
+def test_universal_deprecated(dummy_dist, monkeypatch, tmp_path):
+    monkeypatch.chdir(dummy_dist)
+    with pytest.warns(SetuptoolsDeprecationWarning, match=".*universal is deprecated"):
+        bdist_wheel_cmd(bdist_dir=str(tmp_path), universal=True).run()
+
+    # For now we still respect the option
+    assert os.path.exists("dist/dummy_dist-1.0-py2.py3-none-any.whl")
+
+
+EXTENSION_EXAMPLE = """\
+#include 
+
+static PyMethodDef methods[] = {
+  { NULL, NULL, 0, NULL }
+};
+
+static struct PyModuleDef module_def = {
+  PyModuleDef_HEAD_INIT,
+  "extension",
+  "Dummy extension module",
+  -1,
+  methods
+};
+
+PyMODINIT_FUNC PyInit_extension(void) {
+  return PyModule_Create(&module_def);
+}
+"""
+EXTENSION_SETUPPY = """\
+from __future__ import annotations
+
+from setuptools import Extension, setup
+
+setup(
+    name="extension.dist",
+    version="0.1",
+    description="A testing distribution \N{SNOWMAN}",
+    ext_modules=[Extension(name="extension", sources=["extension.c"])],
+)
+"""
+
+
+@pytest.mark.filterwarnings(
+    "once:Config variable '.*' is unset.*, Python ABI tag may be incorrect"
+)
+def test_limited_abi(monkeypatch, tmp_path, tmp_path_factory):
+    """Test that building a binary wheel with the limited ABI works."""
+    source_dir = tmp_path_factory.mktemp("extension_dist")
+    (source_dir / "setup.py").write_text(EXTENSION_SETUPPY, encoding="utf-8")
+    (source_dir / "extension.c").write_text(EXTENSION_EXAMPLE, encoding="utf-8")
+    build_dir = tmp_path.joinpath("build")
+    dist_dir = tmp_path.joinpath("dist")
+    monkeypatch.chdir(source_dir)
+    bdist_wheel_cmd(bdist_dir=str(build_dir), dist_dir=str(dist_dir)).run()
+
+
+def test_build_from_readonly_tree(dummy_dist, monkeypatch, tmp_path):
+    basedir = str(tmp_path.joinpath("dummy"))
+    shutil.copytree(str(dummy_dist), basedir)
+    monkeypatch.chdir(basedir)
+
+    # Make the tree read-only
+    for root, _dirs, files in os.walk(basedir):
+        for fname in files:
+            os.chmod(os.path.join(root, fname), stat.S_IREAD)
+
+    bdist_wheel_cmd().run()
+
+
+@pytest.mark.parametrize(
+    ("option", "compress_type"),
+    list(bdist_wheel.supported_compressions.items()),
+    ids=list(bdist_wheel.supported_compressions),
+)
+def test_compression(dummy_dist, monkeypatch, tmp_path, option, compress_type):
+    monkeypatch.chdir(dummy_dist)
+    bdist_wheel_cmd(bdist_dir=str(tmp_path), compression=option).run()
+    with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
+        filenames = set(wf.namelist())
+        assert "dummy_dist-1.0.dist-info/RECORD" in filenames
+        assert "dummy_dist-1.0.dist-info/METADATA" in filenames
+        for zinfo in wf.filelist:
+            assert zinfo.compress_type == compress_type
+
+
+def test_wheelfile_line_endings(wheel_paths):
+    for path in wheel_paths:
+        with ZipFile(path) as wf:
+            wheelfile = next(fn for fn in wf.filelist if fn.filename.endswith("WHEEL"))
+            wheelfile_contents = wf.read(wheelfile)
+            assert b"\r" not in wheelfile_contents
+
+
+def test_unix_epoch_timestamps(dummy_dist, monkeypatch, tmp_path):
+    monkeypatch.setenv("SOURCE_DATE_EPOCH", "0")
+    monkeypatch.chdir(dummy_dist)
+    bdist_wheel_cmd(bdist_dir=str(tmp_path), build_number="2a").run()
+    with ZipFile("dist/dummy_dist-1.0-2a-py3-none-any.whl") as wf:
+        for zinfo in wf.filelist:
+            assert zinfo.date_time >= (1980, 1, 1, 0, 0, 0)  # min epoch is used
+
+
+def test_get_abi_tag_windows(monkeypatch):
+    monkeypatch.setattr(tags, "interpreter_name", lambda: "cp")
+    monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "cp313-win_amd64")
+    assert get_abi_tag() == "cp313"
+    monkeypatch.setattr(sys, "gettotalrefcount", lambda: 1, False)
+    assert get_abi_tag() == "cp313d"
+    monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "cp313t-win_amd64")
+    assert get_abi_tag() == "cp313td"
+    monkeypatch.delattr(sys, "gettotalrefcount")
+    assert get_abi_tag() == "cp313t"
+
+
+def test_get_abi_tag_pypy_old(monkeypatch):
+    monkeypatch.setattr(tags, "interpreter_name", lambda: "pp")
+    monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "pypy36-pp73")
+    assert get_abi_tag() == "pypy36_pp73"
+
+
+def test_get_abi_tag_pypy_new(monkeypatch):
+    monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "pypy37-pp73-darwin")
+    monkeypatch.setattr(tags, "interpreter_name", lambda: "pp")
+    assert get_abi_tag() == "pypy37_pp73"
+
+
+def test_get_abi_tag_graalpy(monkeypatch):
+    monkeypatch.setattr(
+        sysconfig, "get_config_var", lambda x: "graalpy231-310-native-x86_64-linux"
+    )
+    monkeypatch.setattr(tags, "interpreter_name", lambda: "graalpy")
+    assert get_abi_tag() == "graalpy231_310_native"
+
+
+def test_get_abi_tag_fallback(monkeypatch):
+    monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "unknown-python-310")
+    monkeypatch.setattr(tags, "interpreter_name", lambda: "unknown-python")
+    assert get_abi_tag() == "unknown_python_310"
+
+
+def test_platform_with_space(dummy_dist, monkeypatch):
+    """Ensure building on platforms with a space in the name succeed."""
+    monkeypatch.chdir(dummy_dist)
+    bdist_wheel_cmd(plat_name="isilon onefs").run()
+
+
+def test_data_dir_with_tag_build(monkeypatch, tmp_path):
+    """
+    Setuptools allow authors to set PEP 440's local version segments
+    using ``egg_info.tag_build``. This should be reflected not only in the
+    ``.whl`` file name, but also in the ``.dist-info`` and ``.data`` dirs.
+    See pypa/setuptools#3997.
+    """
+    monkeypatch.chdir(tmp_path)
+    files = {
+        "setup.py": """
+            from setuptools import setup
+            setup(headers=["hello.h"])
+            """,
+        "setup.cfg": """
+            [metadata]
+            name = test
+            version = 1.0
+
+            [options.data_files]
+            hello/world = file.txt
+
+            [egg_info]
+            tag_build = +what
+            tag_date = 0
+            """,
+        "file.txt": "",
+        "hello.h": "",
+    }
+    for file, content in files.items():
+        with open(file, "w", encoding="utf-8") as fh:
+            fh.write(cleandoc(content))
+
+    bdist_wheel_cmd().run()
+
+    # Ensure .whl, .dist-info and .data contain the local segment
+    wheel_path = "dist/test-1.0+what-py3-none-any.whl"
+    assert os.path.exists(wheel_path)
+    entries = set(ZipFile(wheel_path).namelist())
+    for expected in (
+        "test-1.0+what.data/headers/hello.h",
+        "test-1.0+what.data/data/hello/world/file.txt",
+        "test-1.0+what.dist-info/METADATA",
+        "test-1.0+what.dist-info/WHEEL",
+    ):
+        assert expected in entries
+
+    for not_expected in (
+        "test.data/headers/hello.h",
+        "test-1.0.data/data/hello/world/file.txt",
+        "test.dist-info/METADATA",
+        "test-1.0.dist-info/WHEEL",
+    ):
+        assert not_expected not in entries
+
+
+@pytest.mark.parametrize(
+    ("reported", "expected"),
+    [("linux-x86_64", "linux_i686"), ("linux-aarch64", "linux_armv7l")],
+)
+@pytest.mark.skipif(
+    platform.system() != "Linux", reason="Only makes sense to test on Linux"
+)
+def test_platform_linux32(reported, expected, monkeypatch):
+    monkeypatch.setattr(struct, "calcsize", lambda x: 4)
+    dist = setuptools.Distribution()
+    cmd = bdist_wheel(dist)
+    cmd.plat_name = reported
+    cmd.root_is_pure = False
+    _, _, actual = cmd.get_tag()
+    assert actual == expected
+
+
+def test_no_ctypes(monkeypatch) -> None:
+    def _fake_import(name: str, *args, **kwargs):
+        if name == "ctypes":
+            raise ModuleNotFoundError(f"No module named {name}")
+
+        return importlib.__import__(name, *args, **kwargs)
+
+    with suppress(KeyError):
+        monkeypatch.delitem(sys.modules, "wheel.macosx_libfile")
+
+    # Install an importer shim that refuses to load ctypes
+    monkeypatch.setattr(builtins, "__import__", _fake_import)
+    with pytest.raises(ModuleNotFoundError, match="No module named ctypes"):
+        import wheel.macosx_libfile  # noqa: F401
+
+    # Unload and reimport the bdist_wheel command module to make sure it won't try to
+    # import ctypes
+    monkeypatch.delitem(sys.modules, "setuptools.command.bdist_wheel")
+
+    import setuptools.command.bdist_wheel  # noqa: F401
+
+
+def test_dist_info_provided(dummy_dist, monkeypatch, tmp_path):
+    monkeypatch.chdir(dummy_dist)
+    distinfo = tmp_path / "dummy_dist.dist-info"
+
+    distinfo.mkdir()
+    (distinfo / "METADATA").write_text("name: helloworld", encoding="utf-8")
+
+    # We don't control the metadata. According to PEP-517, "The hook MAY also
+    # create other files inside this directory, and a build frontend MUST
+    # preserve".
+    (distinfo / "FOO").write_text("bar", encoding="utf-8")
+
+    bdist_wheel_cmd(bdist_dir=str(tmp_path), dist_info_dir=str(distinfo)).run()
+    expected = {
+        "dummy_dist-1.0.dist-info/FOO",
+        "dummy_dist-1.0.dist-info/RECORD",
+    }
+    with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
+        files_found = set(wf.namelist())
+    # Check that all expected files are there.
+    assert expected - files_found == set()
+    # Make sure there is no accidental egg-info bleeding into the wheel.
+    assert not [path for path in files_found if 'egg-info' in str(path)]
+
+
+def test_allow_grace_period_parent_directory_license(monkeypatch, tmp_path):
+    # Motivation: https://github.com/pypa/setuptools/issues/4892
+    # TODO: Remove this test after deprecation period is over
+    files = {
+        "LICENSE.txt": "parent license",  # <---- the license files are outside
+        "NOTICE.txt": "parent notice",
+        "python": {
+            "pyproject.toml": cleandoc(
+                """
+                [project]
+                name = "test-proj"
+                dynamic = ["version"]      # <---- testing dynamic will not break
+                [tool.setuptools.dynamic]
+                version.file = "VERSION"
+                """
+            ),
+            "setup.cfg": cleandoc(
+                """
+                [metadata]
+                license_files =
+                  ../LICENSE.txt
+                  ../NOTICE.txt
+                """
+            ),
+            "VERSION": "42",
+        },
+    }
+    jaraco.path.build(files, prefix=str(tmp_path))
+    monkeypatch.chdir(tmp_path / "python")
+    msg = "Pattern '../.*.txt' cannot contain '..'"
+    with pytest.warns(SetuptoolsDeprecationWarning, match=msg):
+        bdist_wheel_cmd().run()
+    with ZipFile("dist/test_proj-42-py3-none-any.whl") as wf:
+        files_found = set(wf.namelist())
+        expected_files = {
+            "test_proj-42.dist-info/licenses/LICENSE.txt",
+            "test_proj-42.dist-info/licenses/NOTICE.txt",
+        }
+        assert expected_files <= files_found
+
+        metadata = wf.read("test_proj-42.dist-info/METADATA").decode("utf8")
+        assert "License-File: LICENSE.txt" in metadata
+        assert "License-File: NOTICE.txt" in metadata
diff --git a/setuptools/tests/test_build.py b/setuptools/tests/test_build.py
index 4a3b11de18..f0f1d9dcf2 100644
--- a/setuptools/tests/test_build.py
+++ b/setuptools/tests/test_build.py
@@ -1,10 +1,6 @@
-from contextlib import contextmanager
-from setuptools import Command, SetuptoolsDeprecationWarning
-from setuptools.dist import Distribution
+from setuptools import Command
 from setuptools.command.build import build
-from distutils.command.build import build as distutils_build
-
-import pytest
+from setuptools.dist import Distribution
 
 
 def test_distribution_gives_setuptools_build_obj(tmpdir_cwd):
@@ -24,15 +20,6 @@ def test_distribution_gives_setuptools_build_obj(tmpdir_cwd):
     assert isinstance(dist.get_command_obj("build"), build)
 
 
-@contextmanager
-def _restore_sub_commands():
-    orig = distutils_build.sub_commands[:]
-    try:
-        yield
-    finally:
-        distutils_build.sub_commands = orig
-
-
 class Subcommand(Command):
     """Dummy command to be used in tests"""
 
@@ -44,24 +31,3 @@ def finalize_options(self):
 
     def run(self):
         raise NotImplementedError("just to check if the command runs")
-
-
-@_restore_sub_commands()
-def test_subcommand_in_distutils(tmpdir_cwd):
-    """
-    Ensure that sub commands registered in ``distutils`` run,
-    after instructing the users to migrate to ``setuptools``.
-    """
-    dist = Distribution(
-        dict(
-            packages=[],
-            cmdclass={'subcommand': Subcommand},
-        )
-    )
-    distutils_build.sub_commands.append(('subcommand', None))
-
-    warning_msg = "please use .setuptools.command.build."
-    with pytest.warns(SetuptoolsDeprecationWarning, match=warning_msg):
-        # For backward compatibility, the subcommand should run anyway:
-        with pytest.raises(NotImplementedError, match="the command runs"):
-            dist.run_command("build")
diff --git a/setuptools/tests/test_build_clib.py b/setuptools/tests/test_build_clib.py
index 2c5b956c7c..b5315df4f6 100644
--- a/setuptools/tests/test_build_clib.py
+++ b/setuptools/tests/test_build_clib.py
@@ -1,12 +1,13 @@
+import random
 from unittest import mock
 
 import pytest
 
-import random
-from distutils.errors import DistutilsSetupError
 from setuptools.command.build_clib import build_clib
 from setuptools.dist import Distribution
 
+from distutils.errors import DistutilsSetupError
+
 
 class TestBuildCLib:
     @mock.patch('setuptools.command.build_clib.newer_pairwise_group')
diff --git a/setuptools/tests/test_build_ext.py b/setuptools/tests/test_build_ext.py
index 7fd09687e1..c7b60ac32f 100644
--- a/setuptools/tests/test_build_ext.py
+++ b/setuptools/tests/test_build_ext.py
@@ -1,21 +1,22 @@
+from __future__ import annotations
+
 import os
 import sys
-import distutils.command.build_ext as orig
-from distutils.sysconfig import get_config_var
 from importlib.util import cache_from_source as _compiled_file_name
 
+import pytest
 from jaraco import path
 
 from setuptools.command.build_ext import build_ext, get_abi3_suffix
 from setuptools.dist import Distribution
-from setuptools.extension import Extension
 from setuptools.errors import CompileError
+from setuptools.extension import Extension
 
 from . import environment
 from .textwrap import DALS
 
-import pytest
-
+import distutils.command.build_ext as orig
+from distutils.sysconfig import get_config_var
 
 IS_PYPY = '__pypy__' in sys.builtin_module_names
 
@@ -98,14 +99,11 @@ def dist_with_example(self):
         ext3 = Extension("ext3", ["c-extension/ext3.c"])
 
         path.build(files)
-        dist = Distribution(
-            {
-                "script_name": "%test%",
-                "ext_modules": [ext1, ext2, ext3],
-                "package_dir": {"": "src"},
-            }
-        )
-        return dist
+        return Distribution({
+            "script_name": "%test%",
+            "ext_modules": [ext1, ext2, ext3],
+            "package_dir": {"": "src"},
+        })
 
     def test_get_outputs(self, tmpdir_cwd, monkeypatch):
         monkeypatch.setenv('SETUPTOOLS_EXT_SUFFIX', '.mp3')  # make test OS-independent
@@ -182,8 +180,8 @@ def C(file):
 
 
 class TestBuildExtInplace:
-    def get_build_ext_cmd(self, optional: bool, **opts):
-        files = {
+    def get_build_ext_cmd(self, optional: bool, **opts) -> build_ext:
+        files: dict[str, str | dict[str, dict[str, str]]] = {
             "eggs.c": "#include missingheader.h\n",
             ".build": {"lib": {}, "tmp": {}},
         }
@@ -288,8 +286,8 @@ def test_build_ext_config_handling(tmpdir_cwd):
         ),
     }
     path.build(files)
-    code, output = environment.run_setup_py(
+    code, (stdout, stderr) = environment.run_setup_py(
         cmd=['build'],
         data_stream=(0, 2),
     )
-    assert code == 0, '\nSTDOUT:\n%s\nSTDERR:\n%s' % output
+    assert code == 0, f'\nSTDOUT:\n{stdout}\nSTDERR:\n{stderr}'
diff --git a/setuptools/tests/test_build_meta.py b/setuptools/tests/test_build_meta.py
index fd7cf168ce..8237bf64a5 100644
--- a/setuptools/tests/test_build_meta.py
+++ b/setuptools/tests/test_build_meta.py
@@ -1,17 +1,23 @@
+import contextlib
+import importlib
 import os
-import sys
+import re
 import shutil
 import signal
+import sys
 import tarfile
-import importlib
-import contextlib
+import warnings
+from collections.abc import Callable
 from concurrent import futures
-import re
-from zipfile import ZipFile
 from pathlib import Path
+from typing import Any
+from zipfile import ZipFile
 
 import pytest
 from jaraco import path
+from packaging.requirements import Requirement
+
+from setuptools.warnings import SetuptoolsDeprecationWarning
 
 from .textwrap import DALS
 
@@ -30,20 +36,20 @@
 
 
 class BuildBackendBase:
-    def __init__(self, cwd='.', env={}, backend_name='setuptools.build_meta'):
+    def __init__(self, cwd='.', env=None, backend_name='setuptools.build_meta') -> None:
         self.cwd = cwd
-        self.env = env
+        self.env = env or {}
         self.backend_name = backend_name
 
 
 class BuildBackend(BuildBackendBase):
     """PEP 517 Build Backend"""
 
-    def __init__(self, *args, **kwargs):
-        super(BuildBackend, self).__init__(*args, **kwargs)
+    def __init__(self, *args, **kwargs) -> None:
+        super().__init__(*args, **kwargs)
         self.pool = futures.ProcessPoolExecutor(max_workers=1)
 
-    def __getattr__(self, name):
+    def __getattr__(self, name: str) -> Callable[..., Any]:
         """Handles arbitrary function invocations on the build backend."""
 
         def method(*args, **kw):
@@ -72,12 +78,12 @@ def _kill(self, pid):
 
 
 class BuildBackendCaller(BuildBackendBase):
-    def __init__(self, *args, **kwargs):
-        super(BuildBackendCaller, self).__init__(*args, **kwargs)
+    def __init__(self, *args, **kwargs) -> None:
+        super().__init__(*args, **kwargs)
 
         (self.backend_name, _, self.backend_obj) = self.backend_name.partition(':')
 
-    def __call__(self, name, *args, **kw):
+    def __call__(self, name, *args, **kw) -> Any:
         """Handles arbitrary function invocations on the build backend."""
         os.chdir(self.cwd)
         os.environ.update(self.env)
@@ -160,7 +166,7 @@ def run():
             # to obtain a distribution object first, and then run the distutils
             # commands later, because these files will be removed in the meantime.
 
-            with open('world.py', 'w') as f:
+            with open('world.py', 'w', encoding="utf-8") as f:
                 f.write('x = 42')
 
             try:
@@ -232,7 +238,7 @@ def build_backend(self, tmpdir, request):
 
     def test_get_requires_for_build_wheel(self, build_backend):
         actual = build_backend.get_requires_for_build_wheel()
-        expected = ['six', 'wheel']
+        expected = ['six']
         assert sorted(actual) == sorted(expected)
 
     def test_get_requires_for_build_sdist(self, build_backend):
@@ -272,14 +278,14 @@ def test_build_with_existing_file_present(self, build_type, tmpdir_cwd):
                 [metadata]
                 name = foo
                 version = file: VERSION
-            """
+                """
             ),
             'pyproject.toml': DALS(
                 """
                 [build-system]
                 requires = ["setuptools", "wheel"]
                 build-backend = "setuptools.build_meta"
-            """
+                """
             ),
         }
 
@@ -296,7 +302,7 @@ def test_build_with_existing_file_present(self, build_type, tmpdir_cwd):
         first_result = build_method(dist_dir)
 
         # Change version.
-        with open("VERSION", "wt") as version_file:
+        with open("VERSION", "wt", encoding="utf-8") as version_file:
             version_file.write("0.0.2")
 
         # Build a *second* sdist/wheel.
@@ -306,7 +312,7 @@ def test_build_with_existing_file_present(self, build_type, tmpdir_cwd):
         assert first_result != second_result
 
         # And if rebuilding the exact same sdist/wheel?
-        open(os.path.join(dist_dir, second_result), 'w').close()
+        open(os.path.join(dist_dir, second_result), 'wb').close()
         third_result = build_method(dist_dir)
         assert third_result == second_result
         assert os.path.getsize(os.path.join(dist_dir, third_result)) > 0
@@ -356,9 +362,6 @@ def test_build_with_pyproject_config(self, tmpdir, setup_script):
 
                 [tool.distutils.sdist]
                 formats = "gztar"
-
-                [tool.distutils.bdist_wheel]
-                universal = true
                 """
             ),
             "MANIFEST.in": DALS(
@@ -372,8 +375,10 @@ def test_build_with_pyproject_config(self, tmpdir, setup_script):
             "src": {
                 "foo": {
                     "__init__.py": "__version__ = '0.1'",
+                    "__init__.pyi": "__version__: str",
                     "cli.py": "def main(): print('hello world')",
                     "data.txt": "def main(): print('hello world')",
+                    "py.typed": "",
                 }
             },
         }
@@ -383,8 +388,15 @@ def test_build_with_pyproject_config(self, tmpdir, setup_script):
         build_backend = self.get_build_backend()
         with tmpdir.as_cwd():
             path.build(files)
-            sdist_path = build_backend.build_sdist("temp")
-            wheel_file = build_backend.build_wheel("temp")
+            msgs = [
+                "'tool.setuptools.license-files' is deprecated in favor of 'project.license-files'",
+                "`project.license` as a TOML table is deprecated",
+            ]
+            with warnings.catch_warnings():
+                for msg in msgs:
+                    warnings.filterwarnings("ignore", msg, SetuptoolsDeprecationWarning)
+                sdist_path = build_backend.build_sdist("temp")
+                wheel_file = build_backend.build_wheel("temp")
 
         with tarfile.open(os.path.join(tmpdir, "temp", sdist_path)) as tar:
             sdist_contents = set(tar.getnames())
@@ -392,7 +404,9 @@ def test_build_with_pyproject_config(self, tmpdir, setup_script):
         with ZipFile(os.path.join(tmpdir, "temp", wheel_file)) as zipfile:
             wheel_contents = set(zipfile.namelist())
             metadata = str(zipfile.read("foo-0.1.dist-info/METADATA"), "utf-8")
-            license = str(zipfile.read("foo-0.1.dist-info/LICENSE.txt"), "utf-8")
+            license = str(
+                zipfile.read("foo-0.1.dist-info/licenses/LICENSE.txt"), "utf-8"
+            )
             epoints = str(zipfile.read("foo-0.1.dist-info/entry_points.txt"), "utf-8")
 
         assert sdist_contents - {"foo-0.1/setup.py"} == {
@@ -406,8 +420,10 @@ def test_build_with_pyproject_config(self, tmpdir, setup_script):
             'foo-0.1/src',
             'foo-0.1/src/foo',
             'foo-0.1/src/foo/__init__.py',
+            'foo-0.1/src/foo/__init__.pyi',
             'foo-0.1/src/foo/cli.py',
             'foo-0.1/src/foo/data.txt',
+            'foo-0.1/src/foo/py.typed',
             'foo-0.1/src/foo.egg-info',
             'foo-0.1/src/foo.egg-info/PKG-INFO',
             'foo-0.1/src/foo.egg-info/SOURCES.txt',
@@ -419,9 +435,11 @@ def test_build_with_pyproject_config(self, tmpdir, setup_script):
         }
         assert wheel_contents == {
             "foo/__init__.py",
+            "foo/__init__.pyi",  # include type information by default
             "foo/cli.py",
             "foo/data.txt",  # include_package_data defaults to True
-            "foo-0.1.dist-info/LICENSE.txt",
+            "foo/py.typed",  # include type information by default
+            "foo-0.1.dist-info/licenses/LICENSE.txt",
             "foo-0.1.dist-info/METADATA",
             "foo-0.1.dist-info/WHEEL",
             "foo-0.1.dist-info/entry_points.txt",
@@ -430,18 +448,17 @@ def test_build_with_pyproject_config(self, tmpdir, setup_script):
         }
         assert license == "---- placeholder MIT license ----"
 
-        metadata = metadata.replace("(", "").replace(")", "")
-        # ^-- compatibility hack for pypa/wheel#552
-
         for line in (
             "Summary: This is a Python package",
             "License: MIT",
+            "License-File: LICENSE.txt",
             "Classifier: Intended Audience :: Developers",
             "Requires-Dist: appdirs",
-            "Requires-Dist: tomli >=1 ; extra == 'all'",
-            "Requires-Dist: importlib ; python_version == \"2.6\" and extra == 'all'",
+            "Requires-Dist: " + str(Requirement('tomli>=1 ; extra == "all"')),
+            "Requires-Dist: "
+            + str(Requirement('importlib; python_version=="2.6" and extra =="all"')),
         ):
-            assert line in metadata
+            assert line in metadata, (line, metadata)
 
         assert metadata.strip().endswith("This is a ``README``")
         assert epoints.strip() == "[console_scripts]\nfoo = foo.cli:main"
@@ -562,9 +579,9 @@ def test_build_sdist_version_change(self, build_backend):
         if not os.path.exists(setup_loc):
             setup_loc = os.path.abspath("setup.cfg")
 
-        with open(setup_loc, 'rt') as file_handler:
+        with open(setup_loc, 'rt', encoding="utf-8") as file_handler:
             content = file_handler.read()
-        with open(setup_loc, 'wt') as file_handler:
+        with open(setup_loc, 'wt', encoding="utf-8") as file_handler:
             file_handler.write(content.replace("version='0.0.0'", "version='0.0.1'"))
 
         shutil.rmtree(sdist_into_directory)
@@ -700,25 +717,6 @@ def _assert_link_tree(self, parent_dir):
         for file in files:
             assert file.is_symlink() or os.stat(file).st_nlink > 0
 
-    @pytest.mark.filterwarnings("ignore::setuptools.SetuptoolsDeprecationWarning")
-    # Since the backend is running via a process pool, in some operating systems
-    # we may have problems to make assertions based on warnings/stdout/stderr...
-    # So the best is to ignore them for the time being.
-    def test_editable_with_global_option_still_works(self, tmpdir_cwd):
-        """The usage of --global-option is now discouraged in favour of --build-option.
-        This is required to make more sense of the provided scape hatch and align with
-        previous pip behaviour. See pypa/setuptools#1928.
-        """
-        path.build({**self._simple_pyproject_example, '_meta': {}})
-        build_backend = self.get_build_backend()
-        assert not Path("build").exists()
-
-        cfg = {"--global-option": ["--mode", "strict"]}
-        build_backend.prepare_metadata_for_build_editable("_meta", cfg)
-        build_backend.build_editable("temp", cfg, "_meta")
-
-        self._assert_link_tree(next(Path("build").glob("__editable__.*")))
-
     def test_editable_without_config_settings(self, tmpdir_cwd):
         """
         Sanity check to ensure tests with --mode=strict are different from the ones
@@ -733,13 +731,17 @@ def test_editable_without_config_settings(self, tmpdir_cwd):
         build_backend.build_editable("temp")
         assert not Path("build").exists()
 
-    @pytest.mark.parametrize(
-        "config_settings",
-        [
-            {"--build-option": ["--mode", "strict"]},
-            {"editable-mode": "strict"},
-        ],
-    )
+    def test_build_wheel_inplace(self, tmpdir_cwd):
+        config_settings = {"--build-option": ["build_ext", "--inplace"]}
+        path.build(self._simple_pyproject_example)
+        build_backend = self.get_build_backend()
+        assert not Path("build").exists()
+        Path("build").mkdir()
+        build_backend.prepare_metadata_for_build_wheel("build", config_settings)
+        build_backend.build_wheel("build", config_settings)
+        assert Path("build/proj-42-py3-none-any.whl").exists()
+
+    @pytest.mark.parametrize("config_settings", [{"editable-mode": "strict"}])
     def test_editable_with_config_settings(self, tmpdir_cwd, config_settings):
         path.build({**self._simple_pyproject_example, '_meta': {}})
         assert not Path("build").exists()
@@ -749,7 +751,7 @@ def test_editable_with_config_settings(self, tmpdir_cwd, config_settings):
         self._assert_link_tree(next(Path("build").glob("__editable__.*")))
 
     @pytest.mark.parametrize(
-        'setup_literal, requirements',
+        ("setup_literal", "requirements"),
         [
             ("'foo'", ['foo']),
             ("['foo']", ['foo']),
@@ -792,14 +794,12 @@ def run():
         build_backend = self.get_build_backend()
 
         if use_wheel:
-            base_requirements = ['wheel']
             get_requires = build_backend.get_requires_for_build_wheel
         else:
-            base_requirements = []
             get_requires = build_backend.get_requires_for_build_sdist
 
         # Ensure that the build requirements are properly parsed
-        expected = sorted(base_requirements + requirements)
+        expected = sorted(requirements)
         actual = get_requires()
 
         assert expected == sorted(actual)
@@ -830,7 +830,7 @@ def test_setup_requires_with_auto_discovery(self, tmpdir_cwd):
         path.build(files)
         build_backend = self.get_build_backend()
         setup_requires = build_backend.get_requires_for_build_wheel()
-        assert setup_requires == ["wheel", "foo"]
+        assert setup_requires == ["foo"]
 
     def test_dont_install_setup_requires(self, tmpdir_cwd):
         files = {
@@ -914,7 +914,8 @@ def test_build_with_empty_setuppy(self, build_backend, build_hook):
         files = {'setup.py': ''}
         path.build(files)
 
-        with pytest.raises(ValueError, match=re.escape('No distribution was found.')):
+        msg = re.escape('No distribution was found.')
+        with pytest.raises(ValueError, match=msg):
             getattr(build_backend, build_hook)("temp")
 
 
@@ -936,33 +937,9 @@ def test_sys_argv_passthrough(self, tmpdir_cwd):
         build_backend.build_sdist("temp")
 
 
-def test_legacy_editable_install(venv, tmpdir, tmpdir_cwd):
-    pyproject = """
-    [build-system]
-    requires = ["setuptools"]
-    build-backend = "setuptools.build_meta"
-    [project]
-    name = "myproj"
-    version = "42"
-    """
-    path.build({"pyproject.toml": DALS(pyproject), "mymod.py": ""})
-
-    # First: sanity check
-    cmd = ["pip", "install", "--no-build-isolation", "-e", "."]
-    output = str(venv.run(cmd, cwd=tmpdir), "utf-8").lower()
-    assert "running setup.py develop for myproj" not in output
-    assert "created wheel for myproj" in output
-
-    # Then: real test
-    env = {**os.environ, "SETUPTOOLS_ENABLE_FEATURES": "legacy-editable"}
-    cmd = ["pip", "install", "--no-build-isolation", "-e", "."]
-    output = str(venv.run(cmd, cwd=tmpdir, env=env), "utf-8").lower()
-    assert "running setup.py develop for myproj" in output
-
-
 @pytest.mark.filterwarnings("ignore::setuptools.SetuptoolsDeprecationWarning")
 def test_sys_exit_0_in_setuppy(monkeypatch, tmp_path):
-    """Setuptools should be resilent to setup.py with ``sys.exit(0)`` (#3973)."""
+    """Setuptools should be resilient to setup.py with ``sys.exit(0)`` (#3973)."""
     monkeypatch.chdir(tmp_path)
     setuppy = """
         import sys, setuptools
@@ -971,7 +948,7 @@ def test_sys_exit_0_in_setuppy(monkeypatch, tmp_path):
         """
     (tmp_path / "setup.py").write_text(DALS(setuppy), encoding="utf-8")
     backend = BuildBackend(backend_name="setuptools.build_meta")
-    assert backend.get_requires_for_build_wheel() == ["wheel"]
+    assert backend.get_requires_for_build_wheel() == []
 
 
 def test_system_exit_in_setuppy(monkeypatch, tmp_path):
diff --git a/setuptools/tests/test_build_py.py b/setuptools/tests/test_build_py.py
index ca50ce634a..78848f7182 100644
--- a/setuptools/tests/test_build_py.py
+++ b/setuptools/tests/test_build_py.py
@@ -1,11 +1,12 @@
 import os
-import stat
 import shutil
+import stat
+import warnings
 from pathlib import Path
 from unittest.mock import Mock
 
-import pytest
 import jaraco.path
+import pytest
 
 from setuptools import SetuptoolsDeprecationWarning
 from setuptools.dist import Distribution
@@ -49,14 +50,14 @@ def test_recursive_in_package_data_glob(tmpdir_cwd):
         )
     )
     os.makedirs('path/subpath/subsubpath')
-    open('path/subpath/subsubpath/data', 'w').close()
+    open('path/subpath/subsubpath/data', 'wb').close()
 
     dist.parse_command_line()
     dist.run_commands()
 
-    assert stat.S_ISREG(
-        os.stat('build/lib/path/subpath/subsubpath/data').st_mode
-    ), "File is not included"
+    assert stat.S_ISREG(os.stat('build/lib/path/subpath/subsubpath/data').st_mode), (
+        "File is not included"
+    )
 
 
 def test_read_only(tmpdir_cwd):
@@ -77,8 +78,8 @@ def test_read_only(tmpdir_cwd):
         )
     )
     os.makedirs('pkg')
-    open('pkg/__init__.py', 'w').close()
-    open('pkg/data.dat', 'w').close()
+    open('pkg/__init__.py', 'wb').close()
+    open('pkg/data.dat', 'wb').close()
     os.chmod('pkg/__init__.py', stat.S_IREAD)
     os.chmod('pkg/data.dat', stat.S_IREAD)
     dist.parse_command_line()
@@ -108,16 +109,16 @@ def test_executable_data(tmpdir_cwd):
         )
     )
     os.makedirs('pkg')
-    open('pkg/__init__.py', 'w').close()
-    open('pkg/run-me', 'w').close()
+    open('pkg/__init__.py', 'wb').close()
+    open('pkg/run-me', 'wb').close()
     os.chmod('pkg/run-me', 0o700)
 
     dist.parse_command_line()
     dist.run_commands()
 
-    assert (
-        os.stat('build/lib/pkg/run-me').st_mode & stat.S_IEXEC
-    ), "Script is not executable"
+    assert os.stat('build/lib/pkg/run-me').st_mode & stat.S_IEXEC, (
+        "Script is not executable"
+    )
 
 
 EXAMPLE_WITH_MANIFEST = {
@@ -162,11 +163,23 @@ def test_excluded_subpackages(tmpdir_cwd):
     dist.parse_config_files()
 
     build_py = dist.get_command_obj("build_py")
+
     msg = r"Python recognizes 'mypkg\.tests' as an importable package"
-    with pytest.warns(SetuptoolsDeprecationWarning, match=msg):
+    with pytest.warns(SetuptoolsDeprecationWarning, match=msg):  # noqa: PT031
         # TODO: To fix #3260 we need some transition period to deprecate the
         # existing behavior of `include_package_data`. After the transition, we
-        # should remove the warning and fix the behaviour.
+        # should remove the warning and fix the behavior.
+
+        if os.getenv("SETUPTOOLS_USE_DISTUTILS") == "stdlib":
+            # pytest.warns reset the warning filter temporarily
+            # https://github.com/pytest-dev/pytest/issues/4011#issuecomment-423494810
+            warnings.filterwarnings(
+                "ignore",
+                "'encoding' argument not specified",
+                module="distutils.text_file",
+                # This warning is already fixed in pypa/distutils but not in stdlib
+            )
+
         build_py.finalize_options()
         build_py.run()
 
@@ -319,3 +332,149 @@ def test_get_outputs(tmpdir_cwd):
         f"{build_lib}/mypkg/sub2/nested/__init__.py": "other/__init__.py",
         f"{build_lib}/mypkg/sub2/nested/mod3.py": "other/mod3.py",
     }
+
+
+class TestTypeInfoFiles:
+    PYPROJECTS = {
+        "default_pyproject": DALS(
+            """
+            [project]
+            name = "foo"
+            version = "1"
+            """
+        ),
+        "dont_include_package_data": DALS(
+            """
+            [project]
+            name = "foo"
+            version = "1"
+
+            [tool.setuptools]
+            include-package-data = false
+            """
+        ),
+        "exclude_type_info": DALS(
+            """
+            [project]
+            name = "foo"
+            version = "1"
+
+            [tool.setuptools]
+            include-package-data = false
+
+            [tool.setuptools.exclude-package-data]
+            "*" = ["py.typed", "*.pyi"]
+            """
+        ),
+    }
+
+    EXAMPLES = {
+        "simple_namespace": {
+            "directory_structure": {
+                "foo": {
+                    "bar.pyi": "",
+                    "py.typed": "",
+                    "__init__.py": "",
+                }
+            },
+            "expected_type_files": {"foo/bar.pyi", "foo/py.typed"},
+        },
+        "nested_inside_namespace": {
+            "directory_structure": {
+                "foo": {
+                    "bar": {
+                        "py.typed": "",
+                        "mod.pyi": "",
+                    }
+                }
+            },
+            "expected_type_files": {"foo/bar/mod.pyi", "foo/bar/py.typed"},
+        },
+        "namespace_nested_inside_regular": {
+            "directory_structure": {
+                "foo": {
+                    "namespace": {
+                        "foo.pyi": "",
+                    },
+                    "__init__.pyi": "",
+                    "py.typed": "",
+                }
+            },
+            "expected_type_files": {
+                "foo/namespace/foo.pyi",
+                "foo/__init__.pyi",
+                "foo/py.typed",
+            },
+        },
+    }
+
+    @pytest.mark.parametrize(
+        "pyproject",
+        [
+            "default_pyproject",
+            pytest.param(
+                "dont_include_package_data",
+                marks=pytest.mark.xfail(reason="pypa/setuptools#4350"),
+            ),
+        ],
+    )
+    @pytest.mark.parametrize("example", EXAMPLES.keys())
+    def test_type_files_included_by_default(self, tmpdir_cwd, pyproject, example):
+        structure = {
+            **self.EXAMPLES[example]["directory_structure"],
+            "pyproject.toml": self.PYPROJECTS[pyproject],
+        }
+        expected_type_files = self.EXAMPLES[example]["expected_type_files"]
+        jaraco.path.build(structure)
+
+        build_py = get_finalized_build_py()
+        outputs = get_outputs(build_py)
+        assert expected_type_files <= outputs
+
+    @pytest.mark.parametrize("pyproject", ["exclude_type_info"])
+    @pytest.mark.parametrize("example", EXAMPLES.keys())
+    def test_type_files_can_be_excluded(self, tmpdir_cwd, pyproject, example):
+        structure = {
+            **self.EXAMPLES[example]["directory_structure"],
+            "pyproject.toml": self.PYPROJECTS[pyproject],
+        }
+        expected_type_files = self.EXAMPLES[example]["expected_type_files"]
+        jaraco.path.build(structure)
+
+        build_py = get_finalized_build_py()
+        outputs = get_outputs(build_py)
+        assert expected_type_files.isdisjoint(outputs)
+
+    def test_stub_only_package(self, tmpdir_cwd):
+        structure = {
+            "pyproject.toml": DALS(
+                """
+                [project]
+                name = "foo-stubs"
+                version = "1"
+                """
+            ),
+            "foo-stubs": {"__init__.pyi": "", "bar.pyi": ""},
+        }
+        expected_type_files = {"foo-stubs/__init__.pyi", "foo-stubs/bar.pyi"}
+        jaraco.path.build(structure)
+
+        build_py = get_finalized_build_py()
+        outputs = get_outputs(build_py)
+        assert expected_type_files <= outputs
+
+
+def get_finalized_build_py(script_name="%build_py-test%"):
+    dist = Distribution({"script_name": script_name})
+    dist.parse_config_files()
+    build_py = dist.get_command_obj("build_py")
+    build_py.finalize_options()
+    return build_py
+
+
+def get_outputs(build_py):
+    build_dir = Path(build_py.build_lib)
+    return {
+        os.path.relpath(x, build_dir).replace(os.sep, "/")
+        for x in build_py.get_outputs()
+    }
diff --git a/setuptools/tests/test_config_discovery.py b/setuptools/tests/test_config_discovery.py
index 85cb09730c..b5df8203cd 100644
--- a/setuptools/tests/test_config_discovery.py
+++ b/setuptools/tests/test_config_discovery.py
@@ -2,23 +2,24 @@
 import sys
 from configparser import ConfigParser
 from itertools import product
+from typing import cast
 
+import jaraco.path
+import pytest
+from path import Path
+
+import setuptools  # noqa: F401 # force distutils.core to be patched
 from setuptools.command.sdist import sdist
-from setuptools.dist import Distribution
 from setuptools.discovery import find_package_path, find_parent_package
+from setuptools.dist import Distribution
 from setuptools.errors import PackageDiscoveryError
 
-import setuptools  # noqa -- force distutils.core to be patched
-import distutils.core
-
-import pytest
-import jaraco.path
-from path import Path as _Path
-
 from .contexts import quiet
 from .integration.helpers import get_sdist_members, get_wheel_members, run
 from .textwrap import DALS
 
+import distutils.core
+
 
 class TestFindParentPackage:
     def test_single_package(self, tmp_path):
@@ -160,7 +161,7 @@ def test_project(self, tmp_path, circumstance):
     }
 
     @pytest.mark.parametrize(
-        "config_file, param, circumstance",
+        ("config_file", "param", "circumstance"),
         product(
             ["setup.cfg", "setup.py", "pyproject.toml"],
             ["packages", "py_modules"],
@@ -176,11 +177,11 @@ def test_purposefully_empty(self, tmp_path, config_file, param, circumstance):
         else:
             # Make sure build works with or without setup.cfg
             pyproject = self.PURPOSEFULLY_EMPY["template-pyproject.toml"]
-            (tmp_path / "pyproject.toml").write_text(pyproject)
+            (tmp_path / "pyproject.toml").write_text(pyproject, encoding="utf-8")
             template_param = param
 
         config = self.PURPOSEFULLY_EMPY[config_file].format(param=template_param)
-        (tmp_path / config_file).write_text(config)
+        (tmp_path / config_file).write_text(config, encoding="utf-8")
 
         dist = _get_dist(tmp_path, {})
         # When either parameter package or py_modules is an empty list,
@@ -190,7 +191,7 @@ def test_purposefully_empty(self, tmp_path, config_file, param, circumstance):
         assert getattr(dist, other) is None
 
     @pytest.mark.parametrize(
-        "extra_files, pkgs",
+        ("extra_files", "pkgs"),
         [
             (["venv/bin/simulate_venv"], {"pkg"}),
             (["pkg-stubs/__init__.pyi"], {"pkg", "pkg-stubs"}),
@@ -277,13 +278,13 @@ def test_build_with_discovered_name(self, tmp_path):
         _populate_project_dir(tmp_path, files, {})
         _run_build(tmp_path, "--sdist")
         # Expected distribution file
-        dist_file = tmp_path / f"dist/ns.nested.pkg-{self.DEFAULT_VERSION}.tar.gz"
+        dist_file = tmp_path / f"dist/ns_nested_pkg-{self.DEFAULT_VERSION}.tar.gz"
         assert dist_file.is_file()
 
 
 class TestWithAttrDirective:
     @pytest.mark.parametrize(
-        "folder, opts",
+        ("folder", "opts"),
         [
             ("src", {}),
             ("lib", {"packages": "find:", "packages.find": {"where": "lib"}}),
@@ -292,11 +293,13 @@ class TestWithAttrDirective:
     def test_setupcfg_metadata(self, tmp_path, folder, opts):
         files = [f"{folder}/pkg/__init__.py", "setup.cfg"]
         _populate_project_dir(tmp_path, files, opts)
-        (tmp_path / folder / "pkg/__init__.py").write_text("version = 42")
-        (tmp_path / "setup.cfg").write_text(
-            "[metadata]\nversion = attr: pkg.version\n"
-            + (tmp_path / "setup.cfg").read_text()
-        )
+
+        config = (tmp_path / "setup.cfg").read_text(encoding="utf-8")
+        overwrite = {
+            folder: {"pkg": {"__init__.py": "version = 42"}},
+            "setup.cfg": "[metadata]\nversion = attr: pkg.version\n" + config,
+        }
+        jaraco.path.build(overwrite, prefix=tmp_path)
 
         dist = _get_dist(tmp_path, {})
         assert dist.get_name() == "pkg"
@@ -304,7 +307,7 @@ def test_setupcfg_metadata(self, tmp_path, folder, opts):
         assert dist.package_dir
         package_path = find_package_path("pkg", dist.package_dir, tmp_path)
         assert os.path.exists(package_path)
-        assert folder in _Path(package_path).parts()
+        assert folder in Path(package_path).parts()
 
         _run_build(tmp_path, "--sdist")
         dist_file = tmp_path / "dist/pkg-42.tar.gz"
@@ -312,11 +315,16 @@ def test_setupcfg_metadata(self, tmp_path, folder, opts):
 
     def test_pyproject_metadata(self, tmp_path):
         _populate_project_dir(tmp_path, ["src/pkg/__init__.py"], {})
-        (tmp_path / "src/pkg/__init__.py").write_text("version = 42")
-        (tmp_path / "pyproject.toml").write_text(
-            "[project]\nname = 'pkg'\ndynamic = ['version']\n"
-            "[tool.setuptools.dynamic]\nversion = {attr = 'pkg.version'}\n"
-        )
+
+        overwrite = {
+            "src": {"pkg": {"__init__.py": "version = 42"}},
+            "pyproject.toml": (
+                "[project]\nname = 'pkg'\ndynamic = ['version']\n"
+                "[tool.setuptools.dynamic]\nversion = {attr = 'pkg.version'}\n"
+            ),
+        }
+        jaraco.path.build(overwrite, prefix=tmp_path)
+
         dist = _get_dist(tmp_path, {})
         assert dist.get_version() == "42"
         assert dist.package_dir == {"": "src"}
@@ -354,7 +362,7 @@ def _simulate_package_with_extension(self, tmp_path):
             ]
             setup(ext_modules=ext_modules)
         """
-        (tmp_path / "setup.py").write_text(DALS(setup_script))
+        (tmp_path / "setup.py").write_text(DALS(setup_script), encoding="utf-8")
 
     def test_skip_discovery_with_setupcfg_metadata(self, tmp_path):
         """Ensure that auto-discovery is not triggered when the project is based on
@@ -367,14 +375,14 @@ def test_skip_discovery_with_setupcfg_metadata(self, tmp_path):
             requires = []
             build-backend = 'setuptools.build_meta'
         """
-        (tmp_path / "pyproject.toml").write_text(DALS(pyproject))
+        (tmp_path / "pyproject.toml").write_text(DALS(pyproject), encoding="utf-8")
 
         setupcfg = """
             [metadata]
             name = proj
             version = 42
         """
-        (tmp_path / "setup.cfg").write_text(DALS(setupcfg))
+        (tmp_path / "setup.cfg").write_text(DALS(setupcfg), encoding="utf-8")
 
         dist = _get_dist(tmp_path, {})
         assert dist.get_name() == "proj"
@@ -399,7 +407,7 @@ def test_dont_skip_discovery_with_pyproject_metadata(self, tmp_path):
             name = 'proj'
             version = '42'
         """
-        (tmp_path / "pyproject.toml").write_text(DALS(pyproject))
+        (tmp_path / "pyproject.toml").write_text(DALS(pyproject), encoding="utf-8")
         with pytest.raises(PackageDiscoveryError, match="multiple (packages|modules)"):
             _get_dist(tmp_path, {})
 
@@ -416,7 +424,7 @@ def _simulate_package_with_data_files(self, tmp_path, src_root):
         manifest = """
             global-include *.py *.txt
         """
-        (tmp_path / "MANIFEST.in").write_text(DALS(manifest))
+        (tmp_path / "MANIFEST.in").write_text(DALS(manifest), encoding="utf-8")
 
     EXAMPLE_SETUPCFG = """
     [metadata]
@@ -438,7 +446,7 @@ def _simulate_package_with_data_files(self, tmp_path, src_root):
     """
 
     @pytest.mark.parametrize(
-        "src_root, files",
+        ("src_root", "files"),
         [
             (".", {"setup.cfg": DALS(EXAMPLE_SETUPCFG)}),
             (".", {"pyproject.toml": DALS(EXAMPLE_PYPROJECT)}),
@@ -564,9 +572,12 @@ def _populate_project_dir(root, files, options):
     # NOTE: Currently pypa/build will refuse to build the project if no
     # `pyproject.toml` or `setup.py` is found. So it is impossible to do
     # completely "config-less" projects.
-    (root / "setup.py").write_text("import setuptools\nsetuptools.setup()")
-    (root / "README.md").write_text("# Example Package")
-    (root / "LICENSE").write_text("Copyright (c) 2018")
+    basic = {
+        "setup.py": "import setuptools\nsetuptools.setup()",
+        "README.md": "# Example Package",
+        "LICENSE": "Copyright (c) 2018",
+    }
+    jaraco.path.build(basic, prefix=root)
     _write_setupcfg(root, options)
     paths = (root / f for f in files)
     for path in paths:
@@ -591,10 +602,10 @@ def _write_setupcfg(root, options):
             setupcfg["options"][key] = "\n" + str_value
         else:
             setupcfg["options"][key] = str(value)
-    with open(root / "setup.cfg", "w") as f:
+    with open(root / "setup.cfg", "w", encoding="utf-8") as f:
         setupcfg.write(f)
     print("~~~~~ setup.cfg ~~~~~")
-    print((root / "setup.cfg").read_text())
+    print((root / "setup.cfg").read_text(encoding="utf-8"))
 
 
 def _run_build(path, *flags):
@@ -607,14 +618,17 @@ def _get_dist(dist_path, attrs):
 
     script = dist_path / 'setup.py'
     if script.exists():
-        with _Path(dist_path):
-            dist = distutils.core.run_setup("setup.py", {}, stop_after="init")
+        with Path(dist_path):
+            dist = cast(
+                Distribution,
+                distutils.core.run_setup("setup.py", {}, stop_after="init"),
+            )
     else:
         dist = Distribution(attrs)
 
     dist.src_root = root
     dist.script_name = "setup.py"
-    with _Path(dist_path):
+    with Path(dist_path):
         dist.parse_config_files()
 
     dist.set_defaults()
@@ -627,7 +641,7 @@ def _run_sdist_programatically(dist_path, attrs):
     cmd.ensure_finalized()
     assert cmd.distribution.packages or cmd.distribution.py_modules
 
-    with quiet(), _Path(dist_path):
+    with quiet(), Path(dist_path):
         cmd.run()
 
     return dist, cmd
diff --git a/setuptools/tests/test_core_metadata.py b/setuptools/tests/test_core_metadata.py
index 8c2483f26e..5ec6df3dfe 100644
--- a/setuptools/tests/test_core_metadata.py
+++ b/setuptools/tests/test_core_metadata.py
@@ -1,17 +1,26 @@
+from __future__ import annotations
+
 import functools
 import io
-import importlib
 from email import message_from_string
-
+from email.generator import Generator
+from email.message import EmailMessage
+from email.parser import Parser
+from email.policy import EmailPolicy
+from inspect import cleandoc
+from pathlib import Path
+from unittest.mock import Mock
+
+import jaraco.path
 import pytest
-
 from packaging.metadata import Metadata
 
-from setuptools import sic, _reqs
-from setuptools.dist import Distribution
+from setuptools import sic
 from setuptools._core_metadata import rfc822_escape, rfc822_unescape
-from setuptools.command.egg_info import egg_info, write_requirements
+from setuptools.config import expand, setupcfg
+from setuptools.dist import Distribution
 
+from .config.downloads import retrieve_file, urls_from_file
 
 EXAMPLE_BASE_INFO = dict(
     name="package",
@@ -25,7 +34,7 @@
 
 
 @pytest.mark.parametrize(
-    'content, result',
+    ("content", "result"),
     (
         pytest.param(
             "Just a single line",
@@ -63,7 +72,7 @@ def __read_test_cases():
 
     params = functools.partial(dict, base)
 
-    test_cases = [
+    return [
         ('Metadata version 1.0', params()),
         (
             'Metadata Version 1.0: Short long description',
@@ -155,10 +164,8 @@ def __read_test_cases():
         ),
     ]
 
-    return test_cases
-
 
-@pytest.mark.parametrize('name,attrs', __read_test_cases())
+@pytest.mark.parametrize(("name", "attrs"), __read_test_cases())
 def test_read_metadata(name, attrs):
     dist = Distribution(attrs)
     metadata_out = dist.metadata
@@ -192,7 +199,7 @@ def test_read_metadata(name, attrs):
         ('requires', dist_class.get_requires),
         ('classifiers', dist_class.get_classifiers),
         ('project_urls', lambda s: getattr(s, 'project_urls', {})),
-        ('provides_extras', lambda s: getattr(s, 'provides_extras', set())),
+        ('provides_extras', lambda s: getattr(s, 'provides_extras', {})),
     ]
 
     for attr, getter in tested_attrs:
@@ -208,7 +215,7 @@ def merge_dicts(d1, d2):
 
         return d1
 
-    test_cases = [
+    return [
         ('No author, no maintainer', attrs.copy()),
         (
             'Author (no e-mail), no maintainer',
@@ -266,10 +273,8 @@ def merge_dicts(d1, d2):
         ('Maintainer unicode', merge_dicts(attrs, {'maintainer': 'Jan Łukasiewicz'})),
     ]
 
-    return test_cases
 
-
-@pytest.mark.parametrize('name,attrs', __maintainer_test_cases())
+@pytest.mark.parametrize(("name", "attrs"), __maintainer_test_cases())
 def test_maintainer_author(name, attrs, tmpdir):
     tested_keys = {
         'author': 'Author',
@@ -285,7 +290,7 @@ def test_maintainer_author(name, attrs, tmpdir):
 
     dist.metadata.write_pkg_info(fn_s)
 
-    with io.open(str(fn.join('PKG-INFO')), 'r', encoding='utf-8') as f:
+    with open(str(fn.join('PKG-INFO')), 'r', encoding='utf-8') as f:
         pkg_info = f.read()
 
     assert _valid_metadata(pkg_info)
@@ -305,89 +310,239 @@ def test_maintainer_author(name, attrs, tmpdir):
             for line in pkg_lines:
                 assert not line.startswith(fkey + ':')
         else:
-            line = '%s: %s' % (fkey, val)
+            line = f'{fkey}: {val}'
             assert line in pkg_lines_set
 
 
-def test_parity_with_metadata_from_pypa_wheel(tmp_path):
-    attrs = dict(
-        **EXAMPLE_BASE_INFO,
-        # Example with complex requirement definition
-        python_requires=">=3.8",
-        install_requires="""
-        packaging==23.0
-        ordered-set==3.1.1
-        more-itertools==8.8.0; extra == "other"
-        jaraco.text==3.7.0
-        importlib-resources==5.10.2; python_version<"3.8"
-        importlib-metadata==6.0.0 ; python_version<"3.8"
-        colorama>=0.4.4; sys_platform == "win32"
-        """,
-        extras_require={
-            "testing": """
-                pytest >= 6
-                pytest-checkdocs >= 2.4
-                pytest-flake8 ; \\
-                        # workaround for tholo/pytest-flake8#87
-                        python_version < "3.12"
-                ini2toml[lite]>=0.9
-                """,
-            "other": [],
-        }
+class TestParityWithMetadataFromPyPaWheel:
+    def base_example(self):
+        attrs = dict(
+            **EXAMPLE_BASE_INFO,
+            # Example with complex requirement definition
+            python_requires=">=3.8",
+            install_requires="""
+            packaging==23.2
+            more-itertools==8.8.0; extra == "other"
+            jaraco.text==3.7.0
+            importlib-resources==5.10.2; python_version<"3.8"
+            importlib-metadata==6.0.0 ; python_version<"3.8"
+            colorama>=0.4.4; sys_platform == "win32"
+            """,
+            extras_require={
+                "testing": """
+                    pytest >= 6
+                    pytest-checkdocs >= 2.4
+                    tomli ; \\
+                            # Using stdlib when possible
+                            python_version < "3.11"
+                    ini2toml[lite]>=0.9
+                    """,
+                "other": [],
+            },
+        )
+        # Generate a PKG-INFO file using setuptools
+        return Distribution(attrs)
+
+    def test_requires_dist(self, tmp_path):
+        dist = self.base_example()
+        pkg_info = _get_pkginfo(dist)
+        assert _valid_metadata(pkg_info)
+
+        # Ensure Requires-Dist is present
+        expected = [
+            'Metadata-Version:',
+            'Requires-Python: >=3.8',
+            'Provides-Extra: other',
+            'Provides-Extra: testing',
+            'Requires-Dist: tomli; python_version < "3.11" and extra == "testing"',
+            'Requires-Dist: more-itertools==8.8.0; extra == "other"',
+            'Requires-Dist: ini2toml[lite]>=0.9; extra == "testing"',
+        ]
+        for line in expected:
+            assert line in pkg_info
+
+    HERE = Path(__file__).parent
+    EXAMPLES_FILE = HERE / "config/setupcfg_examples.txt"
+
+    @pytest.fixture(params=[None, *urls_from_file(EXAMPLES_FILE)])
+    def dist(self, request, monkeypatch, tmp_path):
+        """Example of distribution with arbitrary configuration"""
+        monkeypatch.chdir(tmp_path)
+        monkeypatch.setattr(expand, "read_attr", Mock(return_value="0.42"))
+        monkeypatch.setattr(expand, "read_files", Mock(return_value="hello world"))
+        monkeypatch.setattr(
+            Distribution, "_finalize_license_files", Mock(return_value=None)
+        )
+        if request.param is None:
+            yield self.base_example()
+        else:
+            # Real-world usage
+            config = retrieve_file(request.param)
+            yield setupcfg.apply_configuration(Distribution({}), config)
+
+    @pytest.mark.uses_network
+    def test_pkg_info_roundtrip(self, tmp_path, dist):
+        """Ensure PKG-INFO round trips according to pypa/wheel's methodology"""
+        # Generate an simplified "egg-info" with PKG-INFO
+        pkg_info = _get_pkginfo(dist)
+
+        # Emulate the way old versions of wheel.bdist_wheel used to parse and regenerate
+        # the message, then ensures the metadata generated by setuptools is compatible.
+        with io.StringIO(pkg_info) as buffer:
+            msg = Parser(EmailMessage).parse(buffer)
+
+        serialization_policy = EmailPolicy(
+            utf8=True,
+            mangle_from_=False,
+            max_line_length=0,
+        )
+        with io.BytesIO() as buffer:
+            out = io.TextIOWrapper(buffer, encoding="utf-8")
+            Generator(out, policy=serialization_policy).flatten(msg)
+            out.flush()
+            regenerated = buffer.getvalue()
+
+        raw_metadata = bytes(pkg_info, "utf-8")
+        # Normalise newlines to avoid test errors on Windows:
+        raw_metadata = b"\n".join(raw_metadata.splitlines())
+        regenerated = b"\n".join(regenerated.splitlines())
+        assert regenerated == raw_metadata
+
+
+class TestPEP643:
+    STATIC_CONFIG = {
+        "setup.cfg": cleandoc(
+            """
+            [metadata]
+            name = package
+            version = 0.0.1
+            author = Foo Bar
+            author_email = foo@bar.net
+            long_description = Long
+                               description
+            description = Short description
+            keywords = one, two
+            platforms = abcd
+            [options]
+            install_requires = requests
+            """
+        ),
+        "pyproject.toml": cleandoc(
+            """
+            [project]
+            name = "package"
+            version = "0.0.1"
+            authors = [
+              {name = "Foo Bar", email = "foo@bar.net"}
+            ]
+            description = "Short description"
+            readme = {text = "Long\\ndescription", content-type = "text/plain"}
+            keywords = ["one", "two"]
+            dependencies = ["requests"]
+            license = "AGPL-3.0-or-later"
+            [tool.setuptools]
+            provides = ["abcd"]
+            obsoletes = ["abcd"]
+            """
+        ),
+    }
+
+    @pytest.mark.parametrize("file", STATIC_CONFIG.keys())
+    def test_static_config_has_no_dynamic(self, file, tmpdir_cwd):
+        Path(file).write_text(self.STATIC_CONFIG[file], encoding="utf-8")
+        metadata = _get_metadata()
+        assert metadata.get_all("Dynamic") is None
+        assert metadata.get_all("dynamic") is None
+
+    @pytest.mark.parametrize("file", STATIC_CONFIG.keys())
+    @pytest.mark.parametrize(
+        "fields",
+        [
+            # Single dynamic field
+            {"requires-python": ("python_requires", ">=3.12")},
+            {"author-email": ("author_email", "snoopy@peanuts.com")},
+            {"keywords": ("keywords", ["hello", "world"])},
+            {"platform": ("platforms", ["abcd"])},
+            # Multiple dynamic fields
+            {
+                "summary": ("description", "hello world"),
+                "description": ("long_description", "bla bla bla bla"),
+                "requires-dist": ("install_requires", ["hello-world"]),
+            },
+        ],
     )
-    # Generate a PKG-INFO file using setuptools
-    dist = Distribution(attrs)
-    with io.StringIO() as fp:
-        dist.metadata.write_pkg_file(fp)
-        pkg_info = fp.getvalue()
+    def test_modified_fields_marked_as_dynamic(self, file, fields, tmpdir_cwd):
+        # We start with a static config
+        Path(file).write_text(self.STATIC_CONFIG[file], encoding="utf-8")
+        dist = _makedist()
+
+        # ... but then we simulate the effects of a plugin modifying the distribution
+        for attr, value in fields.values():
+            # `dist` and `dist.metadata` are complicated...
+            # Some attributes work when set on `dist`, others on `dist.metadata`...
+            # Here we set in both just in case (this also avoids calling `_finalize_*`)
+            setattr(dist, attr, value)
+            setattr(dist.metadata, attr, value)
+
+        # Then we should be able to list the modified fields as Dynamic
+        metadata = _get_metadata(dist)
+        assert set(metadata.get_all("Dynamic")) == set(fields)
+
+    @pytest.mark.parametrize(
+        "extra_toml",
+        [
+            "# Let setuptools autofill license-files",
+            "license-files = ['LICENSE*', 'AUTHORS*', 'NOTICE']",
+        ],
+    )
+    def test_license_files_dynamic(self, extra_toml, tmpdir_cwd):
+        # For simplicity (and for the time being) setuptools is not making
+        # any special handling to guarantee `License-File` is considered static.
+        # Instead we rely in the fact that, although suboptimal, it is OK to have
+        # it as dynamics, as per:
+        # https://github.com/pypa/setuptools/issues/4629#issuecomment-2331233677
+        files = {
+            "pyproject.toml": self.STATIC_CONFIG["pyproject.toml"].replace(
+                'license = "AGPL-3.0-or-later"',
+                f"dynamic = ['license']\n{extra_toml}",
+            ),
+            "LICENSE.md": "--- mock license ---",
+            "NOTICE": "--- mock notice ---",
+            "AUTHORS.txt": "--- me ---",
+        }
+        # Sanity checks:
+        assert extra_toml in files["pyproject.toml"]
+        assert 'license = "AGPL-3.0-or-later"' not in extra_toml
+
+        jaraco.path.build(files)
+        dist = _makedist(license_expression="AGPL-3.0-or-later")
+        metadata = _get_metadata(dist)
+        assert set(metadata.get_all("Dynamic")) == {
+            'license-file',
+            'license-expression',
+        }
+        assert metadata.get("License-Expression") == "AGPL-3.0-or-later"
+        assert set(metadata.get_all("License-File")) == {
+            "NOTICE",
+            "AUTHORS.txt",
+            "LICENSE.md",
+        }
 
-    assert _valid_metadata(pkg_info)
 
-    # Ensure Requires-Dist is present
-    expected = [
-        'Metadata-Version:',
-        'Requires-Python: >=3.8',
-        'Provides-Extra: other',
-        'Provides-Extra: testing',
-        'Requires-Dist: pytest-flake8; python_version < "3.12" and extra == "testing"',
-        'Requires-Dist: more-itertools==8.8.0; extra == "other"',
-        'Requires-Dist: ini2toml[lite]>=0.9; extra == "testing"',
-    ]
-    for line in expected:
-        assert line in pkg_info
+def _makedist(**attrs):
+    dist = Distribution(attrs)
+    dist.parse_config_files()
+    return dist
 
-    # Generate a METADATA file using pypa/wheel for comparisson
-    wheel_metadata = importlib.import_module("wheel.metadata")
-    pkginfo_to_metadata = getattr(wheel_metadata, "pkginfo_to_metadata", None)
 
-    if pkginfo_to_metadata is None:
-        pytest.xfail(
-            "wheel.metadata.pkginfo_to_metadata is undefined, "
-            "(this is likely to be caused by API changes in pypa/wheel"
-        )
+def _get_pkginfo(dist: Distribution):
+    with io.StringIO() as fp:
+        dist.metadata.write_pkg_file(fp)
+        return fp.getvalue()
+
 
-    # Generate an simplified "egg-info" dir for pypa/wheel to convert
-    egg_info_dir = tmp_path / "pkg.egg-info"
-    egg_info_dir.mkdir(parents=True)
-    (egg_info_dir / "PKG-INFO").write_text(pkg_info, encoding="utf-8")
-    write_requirements(egg_info(dist), egg_info_dir, egg_info_dir / "requires.txt")
-
-    # Get pypa/wheel generated METADATA but normalize requirements formatting
-    metadata_msg = pkginfo_to_metadata(egg_info_dir, egg_info_dir / "PKG-INFO")
-    metadata_deps = set(_reqs.parse(metadata_msg.get_all("Requires-Dist")))
-    metadata_extras = set(metadata_msg.get_all("Provides-Extra"))
-    del metadata_msg["Requires-Dist"]
-    del metadata_msg["Provides-Extra"]
-    pkg_info_msg = message_from_string(pkg_info)
-    pkg_info_deps = set(_reqs.parse(pkg_info_msg.get_all("Requires-Dist")))
-    pkg_info_extras = set(pkg_info_msg.get_all("Provides-Extra"))
-    del pkg_info_msg["Requires-Dist"]
-    del pkg_info_msg["Provides-Extra"]
-
-    # Compare setuptools PKG-INFO x pypa/wheel METADATA
-    assert metadata_msg.as_string() == pkg_info_msg.as_string()
-    assert metadata_deps == pkg_info_deps
-    assert metadata_extras == pkg_info_extras
+def _get_metadata(dist: Distribution | None = None):
+    return message_from_string(_get_pkginfo(dist or _makedist()))
 
 
 def _valid_metadata(text: str) -> bool:
diff --git a/setuptools/tests/test_dep_util.py b/setuptools/tests/test_dep_util.py
deleted file mode 100644
index e5027c1020..0000000000
--- a/setuptools/tests/test_dep_util.py
+++ /dev/null
@@ -1,30 +0,0 @@
-from setuptools.dep_util import newer_pairwise_group
-import os
-import pytest
-
-
-@pytest.fixture
-def groups_target(tmpdir):
-    """Sets up some older sources, a target and newer sources.
-    Returns a 3-tuple in this order.
-    """
-    creation_order = ['older.c', 'older.h', 'target.o', 'newer.c', 'newer.h']
-    mtime = 0
-
-    for i in range(len(creation_order)):
-        creation_order[i] = os.path.join(str(tmpdir), creation_order[i])
-        with open(creation_order[i], 'w'):
-            pass
-
-        # make sure modification times are sequential
-        os.utime(creation_order[i], (mtime, mtime))
-        mtime += 1
-
-    return creation_order[:2], creation_order[2], creation_order[3:]
-
-
-def test_newer_pairwise_group(groups_target):
-    older = newer_pairwise_group([groups_target[0]], [groups_target[1]])
-    newer = newer_pairwise_group([groups_target[2]], [groups_target[1]])
-    assert older == ([], [])
-    assert newer == ([groups_target[2]], [groups_target[1]])
diff --git a/setuptools/tests/test_develop.py b/setuptools/tests/test_develop.py
index 3ed276a460..c2a3be28ba 100644
--- a/setuptools/tests/test_develop.py
+++ b/setuptools/tests/test_develop.py
@@ -1,19 +1,15 @@
-"""develop tests
-"""
+"""develop tests"""
 
 import os
-import sys
-import subprocess
 import platform
-
-from setuptools.command import test
+import subprocess
+import sys
 
 import pytest
 
-from setuptools.command.develop import develop
-from setuptools.dist import Distribution
-from . import contexts
-from . import namespaces
+from setuptools._path import paths_on_pythonpath
+
+from . import contexts, namespaces
 
 SETUP_PY = """\
 from setuptools import setup
@@ -52,55 +48,6 @@ def test_env(tmpdir, temp_user):
         yield target
 
 
-class TestDevelop:
-    in_virtualenv = hasattr(sys, 'real_prefix')
-    in_venv = hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix
-
-    def test_console_scripts(self, tmpdir):
-        """
-        Test that console scripts are installed and that they reference
-        only the project by name and not the current version.
-        """
-        pytest.skip(
-            "TODO: needs a fixture to cause 'develop' "
-            "to be invoked without mutating environment."
-        )
-        settings = dict(
-            name='foo',
-            packages=['foo'],
-            version='0.0',
-            entry_points={
-                'console_scripts': [
-                    'foocmd = foo:foo',
-                ],
-            },
-        )
-        dist = Distribution(settings)
-        dist.script_name = 'setup.py'
-        cmd = develop(dist)
-        cmd.ensure_finalized()
-        cmd.install_dir = tmpdir
-        cmd.run()
-        # assert '0.0' not in foocmd_text
-
-
-class TestResolver:
-    """
-    TODO: These tests were written with a minimal understanding
-    of what _resolve_setup_path is intending to do. Come up with
-    more meaningful cases that look like real-world scenarios.
-    """
-
-    def test_resolve_setup_path_cwd(self):
-        assert develop._resolve_setup_path('.', '.', '.') == '.'
-
-    def test_resolve_setup_path_one_dir(self):
-        assert develop._resolve_setup_path('pkgs', '.', 'pkgs') == '../'
-
-    def test_resolve_setup_path_one_dir_trailing_slash(self):
-        assert develop._resolve_setup_path('pkgs/', '.', 'pkgs') == '../'
-
-
 class TestNamespaces:
     @staticmethod
     def install_develop(src_dir, target):
@@ -112,9 +59,10 @@ def install_develop(src_dir, target):
             str(target),
         ]
         with src_dir.as_cwd():
-            with test.test.paths_on_pythonpath([str(target)]):
+            with paths_on_pythonpath([str(target)]):
                 subprocess.check_call(develop_cmd)
 
+    @pytest.mark.xfail(reason="pkg_resources has been removed")
     @pytest.mark.skipif(
         bool(os.environ.get("APPVEYOR")),
         reason="https://github.com/pypa/setuptools/issues/851",
@@ -123,6 +71,7 @@ def install_develop(src_dir, target):
         platform.python_implementation() == 'PyPy',
         reason="https://github.com/pypa/setuptools/issues/1202",
     )
+    @pytest.mark.uses_network
     def test_namespace_package_importable(self, tmpdir):
         """
         Installing two packages sharing the same namespace, one installed
@@ -151,7 +100,7 @@ def test_namespace_package_importable(self, tmpdir):
             '-c',
             'import myns.pkgA; import myns.pkgB',
         ]
-        with test.test.paths_on_pythonpath([str(target)]):
+        with paths_on_pythonpath([str(target)]):
             subprocess.check_call(try_import)
 
         # additionally ensure that pkg_resources import works
@@ -160,5 +109,5 @@ def test_namespace_package_importable(self, tmpdir):
             '-c',
             'import pkg_resources',
         ]
-        with test.test.paths_on_pythonpath([str(target)]):
+        with paths_on_pythonpath([str(target)]):
             subprocess.check_call(pkg_resources_imp)
diff --git a/setuptools/tests/test_dist.py b/setuptools/tests/test_dist.py
index 0caaef6578..9685dcd7cb 100644
--- a/setuptools/tests/test_dist.py
+++ b/setuptools/tests/test_dist.py
@@ -1,23 +1,21 @@
-import collections
-import re
 import os
-import urllib.request
+import re
 import urllib.parse
-from distutils.errors import DistutilsSetupError
-from setuptools.dist import (
-    check_package_data,
-    check_specifier,
-)
+import urllib.request
+
+import pytest
+
 from setuptools import Distribution
+from setuptools.dist import check_package_data, check_specifier
 
-from .textwrap import DALS
-from .test_easy_install import make_nspkg_sdist
+from .fixtures import make_trivial_sdist
 from .test_find_packages import ensure_files
+from .textwrap import DALS
 
-import pytest
+from distutils.errors import DistutilsSetupError
 
 
-def test_dist_fetch_build_egg(tmpdir):
+def test_dist_fetch_build_egg(tmpdir, setuptools_wheel):
     """
     Check multiple calls to `Distribution.fetch_build_egg` work as expected.
     """
@@ -26,16 +24,18 @@ def test_dist_fetch_build_egg(tmpdir):
 
     def sdist_with_index(distname, version):
         dist_dir = index.mkdir(distname)
-        dist_sdist = '%s-%s.tar.gz' % (distname, version)
-        make_nspkg_sdist(str(dist_dir.join(dist_sdist)), distname, version)
+        dist_sdist = f'{distname}-{version}.tar.gz'
+        make_trivial_sdist(
+            str(dist_dir.join(dist_sdist)), distname, version, setuptools_wheel
+        )
         with dist_dir.join('index.html').open('w') as fp:
             fp.write(
                 DALS(
-                    '''
+                    """
                 
                 {dist_sdist}
- ''' + """ ).format(dist_sdist=dist_sdist) ) @@ -44,21 +44,21 @@ def sdist_with_index(distname, version): with tmpdir.join('setup.cfg').open('w') as fp: fp.write( DALS( - ''' + """ [easy_install] index_url = {index_url} - ''' + """ ).format(index_url=index_url) ) - reqs = ''' + reqs = """ barbazquux-runner barbazquux - '''.split() + """.split() with tmpdir.as_cwd(): dist = Distribution() dist.parse_config_files() resolved_dists = [dist.fetch_build_egg(r) for r in reqs] - assert [dist.key for dist in resolved_dists if dist] == reqs + assert [dist.name for dist in resolved_dists if dist] == reqs EXAMPLE_BASE_INFO = dict( @@ -73,17 +73,12 @@ def sdist_with_index(distname, version): def test_provides_extras_deterministic_order(): - extras = collections.OrderedDict() - extras['a'] = ['foo'] - extras['b'] = ['bar'] - attrs = dict(extras_require=extras) + attrs = dict(extras_require=dict(a=['foo'], b=['bar'])) dist = Distribution(attrs) - assert dist.metadata.provides_extras == ['a', 'b'] - attrs['extras_require'] = collections.OrderedDict( - reversed(list(attrs['extras_require'].items())) - ) + assert list(dist.metadata.provides_extras) == ['a', 'b'] + attrs['extras_require'] = dict(reversed(attrs['extras_require'].items())) dist = Distribution(attrs) - assert dist.metadata.provides_extras == ['b', 'a'] + assert list(dist.metadata.provides_extras) == ['b', 'a'] CHECK_PACKAGE_DATA_TESTS = ( @@ -116,11 +111,11 @@ def test_provides_extras_deterministic_order(): # Invalid value type. ( { - 'hello': str('*.msg'), + 'hello': '*.msg', }, ( - "\"values of 'package_data' dict\" " - "must be a list of strings (got '*.msg')" + "\"values of 'package_data' dict\" must be of type " + " (got '*.msg')" ), ), # Invalid value type (generators are single use) @@ -129,20 +124,20 @@ def test_provides_extras_deterministic_order(): 'hello': (x for x in "generator"), }, ( - "\"values of 'package_data' dict\" must be a list of strings " - "(got " + " (got =3.0', '!=3.1']} + dist = Distribution(attrs) + check_specifier(dist, attrs, attrs['python_requires']) + + # invalid specifier value + attrs = {'name': 'foo', 'python_requires': '>=invalid-version'} with pytest.raises(DistutilsSetupError): dist = Distribution(attrs) @@ -163,7 +162,7 @@ def test_metadata_name(): @pytest.mark.parametrize( - "dist_name, py_module", + ('dist_name', 'py_module'), [ ("my.pkg", "my_pkg"), ("my-pkg", "my_pkg"), @@ -194,7 +193,7 @@ def test_dist_default_py_modules(tmp_path, dist_name, py_module): @pytest.mark.parametrize( - "dist_name, package_dir, package_files, packages", + ('dist_name', 'package_dir', 'package_files', 'packages'), [ ("my.pkg", None, ["my_pkg/__init__.py", "my_pkg/mod.py"], ["my_pkg"]), ("my-pkg", None, ["my_pkg/__init__.py", "my_pkg/mod.py"], ["my_pkg"]), @@ -248,7 +247,7 @@ def test_dist_default_packages( @pytest.mark.parametrize( - "dist_name, package_dir, package_files", + ('dist_name', 'package_dir', 'package_files'), [ ("my.pkg.nested", None, ["my/pkg/nested/__init__.py"]), ("my.pkg", None, ["my/pkg/__init__.py", "my/pkg/file.py"]), diff --git a/setuptools/tests/test_dist_info.py b/setuptools/tests/test_dist_info.py index a76dbeb3f2..f65d0afbe4 100644 --- a/setuptools/tests/test_dist_info.py +++ b/setuptools/tests/test_dist_info.py @@ -1,5 +1,5 @@ -"""Test .dist-info style distributions. -""" +"""Test .dist-info style distributions.""" + import pathlib import re import shutil @@ -9,84 +9,21 @@ import pytest -import pkg_resources from setuptools.archive_util import unpack_archive -from .textwrap import DALS +from .textwrap import DALS read = partial(pathlib.Path.read_text, encoding="utf-8") class TestDistInfo: - metadata_base = DALS( - """ - Metadata-Version: 1.2 - Requires-Dist: splort (==4) - Provides-Extra: baz - Requires-Dist: quux (>=1.1); extra == 'baz' - """ - ) - - @classmethod - def build_metadata(cls, **kwargs): - lines = ('{key}: {value}\n'.format(**locals()) for key, value in kwargs.items()) - return cls.metadata_base + ''.join(lines) - - @pytest.fixture - def metadata(self, tmpdir): - dist_info_name = 'VersionedDistribution-2.718.dist-info' - versioned = tmpdir / dist_info_name - versioned.mkdir() - filename = versioned / 'METADATA' - content = self.build_metadata( - Name='VersionedDistribution', - ) - filename.write_text(content, encoding='utf-8') - - dist_info_name = 'UnversionedDistribution.dist-info' - unversioned = tmpdir / dist_info_name - unversioned.mkdir() - filename = unversioned / 'METADATA' - content = self.build_metadata( - Name='UnversionedDistribution', - Version='0.3', - ) - filename.write_text(content, encoding='utf-8') - - return str(tmpdir) - - def test_distinfo(self, metadata): - dists = dict( - (d.project_name, d) for d in pkg_resources.find_distributions(metadata) - ) - - assert len(dists) == 2, dists - - unversioned = dists['UnversionedDistribution'] - versioned = dists['VersionedDistribution'] - - assert versioned.version == '2.718' # from filename - assert unversioned.version == '0.3' # from METADATA - - def test_conditional_dependencies(self, metadata): - specs = 'splort==4', 'quux>=1.1' - requires = list(map(pkg_resources.Requirement.parse, specs)) - - for d in pkg_resources.find_distributions(metadata): - assert d.requires() == requires[:1] - assert d.requires(extras=('baz',)) == [ - requires[0], - pkg_resources.Requirement.parse('quux>=1.1;extra=="baz"'), - ] - assert d.extras == ['baz'] - def test_invalid_version(self, tmp_path): """ Supplying an invalid version crashes dist_info. """ config = "[metadata]\nname=proj\nversion=42\n[egg_info]\ntag_build=invalid!!!\n" (tmp_path / "setup.cfg").write_text(config, encoding="utf-8") - msg = re.compile("invalid version", re.M | re.I) + msg = re.compile("invalid version", re.MULTILINE | re.IGNORECASE) proc = run_command_inner("dist_info", cwd=tmp_path, check=False) assert proc.returncode assert msg.search(proc.stdout) @@ -122,7 +59,7 @@ def test_output_dir(self, tmp_path, keep_egg_info): run_command("dist_info", "--output-dir", out, *opts, cwd=tmp_path) assert len(list(out.glob("*.dist-info"))) == 1 assert len(list(tmp_path.glob("*.dist-info"))) == 0 - expected_egg_info = 1 if keep_egg_info else 0 + expected_egg_info = int(keep_egg_info) assert len(list(out.glob("*.egg-info"))) == expected_egg_info assert len(list(tmp_path.glob("*.egg-info"))) == 0 assert len(list(out.glob("*.__bkp__"))) == 0 @@ -169,7 +106,7 @@ class TestWheelCompatibility: @pytest.mark.parametrize("name", "my-proj my_proj my.proj My.Proj".split()) @pytest.mark.parametrize("version", ["0.42.13"]) - @pytest.mark.parametrize("suffix, cfg", EGG_INFO_OPTS) + @pytest.mark.parametrize(("suffix", "cfg"), EGG_INFO_OPTS) def test_dist_info_is_the_same_as_in_wheel( self, name, version, tmp_path, suffix, cfg ): @@ -188,7 +125,7 @@ def test_dist_info_is_the_same_as_in_wheel( dist_info = next(tmp_path.glob("dir_dist/*.dist-info")) assert dist_info.name == wheel_dist_info.name - assert dist_info.name.startswith(f"{name.replace('-', '_')}-{version}{suffix}") + assert dist_info.name.startswith(f"my_proj-{version}{suffix}") for file in "METADATA", "entry_points.txt": assert read(dist_info / file) == read(wheel_dist_info / file) @@ -198,7 +135,8 @@ def run_command_inner(*cmd, **kwargs): "stderr": subprocess.STDOUT, "stdout": subprocess.PIPE, "text": True, - 'check': True, + "encoding": "utf-8", + "check": True, **kwargs, } cmd = [sys.executable, "-c", "__import__('setuptools').setup()", *map(str, cmd)] diff --git a/setuptools/tests/test_distutils_adoption.py b/setuptools/tests/test_distutils_adoption.py index b371a5d353..f99a588499 100644 --- a/setuptools/tests/test_distutils_adoption.py +++ b/setuptools/tests/test_distutils_adoption.py @@ -1,24 +1,13 @@ import os -import sys -import functools import platform +import sys import textwrap import pytest - IS_PYPY = '__pypy__' in sys.builtin_module_names - -def popen_text(call): - """ - Augment the Popen call with the parameters to ensure unicode text. - """ - return ( - functools.partial(call, universal_newlines=True) - if sys.version_info < (3, 7) - else functools.partial(call, text=True) - ) +_TEXT_KWARGS = {"text": True, "encoding": "utf-8"} # For subprocess.run def win_sr(env): @@ -28,9 +17,7 @@ def win_sr(env): > Fatal Python error: _Py_HashRandomization_Init: failed to > get random numbers to initialize Python """ - if env is None: - return - if platform.system() == 'Windows': + if env and platform.system() == 'Windows': env['SYSTEMROOT'] = os.environ['SYSTEMROOT'] return env @@ -38,7 +25,7 @@ def win_sr(env): def find_distutils(venv, imports='distutils', env=None, **kwargs): py_cmd = 'import {imports}; print(distutils.__file__)'.format(**locals()) cmd = ['python', '-c', py_cmd] - return popen_text(venv.run)(cmd, env=win_sr(env), **kwargs) + return venv.run(cmd, env=win_sr(env), **_TEXT_KWARGS, **kwargs) def count_meta_path(venv, env=None): @@ -50,7 +37,7 @@ def count_meta_path(venv, env=None): """ ) cmd = ['python', '-c', py_cmd] - return int(popen_text(venv.run)(cmd, env=win_sr(env))) + return int(venv.run(cmd, env=win_sr(env), **_TEXT_KWARGS)) skip_without_stdlib_distutils = pytest.mark.skipif( @@ -96,7 +83,7 @@ def test_pip_import(venv): Regression test for #3002. """ cmd = ['python', '-c', 'import pip'] - popen_text(venv.run)(cmd) + venv.run(cmd, **_TEXT_KWARGS) def test_distutils_has_origin(): @@ -127,8 +114,9 @@ def test_distutils_has_origin(): """ +@pytest.mark.usefixtures("tmpdir_cwd") @pytest.mark.parametrize( - "distutils_version, imported_module", + ('distutils_version', 'imported_module'), [ pytest.param("stdlib", "dir_util", marks=skip_without_stdlib_distutils), pytest.param("stdlib", "file_util", marks=skip_without_stdlib_distutils), @@ -138,13 +126,11 @@ def test_distutils_has_origin(): ("local", "archive_util"), ], ) -def test_modules_are_not_duplicated_on_import( - distutils_version, imported_module, tmpdir_cwd, venv -): +def test_modules_are_not_duplicated_on_import(distutils_version, imported_module, venv): env = dict(SETUPTOOLS_USE_DISTUTILS=distutils_version) script = ENSURE_IMPORTS_ARE_NOT_DUPLICATED.format(imported_module=imported_module) cmd = ['python', '-c', script] - output = popen_text(venv.run)(cmd, env=win_sr(env)).strip() + output = venv.run(cmd, env=win_sr(env), **_TEXT_KWARGS).strip() assert output == "success" @@ -158,6 +144,7 @@ def test_modules_are_not_duplicated_on_import( """ +@pytest.mark.usefixtures("tmpdir_cwd") @pytest.mark.parametrize( "distutils_version", [ @@ -165,8 +152,47 @@ def test_modules_are_not_duplicated_on_import( pytest.param("stdlib", marks=skip_without_stdlib_distutils), ], ) -def test_log_module_is_not_duplicated_on_import(distutils_version, tmpdir_cwd, venv): +def test_log_module_is_not_duplicated_on_import(distutils_version, venv): env = dict(SETUPTOOLS_USE_DISTUTILS=distutils_version) cmd = ['python', '-c', ENSURE_LOG_IMPORT_IS_NOT_DUPLICATED] - output = popen_text(venv.run)(cmd, env=win_sr(env)).strip() + output = venv.run(cmd, env=win_sr(env), **_TEXT_KWARGS).strip() + assert output == "success" + + +ENSURE_CONSISTENT_ERROR_FROM_MODIFIED_PY = r""" +from setuptools.modified import newer +from {imported_module}.errors import DistutilsError + +# Can't use pytest.raises in this context +try: + newer("", "") +except DistutilsError: + print("success") +else: + raise AssertionError("Expected to raise") +""" + + +@pytest.mark.usefixtures("tmpdir_cwd") +@pytest.mark.parametrize( + ('distutils_version', 'imported_module'), + [ + ("local", "distutils"), + # Unfortunately we still get ._distutils.errors.DistutilsError with SETUPTOOLS_USE_DISTUTILS=stdlib + # But that's a deprecated use-case we don't mind not fully supporting in newer code + pytest.param( + "stdlib", "setuptools._distutils", marks=skip_without_stdlib_distutils + ), + ], +) +def test_consistent_error_from_modified_py(distutils_version, imported_module, venv): + env = dict(SETUPTOOLS_USE_DISTUTILS=distutils_version) + cmd = [ + 'python', + '-c', + ENSURE_CONSISTENT_ERROR_FROM_MODIFIED_PY.format( + imported_module=imported_module + ), + ] + output = venv.run(cmd, env=win_sr(env), **_TEXT_KWARGS).strip() assert output == "success" diff --git a/setuptools/tests/test_easy_install.py b/setuptools/tests/test_easy_install.py deleted file mode 100644 index d71e01586c..0000000000 --- a/setuptools/tests/test_easy_install.py +++ /dev/null @@ -1,1454 +0,0 @@ -"""Easy install Tests -""" - -import sys -import os -import tempfile -import site -import contextlib -import tarfile -import logging -import itertools -import distutils.errors -import io -import zipfile -import time -import re -import subprocess -import pathlib -import warnings -from collections import namedtuple -from pathlib import Path -from unittest import mock - -import pytest -from jaraco import path - -from setuptools import sandbox -from setuptools.sandbox import run_setup -import setuptools.command.easy_install as ei -from setuptools.command.easy_install import PthDistributions -from setuptools.dist import Distribution -from pkg_resources import normalize_path, working_set -from pkg_resources import Distribution as PRDistribution -from setuptools.tests.server import MockServer, path_to_url -from setuptools.tests import fail_on_ascii -import pkg_resources - -from . import contexts -from .textwrap import DALS - - -@pytest.fixture(autouse=True) -def pip_disable_index(monkeypatch): - """ - Important: Disable the default index for pip to avoid - querying packages in the index and potentially resolving - and installing packages there. - """ - monkeypatch.setenv('PIP_NO_INDEX', 'true') - - -class FakeDist: - def get_entry_map(self, group): - if group != 'console_scripts': - return {} - return {str('name'): 'ep'} - - def as_requirement(self): - return 'spec' - - -SETUP_PY = DALS( - """ - from setuptools import setup - - setup() - """ -) - - -class TestEasyInstallTest: - def test_get_script_args(self): - header = ei.CommandSpec.best().from_environment().as_header() - dist = FakeDist() - args = next(ei.ScriptWriter.get_args(dist)) - name, script = itertools.islice(args, 2) - assert script.startswith(header) - assert "'spec'" in script - assert "'console_scripts'" in script - assert "'name'" in script - assert re.search('^# EASY-INSTALL-ENTRY-SCRIPT', script, flags=re.MULTILINE) - - def test_no_find_links(self): - # new option '--no-find-links', that blocks find-links added at - # the project level - dist = Distribution() - cmd = ei.easy_install(dist) - cmd.check_pth_processing = lambda: True - cmd.no_find_links = True - cmd.find_links = ['link1', 'link2'] - cmd.install_dir = os.path.join(tempfile.mkdtemp(), 'ok') - cmd.args = ['ok'] - cmd.ensure_finalized() - assert cmd.package_index.scanned_urls == {} - - # let's try without it (default behavior) - cmd = ei.easy_install(dist) - cmd.check_pth_processing = lambda: True - cmd.find_links = ['link1', 'link2'] - cmd.install_dir = os.path.join(tempfile.mkdtemp(), 'ok') - cmd.args = ['ok'] - cmd.ensure_finalized() - keys = sorted(cmd.package_index.scanned_urls.keys()) - assert keys == ['link1', 'link2'] - - def test_write_exception(self): - """ - Test that `cant_write_to_target` is rendered as a DistutilsError. - """ - dist = Distribution() - cmd = ei.easy_install(dist) - cmd.install_dir = os.getcwd() - with pytest.raises(distutils.errors.DistutilsError): - cmd.cant_write_to_target() - - def test_all_site_dirs(self, monkeypatch): - """ - get_site_dirs should always return site dirs reported by - site.getsitepackages. - """ - path = normalize_path('/setuptools/test/site-packages') - - def mock_gsp(): - return [path] - - monkeypatch.setattr(site, 'getsitepackages', mock_gsp, raising=False) - assert path in ei.get_site_dirs() - - def test_all_site_dirs_works_without_getsitepackages(self, monkeypatch): - monkeypatch.delattr(site, 'getsitepackages', raising=False) - assert ei.get_site_dirs() - - @pytest.fixture - def sdist_unicode(self, tmpdir): - files = [ - ( - 'setup.py', - DALS( - """ - import setuptools - setuptools.setup( - name="setuptools-test-unicode", - version="1.0", - packages=["mypkg"], - include_package_data=True, - ) - """ - ), - ), - ( - 'mypkg/__init__.py', - "", - ), - ( - 'mypkg/☃.txt', - "", - ), - ] - sdist_name = 'setuptools-test-unicode-1.0.zip' - sdist = tmpdir / sdist_name - # can't use make_sdist, because the issue only occurs - # with zip sdists. - sdist_zip = zipfile.ZipFile(str(sdist), 'w') - for filename, content in files: - sdist_zip.writestr(filename, content) - sdist_zip.close() - return str(sdist) - - @fail_on_ascii - def test_unicode_filename_in_sdist(self, sdist_unicode, tmpdir, monkeypatch): - """ - The install command should execute correctly even if - the package has unicode filenames. - """ - dist = Distribution({'script_args': ['easy_install']}) - target = (tmpdir / 'target').ensure_dir() - cmd = ei.easy_install( - dist, - install_dir=str(target), - args=['x'], - ) - monkeypatch.setitem(os.environ, 'PYTHONPATH', str(target)) - cmd.ensure_finalized() - cmd.easy_install(sdist_unicode) - - @pytest.fixture - def sdist_unicode_in_script(self, tmpdir): - files = [ - ( - "setup.py", - DALS( - """ - import setuptools - setuptools.setup( - name="setuptools-test-unicode", - version="1.0", - packages=["mypkg"], - include_package_data=True, - scripts=['mypkg/unicode_in_script'], - ) - """ - ), - ), - ("mypkg/__init__.py", ""), - ( - "mypkg/unicode_in_script", - DALS( - """ - #!/bin/sh - # á - - non_python_fn() { - } - """ - ), - ), - ] - sdist_name = "setuptools-test-unicode-script-1.0.zip" - sdist = tmpdir / sdist_name - # can't use make_sdist, because the issue only occurs - # with zip sdists. - sdist_zip = zipfile.ZipFile(str(sdist), "w") - for filename, content in files: - sdist_zip.writestr(filename, content.encode('utf-8')) - sdist_zip.close() - return str(sdist) - - @fail_on_ascii - def test_unicode_content_in_sdist( - self, sdist_unicode_in_script, tmpdir, monkeypatch - ): - """ - The install command should execute correctly even if - the package has unicode in scripts. - """ - dist = Distribution({"script_args": ["easy_install"]}) - target = (tmpdir / "target").ensure_dir() - cmd = ei.easy_install(dist, install_dir=str(target), args=["x"]) - monkeypatch.setitem(os.environ, "PYTHONPATH", str(target)) - cmd.ensure_finalized() - cmd.easy_install(sdist_unicode_in_script) - - @pytest.fixture - def sdist_script(self, tmpdir): - files = [ - ( - 'setup.py', - DALS( - """ - import setuptools - setuptools.setup( - name="setuptools-test-script", - version="1.0", - scripts=["mypkg_script"], - ) - """ - ), - ), - ( - 'mypkg_script', - DALS( - """ - #/usr/bin/python - print('mypkg_script') - """ - ), - ), - ] - sdist_name = 'setuptools-test-script-1.0.zip' - sdist = str(tmpdir / sdist_name) - make_sdist(sdist, files) - return sdist - - @pytest.mark.skipif( - not sys.platform.startswith('linux'), reason="Test can only be run on Linux" - ) - def test_script_install(self, sdist_script, tmpdir, monkeypatch): - """ - Check scripts are installed. - """ - dist = Distribution({'script_args': ['easy_install']}) - target = (tmpdir / 'target').ensure_dir() - cmd = ei.easy_install( - dist, - install_dir=str(target), - args=['x'], - ) - monkeypatch.setitem(os.environ, 'PYTHONPATH', str(target)) - cmd.ensure_finalized() - cmd.easy_install(sdist_script) - assert (target / 'mypkg_script').exists() - - -@pytest.mark.filterwarnings('ignore:Unbuilt egg') -class TestPTHFileWriter: - def test_add_from_cwd_site_sets_dirty(self): - '''a pth file manager should set dirty - if a distribution is in site but also the cwd - ''' - pth = PthDistributions('does-not_exist', [os.getcwd()]) - assert not pth.dirty - pth.add(PRDistribution(os.getcwd())) - assert pth.dirty - - def test_add_from_site_is_ignored(self): - location = '/test/location/does-not-have-to-exist' - # PthDistributions expects all locations to be normalized - location = pkg_resources.normalize_path(location) - pth = PthDistributions( - 'does-not_exist', - [ - location, - ], - ) - assert not pth.dirty - pth.add(PRDistribution(location)) - assert not pth.dirty - - def test_many_pth_distributions_merge_together(self, tmpdir): - """ - If the pth file is modified under the hood, then PthDistribution - will refresh its content before saving, merging contents when - necessary. - """ - # putting the pth file in a dedicated sub-folder, - pth_subdir = tmpdir.join("pth_subdir") - pth_subdir.mkdir() - pth_path = str(pth_subdir.join("file1.pth")) - pth1 = PthDistributions(pth_path) - pth2 = PthDistributions(pth_path) - assert ( - pth1.paths == pth2.paths == [] - ), "unless there would be some default added at some point" - # and so putting the src_subdir in folder distinct than the pth one, - # so to keep it absolute by PthDistributions - new_src_path = tmpdir.join("src_subdir") - new_src_path.mkdir() # must exist to be accounted - new_src_path_str = str(new_src_path) - pth1.paths.append(new_src_path_str) - pth1.save() - assert ( - pth1.paths - ), "the new_src_path added must still be present/valid in pth1 after save" - # now, - assert ( - new_src_path_str not in pth2.paths - ), "right before we save the entry should still not be present" - pth2.save() - assert ( - new_src_path_str in pth2.paths - ), "the new_src_path entry should have been added by pth2 with its save() call" - assert pth2.paths[-1] == new_src_path, ( - "and it should match exactly on the last entry actually " - "given we append to it in save()" - ) - # finally, - assert PthDistributions(pth_path).paths == pth2.paths, ( - "and we should have the exact same list at the end " - "with a fresh PthDistributions instance" - ) - - -@pytest.fixture -def setup_context(tmpdir): - with (tmpdir / 'setup.py').open('w') as f: - f.write(SETUP_PY) - with tmpdir.as_cwd(): - yield tmpdir - - -@pytest.mark.usefixtures("user_override") -@pytest.mark.usefixtures("setup_context") -class TestUserInstallTest: - # prevent check that site-packages is writable. easy_install - # shouldn't be writing to system site-packages during finalize - # options, but while it does, bypass the behavior. - prev_sp_write = mock.patch( - 'setuptools.command.easy_install.easy_install.check_site_dir', - mock.Mock(), - ) - - # simulate setuptools installed in user site packages - @mock.patch('setuptools.command.easy_install.__file__', site.USER_SITE) - @mock.patch('site.ENABLE_USER_SITE', True) - @prev_sp_write - def test_user_install_not_implied_user_site_enabled(self): - self.assert_not_user_site() - - @mock.patch('site.ENABLE_USER_SITE', False) - @prev_sp_write - def test_user_install_not_implied_user_site_disabled(self): - self.assert_not_user_site() - - @staticmethod - def assert_not_user_site(): - # create a finalized easy_install command - dist = Distribution() - dist.script_name = 'setup.py' - cmd = ei.easy_install(dist) - cmd.args = ['py'] - cmd.ensure_finalized() - assert not cmd.user, 'user should not be implied' - - def test_multiproc_atexit(self): - pytest.importorskip('multiprocessing') - - log = logging.getLogger('test_easy_install') - logging.basicConfig(level=logging.INFO, stream=sys.stderr) - log.info('this should not break') - - @pytest.fixture() - def foo_package(self, tmpdir): - egg_file = tmpdir / 'foo-1.0.egg-info' - with egg_file.open('w') as f: - f.write('Name: foo\n') - return str(tmpdir) - - @pytest.fixture() - def install_target(self, tmpdir): - target = str(tmpdir) - with mock.patch('sys.path', sys.path + [target]): - python_path = os.path.pathsep.join(sys.path) - with mock.patch.dict(os.environ, PYTHONPATH=python_path): - yield target - - def test_local_index(self, foo_package, install_target): - """ - The local index must be used when easy_install locates installed - packages. - """ - dist = Distribution() - dist.script_name = 'setup.py' - cmd = ei.easy_install(dist) - cmd.install_dir = install_target - cmd.args = ['foo'] - cmd.ensure_finalized() - cmd.local_index.scan([foo_package]) - res = cmd.easy_install('foo') - actual = os.path.normcase(os.path.realpath(res.location)) - expected = os.path.normcase(os.path.realpath(foo_package)) - assert actual == expected - - @contextlib.contextmanager - def user_install_setup_context(self, *args, **kwargs): - """ - Wrap sandbox.setup_context to patch easy_install in that context to - appear as user-installed. - """ - with self.orig_context(*args, **kwargs): - import setuptools.command.easy_install as ei - - ei.__file__ = site.USER_SITE - yield - - def patched_setup_context(self): - self.orig_context = sandbox.setup_context - - return mock.patch( - 'setuptools.sandbox.setup_context', - self.user_install_setup_context, - ) - - -@pytest.fixture -def distutils_package(): - distutils_setup_py = SETUP_PY.replace( - 'from setuptools import setup', - 'from distutils.core import setup', - ) - with contexts.tempdir(cd=os.chdir): - with open('setup.py', 'w') as f: - f.write(distutils_setup_py) - yield - - -@pytest.fixture -def mock_index(): - # set up a server which will simulate an alternate package index. - p_index = MockServer() - if p_index.server_port == 0: - # Some platforms (Jython) don't find a port to which to bind, - # so skip test for them. - pytest.skip("could not find a valid port") - p_index.start() - return p_index - - -class TestDistutilsPackage: - def test_bdist_egg_available_on_distutils_pkg(self, distutils_package): - run_setup('setup.py', ['bdist_egg']) - - -class TestInstallRequires: - def test_setup_install_includes_dependencies(self, tmp_path, mock_index): - """ - When ``python setup.py install`` is called directly, it will use easy_install - to fetch dependencies. - """ - # TODO: Remove these tests once `setup.py install` is completely removed - project_root = tmp_path / "project" - project_root.mkdir(exist_ok=True) - install_root = tmp_path / "install" - install_root.mkdir(exist_ok=True) - - self.create_project(project_root) - cmd = [ - sys.executable, - '-c', - '__import__("setuptools").setup()', - 'install', - '--install-base', - str(install_root), - '--install-lib', - str(install_root), - '--install-headers', - str(install_root), - '--install-scripts', - str(install_root), - '--install-data', - str(install_root), - '--install-purelib', - str(install_root), - '--install-platlib', - str(install_root), - ] - env = {**os.environ, "__EASYINSTALL_INDEX": mock_index.url} - cp = subprocess.run( - cmd, - cwd=str(project_root), - env=env, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - text=True, - ) - assert cp.returncode != 0 - try: - assert '/does-not-exist/' in {r.path for r in mock_index.requests} - assert next( - line - for line in cp.stdout.splitlines() - if "not find suitable distribution for" in line - and "does-not-exist" in line - ) - except Exception: - if "failed to get random numbers" in cp.stdout: - pytest.xfail(f"{sys.platform} failure - {cp.stdout}") - raise - - def create_project(self, root): - config = """ - [metadata] - name = project - version = 42 - - [options] - install_requires = does-not-exist - py_modules = mod - """ - (root / 'setup.cfg').write_text(DALS(config), encoding="utf-8") - (root / 'mod.py').touch() - - -class TestSetupRequires: - def test_setup_requires_honors_fetch_params(self, mock_index, monkeypatch): - """ - When easy_install installs a source distribution which specifies - setup_requires, it should honor the fetch parameters (such as - index-url, and find-links). - """ - monkeypatch.setenv(str('PIP_RETRIES'), str('0')) - monkeypatch.setenv(str('PIP_TIMEOUT'), str('0')) - monkeypatch.setenv('PIP_NO_INDEX', 'false') - with contexts.quiet(): - # create an sdist that has a build-time dependency. - with TestSetupRequires.create_sdist() as dist_file: - with contexts.tempdir() as temp_install_dir: - with contexts.environment(PYTHONPATH=temp_install_dir): - cmd = [ - sys.executable, - '-c', - '__import__("setuptools").setup()', - 'easy_install', - '--index-url', - mock_index.url, - '--exclude-scripts', - '--install-dir', - temp_install_dir, - dist_file, - ] - subprocess.Popen(cmd).wait() - # there should have been one requests to the server - assert [r.path for r in mock_index.requests] == ['/does-not-exist/'] - - @staticmethod - @contextlib.contextmanager - def create_sdist(): - """ - Return an sdist with a setup_requires dependency (of something that - doesn't exist) - """ - with contexts.tempdir() as dir: - dist_path = os.path.join(dir, 'setuptools-test-fetcher-1.0.tar.gz') - make_sdist( - dist_path, - [ - ( - 'setup.py', - DALS( - """ - import setuptools - setuptools.setup( - name="setuptools-test-fetcher", - version="1.0", - setup_requires = ['does-not-exist'], - ) - """ - ), - ), - ('setup.cfg', ''), - ], - ) - yield dist_path - - use_setup_cfg = ( - (), - ('dependency_links',), - ('setup_requires',), - ('dependency_links', 'setup_requires'), - ) - - @pytest.mark.parametrize('use_setup_cfg', use_setup_cfg) - def test_setup_requires_overrides_version_conflict(self, use_setup_cfg): - """ - Regression test for distribution issue 323: - https://bitbucket.org/tarek/distribute/issues/323 - - Ensures that a distribution's setup_requires requirements can still be - installed and used locally even if a conflicting version of that - requirement is already on the path. - """ - - fake_dist = PRDistribution( - 'does-not-matter', project_name='foobar', version='0.0' - ) - working_set.add(fake_dist) - - with contexts.save_pkg_resources_state(): - with contexts.tempdir() as temp_dir: - test_pkg = create_setup_requires_package( - temp_dir, use_setup_cfg=use_setup_cfg - ) - test_setup_py = os.path.join(test_pkg, 'setup.py') - with contexts.quiet() as (stdout, stderr): - # Don't even need to install the package, just - # running the setup.py at all is sufficient - run_setup(test_setup_py, [str('--name')]) - - lines = stdout.readlines() - assert len(lines) > 0 - assert lines[-1].strip() == 'test_pkg' - - @pytest.mark.parametrize('use_setup_cfg', use_setup_cfg) - def test_setup_requires_override_nspkg(self, use_setup_cfg): - """ - Like ``test_setup_requires_overrides_version_conflict`` but where the - ``setup_requires`` package is part of a namespace package that has - *already* been imported. - """ - - with contexts.save_pkg_resources_state(): - with contexts.tempdir() as temp_dir: - foobar_1_archive = os.path.join(temp_dir, 'foo.bar-0.1.tar.gz') - make_nspkg_sdist(foobar_1_archive, 'foo.bar', '0.1') - # Now actually go ahead an extract to the temp dir and add the - # extracted path to sys.path so foo.bar v0.1 is importable - foobar_1_dir = os.path.join(temp_dir, 'foo.bar-0.1') - os.mkdir(foobar_1_dir) - with tarfile.open(foobar_1_archive) as tf: - tf.extraction_filter = lambda member, path: member - tf.extractall(foobar_1_dir) - sys.path.insert(1, foobar_1_dir) - - dist = PRDistribution( - foobar_1_dir, project_name='foo.bar', version='0.1' - ) - working_set.add(dist) - - template = DALS( - """\ - import foo # Even with foo imported first the - # setup_requires package should override - import setuptools - setuptools.setup(**%r) - - if not (hasattr(foo, '__path__') and - len(foo.__path__) == 2): - print('FAIL') - - if 'foo.bar-0.2' not in foo.__path__[0]: - print('FAIL') - """ - ) - - test_pkg = create_setup_requires_package( - temp_dir, - 'foo.bar', - '0.2', - make_nspkg_sdist, - template, - use_setup_cfg=use_setup_cfg, - ) - - test_setup_py = os.path.join(test_pkg, 'setup.py') - - with contexts.quiet() as (stdout, stderr): - try: - # Don't even need to install the package, just - # running the setup.py at all is sufficient - run_setup(test_setup_py, [str('--name')]) - except pkg_resources.VersionConflict: - self.fail( - 'Installing setup.py requirements ' - 'caused a VersionConflict' - ) - - assert 'FAIL' not in stdout.getvalue() - lines = stdout.readlines() - assert len(lines) > 0 - assert lines[-1].strip() == 'test_pkg' - - @pytest.mark.parametrize('use_setup_cfg', use_setup_cfg) - def test_setup_requires_with_attr_version(self, use_setup_cfg): - def make_dependency_sdist(dist_path, distname, version): - files = [ - ( - 'setup.py', - DALS( - """ - import setuptools - setuptools.setup( - name={name!r}, - version={version!r}, - py_modules=[{name!r}], - ) - """.format( - name=distname, version=version - ) - ), - ), - ( - distname + '.py', - DALS( - """ - version = 42 - """ - ), - ), - ] - make_sdist(dist_path, files) - - with contexts.save_pkg_resources_state(): - with contexts.tempdir() as temp_dir: - test_pkg = create_setup_requires_package( - temp_dir, - setup_attrs=dict(version='attr: foobar.version'), - make_package=make_dependency_sdist, - use_setup_cfg=use_setup_cfg + ('version',), - ) - test_setup_py = os.path.join(test_pkg, 'setup.py') - with contexts.quiet() as (stdout, stderr): - run_setup(test_setup_py, [str('--version')]) - lines = stdout.readlines() - assert len(lines) > 0 - assert lines[-1].strip() == '42' - - def test_setup_requires_honors_pip_env(self, mock_index, monkeypatch): - monkeypatch.setenv(str('PIP_RETRIES'), str('0')) - monkeypatch.setenv(str('PIP_TIMEOUT'), str('0')) - monkeypatch.setenv('PIP_NO_INDEX', 'false') - monkeypatch.setenv(str('PIP_INDEX_URL'), mock_index.url) - with contexts.save_pkg_resources_state(): - with contexts.tempdir() as temp_dir: - test_pkg = create_setup_requires_package( - temp_dir, - 'python-xlib', - '0.19', - setup_attrs=dict(dependency_links=[]), - ) - test_setup_cfg = os.path.join(test_pkg, 'setup.cfg') - with open(test_setup_cfg, 'w') as fp: - fp.write( - DALS( - ''' - [easy_install] - index_url = https://pypi.org/legacy/ - ''' - ) - ) - test_setup_py = os.path.join(test_pkg, 'setup.py') - with pytest.raises(distutils.errors.DistutilsError): - run_setup(test_setup_py, [str('--version')]) - assert len(mock_index.requests) == 1 - assert mock_index.requests[0].path == '/python-xlib/' - - def test_setup_requires_with_pep508_url(self, mock_index, monkeypatch): - monkeypatch.setenv(str('PIP_RETRIES'), str('0')) - monkeypatch.setenv(str('PIP_TIMEOUT'), str('0')) - monkeypatch.setenv(str('PIP_INDEX_URL'), mock_index.url) - with contexts.save_pkg_resources_state(): - with contexts.tempdir() as temp_dir: - dep_sdist = os.path.join(temp_dir, 'dep.tar.gz') - make_trivial_sdist(dep_sdist, 'dependency', '42') - dep_url = path_to_url(dep_sdist, authority='localhost') - test_pkg = create_setup_requires_package( - temp_dir, - # Ignored (overridden by setup_attrs) - 'python-xlib', - '0.19', - setup_attrs=dict(setup_requires='dependency @ %s' % dep_url), - ) - test_setup_py = os.path.join(test_pkg, 'setup.py') - run_setup(test_setup_py, [str('--version')]) - assert len(mock_index.requests) == 0 - - def test_setup_requires_with_allow_hosts(self, mock_index): - '''The `allow-hosts` option in not supported anymore.''' - files = { - 'test_pkg': { - 'setup.py': DALS( - ''' - from setuptools import setup - setup(setup_requires='python-xlib') - ''' - ), - 'setup.cfg': DALS( - ''' - [easy_install] - allow_hosts = * - ''' - ), - } - } - with contexts.save_pkg_resources_state(): - with contexts.tempdir() as temp_dir: - path.build(files, prefix=temp_dir) - setup_py = str(pathlib.Path(temp_dir, 'test_pkg', 'setup.py')) - with pytest.raises(distutils.errors.DistutilsError): - run_setup(setup_py, [str('--version')]) - assert len(mock_index.requests) == 0 - - def test_setup_requires_with_python_requires(self, monkeypatch, tmpdir): - '''Check `python_requires` is honored.''' - monkeypatch.setenv(str('PIP_RETRIES'), str('0')) - monkeypatch.setenv(str('PIP_TIMEOUT'), str('0')) - monkeypatch.setenv(str('PIP_NO_INDEX'), str('1')) - monkeypatch.setenv(str('PIP_VERBOSE'), str('1')) - dep_1_0_sdist = 'dep-1.0.tar.gz' - dep_1_0_url = path_to_url(str(tmpdir / dep_1_0_sdist)) - dep_1_0_python_requires = '>=2.7' - make_python_requires_sdist( - str(tmpdir / dep_1_0_sdist), 'dep', '1.0', dep_1_0_python_requires - ) - dep_2_0_sdist = 'dep-2.0.tar.gz' - dep_2_0_url = path_to_url(str(tmpdir / dep_2_0_sdist)) - dep_2_0_python_requires = '!=' + '.'.join(map(str, sys.version_info[:2])) + '.*' - make_python_requires_sdist( - str(tmpdir / dep_2_0_sdist), 'dep', '2.0', dep_2_0_python_requires - ) - index = tmpdir / 'index.html' - index.write_text( - DALS( - ''' - - Links for dep - -

Links for dep

- {dep_1_0_sdist}
- {dep_2_0_sdist}
- - - ''' - ).format( - dep_1_0_url=dep_1_0_url, - dep_1_0_sdist=dep_1_0_sdist, - dep_1_0_python_requires=dep_1_0_python_requires, - dep_2_0_url=dep_2_0_url, - dep_2_0_sdist=dep_2_0_sdist, - dep_2_0_python_requires=dep_2_0_python_requires, - ), - 'utf-8', - ) - index_url = path_to_url(str(index)) - with contexts.save_pkg_resources_state(): - test_pkg = create_setup_requires_package( - str(tmpdir), - 'python-xlib', - '0.19', # Ignored (overridden by setup_attrs). - setup_attrs=dict(setup_requires='dep', dependency_links=[index_url]), - ) - test_setup_py = os.path.join(test_pkg, 'setup.py') - run_setup(test_setup_py, [str('--version')]) - eggs = list( - map(str, pkg_resources.find_distributions(os.path.join(test_pkg, '.eggs'))) - ) - assert eggs == ['dep 1.0'] - - @pytest.mark.parametrize('with_dependency_links_in_setup_py', (False, True)) - def test_setup_requires_with_find_links_in_setup_cfg( - self, monkeypatch, with_dependency_links_in_setup_py - ): - monkeypatch.setenv(str('PIP_RETRIES'), str('0')) - monkeypatch.setenv(str('PIP_TIMEOUT'), str('0')) - with contexts.save_pkg_resources_state(): - with contexts.tempdir() as temp_dir: - make_trivial_sdist( - os.path.join(temp_dir, 'python-xlib-42.tar.gz'), 'python-xlib', '42' - ) - test_pkg = os.path.join(temp_dir, 'test_pkg') - test_setup_py = os.path.join(test_pkg, 'setup.py') - test_setup_cfg = os.path.join(test_pkg, 'setup.cfg') - os.mkdir(test_pkg) - with open(test_setup_py, 'w') as fp: - if with_dependency_links_in_setup_py: - dependency_links = [os.path.join(temp_dir, 'links')] - else: - dependency_links = [] - fp.write( - DALS( - ''' - from setuptools import installer, setup - setup(setup_requires='python-xlib==42', - dependency_links={dependency_links!r}) - ''' - ).format(dependency_links=dependency_links) - ) - with open(test_setup_cfg, 'w') as fp: - fp.write( - DALS( - ''' - [easy_install] - index_url = {index_url} - find_links = {find_links} - ''' - ).format( - index_url=os.path.join(temp_dir, 'index'), - find_links=temp_dir, - ) - ) - run_setup(test_setup_py, [str('--version')]) - - def test_setup_requires_with_transitive_extra_dependency(self, monkeypatch): - ''' - Use case: installing a package with a build dependency on - an already installed `dep[extra]`, which in turn depends - on `extra_dep` (whose is not already installed). - ''' - with contexts.save_pkg_resources_state(): - with contexts.tempdir() as temp_dir: - # Create source distribution for `extra_dep`. - make_trivial_sdist( - os.path.join(temp_dir, 'extra_dep-1.0.tar.gz'), 'extra_dep', '1.0' - ) - # Create source tree for `dep`. - dep_pkg = os.path.join(temp_dir, 'dep') - os.mkdir(dep_pkg) - path.build( - { - 'setup.py': DALS( - """ - import setuptools - setuptools.setup( - name='dep', version='2.0', - extras_require={'extra': ['extra_dep']}, - ) - """ - ), - 'setup.cfg': '', - }, - prefix=dep_pkg, - ) - # "Install" dep. - run_setup(os.path.join(dep_pkg, 'setup.py'), [str('dist_info')]) - working_set.add_entry(dep_pkg) - # Create source tree for test package. - test_pkg = os.path.join(temp_dir, 'test_pkg') - test_setup_py = os.path.join(test_pkg, 'setup.py') - os.mkdir(test_pkg) - with open(test_setup_py, 'w') as fp: - fp.write( - DALS( - ''' - from setuptools import installer, setup - setup(setup_requires='dep[extra]') - ''' - ) - ) - # Check... - monkeypatch.setenv(str('PIP_FIND_LINKS'), str(temp_dir)) - monkeypatch.setenv(str('PIP_NO_INDEX'), str('1')) - monkeypatch.setenv(str('PIP_RETRIES'), str('0')) - monkeypatch.setenv(str('PIP_TIMEOUT'), str('0')) - run_setup(test_setup_py, [str('--version')]) - - def test_setup_requires_with_distutils_command_dep(self, monkeypatch): - ''' - Use case: ensure build requirements' extras - are properly installed and activated. - ''' - with contexts.save_pkg_resources_state(): - with contexts.tempdir() as temp_dir: - # Create source distribution for `extra_dep`. - make_sdist( - os.path.join(temp_dir, 'extra_dep-1.0.tar.gz'), - [ - ( - 'setup.py', - DALS( - """ - import setuptools - setuptools.setup( - name='extra_dep', - version='1.0', - py_modules=['extra_dep'], - ) - """ - ), - ), - ('setup.cfg', ''), - ('extra_dep.py', ''), - ], - ) - # Create source tree for `epdep`. - dep_pkg = os.path.join(temp_dir, 'epdep') - os.mkdir(dep_pkg) - path.build( - { - 'setup.py': DALS( - """ - import setuptools - setuptools.setup( - name='dep', version='2.0', - py_modules=['epcmd'], - extras_require={'extra': ['extra_dep']}, - entry_points=''' - [distutils.commands] - epcmd = epcmd:epcmd [extra] - ''', - ) - """ - ), - 'setup.cfg': '', - 'epcmd.py': DALS( - """ - from distutils.command.build_py import build_py - - import extra_dep - - class epcmd(build_py): - pass - """ - ), - }, - prefix=dep_pkg, - ) - # "Install" dep. - run_setup(os.path.join(dep_pkg, 'setup.py'), [str('dist_info')]) - working_set.add_entry(dep_pkg) - # Create source tree for test package. - test_pkg = os.path.join(temp_dir, 'test_pkg') - test_setup_py = os.path.join(test_pkg, 'setup.py') - os.mkdir(test_pkg) - with open(test_setup_py, 'w') as fp: - fp.write( - DALS( - ''' - from setuptools import installer, setup - setup(setup_requires='dep[extra]') - ''' - ) - ) - # Check... - monkeypatch.setenv(str('PIP_FIND_LINKS'), str(temp_dir)) - monkeypatch.setenv(str('PIP_NO_INDEX'), str('1')) - monkeypatch.setenv(str('PIP_RETRIES'), str('0')) - monkeypatch.setenv(str('PIP_TIMEOUT'), str('0')) - run_setup(test_setup_py, ['epcmd']) - - -def make_trivial_sdist(dist_path, distname, version): - """ - Create a simple sdist tarball at dist_path, containing just a simple - setup.py. - """ - - make_sdist( - dist_path, - [ - ( - 'setup.py', - DALS( - """\ - import setuptools - setuptools.setup( - name=%r, - version=%r - ) - """ - % (distname, version) - ), - ), - ('setup.cfg', ''), - ], - ) - - -def make_nspkg_sdist(dist_path, distname, version): - """ - Make an sdist tarball with distname and version which also contains one - package with the same name as distname. The top-level package is - designated a namespace package). - """ - - parts = distname.split('.') - nspackage = parts[0] - - packages = ['.'.join(parts[:idx]) for idx in range(1, len(parts) + 1)] - - setup_py = DALS( - """\ - import setuptools - setuptools.setup( - name=%r, - version=%r, - packages=%r, - namespace_packages=[%r] - ) - """ - % (distname, version, packages, nspackage) - ) - - init = "__import__('pkg_resources').declare_namespace(__name__)" - - files = [('setup.py', setup_py), (os.path.join(nspackage, '__init__.py'), init)] - for package in packages[1:]: - filename = os.path.join(*(package.split('.') + ['__init__.py'])) - files.append((filename, '')) - - make_sdist(dist_path, files) - - -def make_python_requires_sdist(dist_path, distname, version, python_requires): - make_sdist( - dist_path, - [ - ( - 'setup.py', - DALS( - """\ - import setuptools - setuptools.setup( - name={name!r}, - version={version!r}, - python_requires={python_requires!r}, - ) - """ - ).format( - name=distname, version=version, python_requires=python_requires - ), - ), - ('setup.cfg', ''), - ], - ) - - -def make_sdist(dist_path, files): - """ - Create a simple sdist tarball at dist_path, containing the files - listed in ``files`` as ``(filename, content)`` tuples. - """ - - # Distributions with only one file don't play well with pip. - assert len(files) > 1 - with tarfile.open(dist_path, 'w:gz') as dist: - for filename, content in files: - file_bytes = io.BytesIO(content.encode('utf-8')) - file_info = tarfile.TarInfo(name=filename) - file_info.size = len(file_bytes.getvalue()) - file_info.mtime = int(time.time()) - dist.addfile(file_info, fileobj=file_bytes) - - -def create_setup_requires_package( - path, - distname='foobar', - version='0.1', - make_package=make_trivial_sdist, - setup_py_template=None, - setup_attrs={}, - use_setup_cfg=(), -): - """Creates a source tree under path for a trivial test package that has a - single requirement in setup_requires--a tarball for that requirement is - also created and added to the dependency_links argument. - - ``distname`` and ``version`` refer to the name/version of the package that - the test package requires via ``setup_requires``. The name of the test - package itself is just 'test_pkg'. - """ - - test_setup_attrs = { - 'name': 'test_pkg', - 'version': '0.0', - 'setup_requires': ['%s==%s' % (distname, version)], - 'dependency_links': [os.path.abspath(path)], - } - test_setup_attrs.update(setup_attrs) - - test_pkg = os.path.join(path, 'test_pkg') - os.mkdir(test_pkg) - - # setup.cfg - if use_setup_cfg: - options = [] - metadata = [] - for name in use_setup_cfg: - value = test_setup_attrs.pop(name) - if name in 'name version'.split(): - section = metadata - else: - section = options - if isinstance(value, (tuple, list)): - value = ';'.join(value) - section.append('%s: %s' % (name, value)) - test_setup_cfg_contents = DALS( - """ - [metadata] - {metadata} - [options] - {options} - """ - ).format( - options='\n'.join(options), - metadata='\n'.join(metadata), - ) - else: - test_setup_cfg_contents = '' - with open(os.path.join(test_pkg, 'setup.cfg'), 'w') as f: - f.write(test_setup_cfg_contents) - - # setup.py - if setup_py_template is None: - setup_py_template = DALS( - """\ - import setuptools - setuptools.setup(**%r) - """ - ) - with open(os.path.join(test_pkg, 'setup.py'), 'w') as f: - f.write(setup_py_template % test_setup_attrs) - - foobar_path = os.path.join(path, '%s-%s.tar.gz' % (distname, version)) - make_package(foobar_path, distname, version) - - return test_pkg - - -@pytest.mark.skipif( - sys.platform.startswith('java') and ei.is_sh(sys.executable), - reason="Test cannot run under java when executable is sh", -) -class TestScriptHeader: - non_ascii_exe = '/Users/José/bin/python' - exe_with_spaces = r'C:\Program Files\Python36\python.exe' - - def test_get_script_header(self): - expected = '#!%s\n' % ei.nt_quote_arg(os.path.normpath(sys.executable)) - actual = ei.ScriptWriter.get_header('#!/usr/local/bin/python') - assert actual == expected - - def test_get_script_header_args(self): - expected = '#!%s -x\n' % ei.nt_quote_arg(os.path.normpath(sys.executable)) - actual = ei.ScriptWriter.get_header('#!/usr/bin/python -x') - assert actual == expected - - def test_get_script_header_non_ascii_exe(self): - actual = ei.ScriptWriter.get_header( - '#!/usr/bin/python', executable=self.non_ascii_exe - ) - expected = str('#!%s -x\n') % self.non_ascii_exe - assert actual == expected - - def test_get_script_header_exe_with_spaces(self): - actual = ei.ScriptWriter.get_header( - '#!/usr/bin/python', executable='"' + self.exe_with_spaces + '"' - ) - expected = '#!"%s"\n' % self.exe_with_spaces - assert actual == expected - - -class TestCommandSpec: - def test_custom_launch_command(self): - """ - Show how a custom CommandSpec could be used to specify a #! executable - which takes parameters. - """ - cmd = ei.CommandSpec(['/usr/bin/env', 'python3']) - assert cmd.as_header() == '#!/usr/bin/env python3\n' - - def test_from_param_for_CommandSpec_is_passthrough(self): - """ - from_param should return an instance of a CommandSpec - """ - cmd = ei.CommandSpec(['python']) - cmd_new = ei.CommandSpec.from_param(cmd) - assert cmd is cmd_new - - @mock.patch('sys.executable', TestScriptHeader.exe_with_spaces) - @mock.patch.dict(os.environ) - def test_from_environment_with_spaces_in_executable(self): - os.environ.pop('__PYVENV_LAUNCHER__', None) - cmd = ei.CommandSpec.from_environment() - assert len(cmd) == 1 - assert cmd.as_header().startswith('#!"') - - def test_from_simple_string_uses_shlex(self): - """ - In order to support `executable = /usr/bin/env my-python`, make sure - from_param invokes shlex on that input. - """ - cmd = ei.CommandSpec.from_param('/usr/bin/env my-python') - assert len(cmd) == 2 - assert '"' not in cmd.as_header() - - -class TestWindowsScriptWriter: - def test_header(self): - hdr = ei.WindowsScriptWriter.get_header('') - assert hdr.startswith('#!') - assert hdr.endswith('\n') - hdr = hdr.lstrip('#!') - hdr = hdr.rstrip('\n') - # header should not start with an escaped quote - assert not hdr.startswith('\\"') - - -VersionStub = namedtuple("VersionStub", "major, minor, micro, releaselevel, serial") - - -def test_use_correct_python_version_string(tmpdir, tmpdir_cwd, monkeypatch): - # In issue #3001, easy_install wrongly uses the `python3.1` directory - # when the interpreter is `python3.10` and the `--user` option is given. - # See pypa/setuptools#3001. - dist = Distribution() - cmd = dist.get_command_obj('easy_install') - cmd.args = ['ok'] - cmd.optimize = 0 - cmd.user = True - cmd.install_userbase = str(tmpdir) - cmd.install_usersite = None - install_cmd = dist.get_command_obj('install') - install_cmd.install_userbase = str(tmpdir) - install_cmd.install_usersite = None - - with monkeypatch.context() as patch, warnings.catch_warnings(): - warnings.simplefilter("ignore") - version = '3.10.1 (main, Dec 21 2021, 09:17:12) [GCC 10.2.1 20210110]' - info = VersionStub(3, 10, 1, "final", 0) - patch.setattr('site.ENABLE_USER_SITE', True) - patch.setattr('sys.version', version) - patch.setattr('sys.version_info', info) - patch.setattr(cmd, 'create_home_path', mock.Mock()) - cmd.finalize_options() - - name = "pypy" if hasattr(sys, 'pypy_version_info') else "python" - install_dir = cmd.install_dir.lower() - - # In some platforms (e.g. Windows), install_dir is mostly determined - # via `sysconfig`, which define constants eagerly at module creation. - # This means that monkeypatching `sys.version` to emulate 3.10 for testing - # may have no effect. - # The safest test here is to rely on the fact that 3.1 is no longer - # supported/tested, and make sure that if 'python3.1' ever appears in the string - # it is followed by another digit (e.g. 'python3.10'). - if re.search(name + r'3\.?1', install_dir): - assert re.search(name + r'3\.?1\d', install_dir) - - # The following "variables" are used for interpolation in distutils - # installation schemes, so it should be fair to treat them as "semi-public", - # or at least public enough so we can have a test to make sure they are correct - assert cmd.config_vars['py_version'] == '3.10.1' - assert cmd.config_vars['py_version_short'] == '3.10' - assert cmd.config_vars['py_version_nodot'] == '310' - - -def test_editable_user_and_build_isolation(setup_context, monkeypatch, tmp_path): - '''`setup.py develop` should honor `--user` even under build isolation''' - - # == Arrange == - # Pretend that build isolation was enabled - # e.g pip sets the environment variable PYTHONNOUSERSITE=1 - monkeypatch.setattr('site.ENABLE_USER_SITE', False) - - # Patching $HOME for 2 reasons: - # 1. setuptools/command/easy_install.py:create_home_path - # tries creating directories in $HOME. - # Given:: - # self.config_vars['DESTDIRS'] = ( - # "/home/user/.pyenv/versions/3.9.10 " - # "/home/user/.pyenv/versions/3.9.10/lib " - # "/home/user/.pyenv/versions/3.9.10/lib/python3.9 " - # "/home/user/.pyenv/versions/3.9.10/lib/python3.9/lib-dynload") - # `create_home_path` will:: - # makedirs( - # "/home/user/.pyenv/versions/3.9.10 " - # "/home/user/.pyenv/versions/3.9.10/lib " - # "/home/user/.pyenv/versions/3.9.10/lib/python3.9 " - # "/home/user/.pyenv/versions/3.9.10/lib/python3.9/lib-dynload") - # - # 2. We are going to force `site` to update site.USER_BASE and site.USER_SITE - # To point inside our new home - monkeypatch.setenv('HOME', str(tmp_path / '.home')) - monkeypatch.setenv('USERPROFILE', str(tmp_path / '.home')) - monkeypatch.setenv('APPDATA', str(tmp_path / '.home')) - monkeypatch.setattr('site.USER_BASE', None) - monkeypatch.setattr('site.USER_SITE', None) - user_site = Path(site.getusersitepackages()) - user_site.mkdir(parents=True, exist_ok=True) - - sys_prefix = tmp_path / '.sys_prefix' - sys_prefix.mkdir(parents=True, exist_ok=True) - monkeypatch.setattr('sys.prefix', str(sys_prefix)) - - setup_script = ( - "__import__('setuptools').setup(name='aproj', version=42, packages=[])\n" - ) - (tmp_path / "setup.py").write_text(setup_script, encoding="utf-8") - - # == Sanity check == - assert list(sys_prefix.glob("*")) == [] - assert list(user_site.glob("*")) == [] - - # == Act == - run_setup('setup.py', ['develop', '--user']) - - # == Assert == - # Should not install to sys.prefix - assert list(sys_prefix.glob("*")) == [] - # Should install to user site - installed = {f.name for f in user_site.glob("*")} - # sometimes easy-install.pth is created and sometimes not - installed = installed - {"easy-install.pth"} - assert installed == {'aproj.egg-link'} diff --git a/setuptools/tests/test_editable_install.py b/setuptools/tests/test_editable_install.py index e58168b0cf..cf2dbe9e0f 100644 --- a/setuptools/tests/test_editable_install.py +++ b/setuptools/tests/test_editable_install.py @@ -1,13 +1,16 @@ +from __future__ import annotations + import os +import platform import stat -import sys import subprocess -import platform +import sys from copy import deepcopy from importlib import import_module from importlib.machinery import EXTENSION_SUFFIXES from pathlib import Path from textwrap import dedent +from typing import Any from unittest.mock import Mock from uuid import uuid4 @@ -16,21 +19,24 @@ import pytest from path import Path as _Path -from . import contexts, namespaces - from setuptools._importlib import resources as importlib_resources from setuptools.command.editable_wheel import ( - _DebuggingTips, - _LinkTree, _encode_pth, - _find_virtual_namespaces, _find_namespaces, _find_package_roots, + _find_virtual_namespaces, _finder_template, + _LinkTree, + _TopLevelFinder, editable_wheel, ) from setuptools.dist import Distribution from setuptools.extension import Extension +from setuptools.warnings import SetuptoolsDeprecationWarning + +from . import contexts, namespaces + +from distutils.core import run_setup @pytest.fixture(params=["strict", "lenient"]) @@ -57,8 +63,7 @@ def editable_opts(request): "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers" ] - urls = {Homepage = "http://github.com"} - dependencies = ['importlib-metadata; python_version<"3.8"'] + urls = {Homepage = "https://github.com"} [tool.setuptools] package-dir = {"" = "src"} @@ -87,11 +92,7 @@ def editable_opts(request): "__init__.py": dedent( """\ import sys - - if sys.version_info[:2] >= (3, 8): - from importlib.metadata import PackageNotFoundError, version - else: - from importlib_metadata import PackageNotFoundError, version + from importlib.metadata import PackageNotFoundError, version try: __version__ = version(__name__) @@ -119,10 +120,11 @@ def editable_opts(request): SETUP_SCRIPT_STUB = "__import__('setuptools').setup()" +@pytest.mark.xfail(sys.platform == "darwin", reason="pypa/setuptools#4328") @pytest.mark.parametrize( "files", [ - {**EXAMPLE, "setup.py": SETUP_SCRIPT_STUB}, # type: ignore + {**EXAMPLE, "setup.py": SETUP_SCRIPT_STUB}, EXAMPLE, # No setup.py script ], ) @@ -132,7 +134,7 @@ def test_editable_with_pyproject(tmp_path, venv, files, editable_opts): jaraco.path.build(files, prefix=project) cmd = [ - venv.exe(), + "python", "-m", "pip", "install", @@ -141,14 +143,14 @@ def test_editable_with_pyproject(tmp_path, venv, files, editable_opts): str(project), *editable_opts, ] - print(str(subprocess.check_output(cmd), "utf-8")) + print(venv.run(cmd)) - cmd = [venv.exe(), "-m", "mypkg"] - assert subprocess.check_output(cmd).strip() == b"3.14159.post0 Hello World" + cmd = ["python", "-m", "mypkg"] + assert venv.run(cmd).strip() == "3.14159.post0 Hello World" - (project / "src/mypkg/data.txt").write_text("foobar") - (project / "src/mypkg/mod.py").write_text("x = 42") - assert subprocess.check_output(cmd).strip() == b"3.14159.post0 foobar 42" + (project / "src/mypkg/data.txt").write_text("foobar", encoding="utf-8") + (project / "src/mypkg/mod.py").write_text("x = 42", encoding="utf-8") + assert venv.run(cmd).strip() == "3.14159.post0 foobar 42" def test_editable_with_flat_layout(tmp_path, venv, editable_opts): @@ -177,7 +179,7 @@ def test_editable_with_flat_layout(tmp_path, venv, editable_opts): project = tmp_path / "mypkg" cmd = [ - venv.exe(), + "python", "-m", "pip", "install", @@ -186,9 +188,9 @@ def test_editable_with_flat_layout(tmp_path, venv, editable_opts): str(project), *editable_opts, ] - print(str(subprocess.check_output(cmd), "utf-8")) - cmd = [venv.exe(), "-c", "import pkg, mod; print(pkg.a, mod.b)"] - assert subprocess.check_output(cmd).strip() == b"4 2" + print(venv.run(cmd)) + cmd = ["python", "-c", "import pkg, mod; print(pkg.a, mod.b)"] + assert venv.run(cmd).strip() == "4 2" def test_editable_with_single_module(tmp_path, venv, editable_opts): @@ -215,7 +217,7 @@ def test_editable_with_single_module(tmp_path, venv, editable_opts): project = tmp_path / "mypkg" cmd = [ - venv.exe(), + "python", "-m", "pip", "install", @@ -224,28 +226,65 @@ def test_editable_with_single_module(tmp_path, venv, editable_opts): str(project), *editable_opts, ] - print(str(subprocess.check_output(cmd), "utf-8")) - cmd = [venv.exe(), "-c", "import mod; print(mod.b)"] - assert subprocess.check_output(cmd).strip() == b"2" + print(venv.run(cmd)) + cmd = ["python", "-c", "import mod; print(mod.b)"] + assert venv.run(cmd).strip() == "2" class TestLegacyNamespaces: - """Ported from test_develop""" + # legacy => pkg_resources.declare_namespace(...) + setup(namespace_packages=...) - def test_namespace_package_importable(self, venv, tmp_path, editable_opts): + def test_nspkg_file_is_unique(self, tmp_path, monkeypatch): + deprecation = pytest.warns( + SetuptoolsDeprecationWarning, match=".*namespace_packages parameter.*" + ) + installation_dir = tmp_path / ".installation_dir" + installation_dir.mkdir() + examples = ( + "myns.pkgA", + "myns.pkgB", + "myns.n.pkgA", + "myns.n.pkgB", + ) + + for name in examples: + pkg = namespaces.build_namespace_package(tmp_path, name, version="42") + with deprecation, monkeypatch.context() as ctx: + ctx.chdir(pkg) + dist = run_setup("setup.py", stop_after="config") + cmd = editable_wheel(dist) + cmd.finalize_options() + editable_name = cmd.get_finalized_command("dist_info").name + cmd._install_namespaces(installation_dir, editable_name) + + files = list(installation_dir.glob("*-nspkg.pth")) + assert len(files) == len(examples) + + @pytest.mark.parametrize( + "impl", + ( + "pkg_resources", + # "pkgutil", => does not work + ), + ) + @pytest.mark.parametrize("ns", ("myns.n",)) + def test_namespace_package_importable( + self, venv, tmp_path, ns, impl, editable_opts + ): """ Installing two packages sharing the same namespace, one installed naturally using pip or `--single-version-externally-managed` and the other installed in editable mode should leave the namespace intact and both packages reachable by import. + (Ported from test_develop). """ build_system = """\ [build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" """ - pkg_A = namespaces.build_namespace_package(tmp_path, 'myns.pkgA') - pkg_B = namespaces.build_namespace_package(tmp_path, 'myns.pkgB') + pkg_A = namespaces.build_namespace_package(tmp_path, f"{ns}.pkgA", impl=impl) + pkg_B = namespaces.build_namespace_package(tmp_path, f"{ns}.pkgB", impl=impl) (pkg_A / "pyproject.toml").write_text(build_system, encoding="utf-8") (pkg_B / "pyproject.toml").write_text(build_system, encoding="utf-8") # use pip to install to the target directory @@ -253,9 +292,7 @@ def test_namespace_package_importable(self, venv, tmp_path, editable_opts): opts.append("--no-build-isolation") # force current version of setuptools venv.run(["python", "-m", "pip", "install", str(pkg_A), *opts]) venv.run(["python", "-m", "pip", "install", "-e", str(pkg_B), *opts]) - venv.run(["python", "-c", "import myns.pkgA; import myns.pkgB"]) - # additionally ensure that pkg_resources import works - venv.run(["python", "-c", "import pkg_resources"]) + venv.run(["python", "-c", f"import {ns}.pkgA; import {ns}.pkgB"]) class TestPep420Namespaces: @@ -348,7 +385,7 @@ def test_namespace_accidental_config_in_lenient_mode(self, venv, tmp_path): opts = ["--no-build-isolation"] # force current version of setuptools venv.run(["python", "-m", "pip", "-v", "install", "-e", str(pkg_A), *opts]) out = venv.run(["python", "-c", "from mypkg.n import pkgA; print(pkgA.a)"]) - assert str(out, "utf-8").strip() == "1" + assert out.strip() == "1" cmd = """\ try: import mypkg.other @@ -356,14 +393,9 @@ def test_namespace_accidental_config_in_lenient_mode(self, venv, tmp_path): print("mypkg.other not defined") """ out = venv.run(["python", "-c", dedent(cmd)]) - assert "mypkg.other not defined" in str(out, "utf-8") + assert "mypkg.other not defined" in out -# Moved here from test_develop: -@pytest.mark.xfail( - platform.python_implementation() == 'PyPy', - reason="Workaround fails on PyPy (why?)", -) def test_editable_with_prefix(tmp_path, sample_project, editable_opts): """ Editable install to a prefix should be discoverable. @@ -371,17 +403,19 @@ def test_editable_with_prefix(tmp_path, sample_project, editable_opts): prefix = tmp_path / 'prefix' # figure out where pip will likely install the package - site_packages = prefix / next( - Path(path).relative_to(sys.prefix) + site_packages_all = [ + prefix / Path(path).relative_to(sys.prefix) for path in sys.path if 'site-packages' in path and path.startswith(sys.prefix) - ) - site_packages.mkdir(parents=True) + ] + + for sp in site_packages_all: + sp.mkdir(parents=True) # install workaround - _addsitedir(site_packages) + _addsitedirs(site_packages_all) - env = dict(os.environ, PYTHONPATH=str(site_packages)) + env = dict(os.environ, PYTHONPATH=os.pathsep.join(map(str, site_packages_all))) cmd = [ sys.executable, '-m', @@ -399,8 +433,6 @@ def test_editable_with_prefix(tmp_path, sample_project, editable_opts): # now run 'sample' with the prefix on the PYTHONPATH bin = 'Scripts' if platform.system() == 'Windows' else 'bin' exe = prefix / bin / 'sample' - if sys.version_info < (3, 8) and platform.system() == 'Windows': - exe = str(exe) subprocess.check_call([exe], env=env) @@ -497,6 +529,49 @@ def test_combine_namespaces(self, tmp_path): assert pkgA.a == 13 assert mod2.b == 37 + def test_combine_namespaces_nested(self, tmp_path): + """ + Users may attempt to combine namespace packages in a nested way via + ``package_dir`` as shown in pypa/setuptools#4248. + """ + + files = { + "src": {"my_package": {"my_module.py": "a = 13"}}, + "src2": {"my_package2": {"my_module2.py": "b = 37"}}, + } + + stack = jaraco.path.DirectoryStack() + with stack.context(tmp_path): + jaraco.path.build(files) + attrs = { + "script_name": "%PEP 517%", + "package_dir": { + "different_name": "src/my_package", + "different_name.subpkg": "src2/my_package2", + }, + "packages": ["different_name", "different_name.subpkg"], + } + dist = Distribution(attrs) + finder = _TopLevelFinder(dist, str(uuid4())) + code = next(v for k, v in finder.get_implementation() if k.endswith(".py")) + + with contexts.save_paths(), contexts.save_sys_modules(): + for mod in attrs["packages"]: + sys.modules.pop(mod, None) + + self.install_finder(code) + mod1 = import_module("different_name.my_module") + mod2 = import_module("different_name.subpkg.my_module2") + + expected = str((tmp_path / "src/my_package/my_module.py").resolve()) + assert str(Path(mod1.__file__).resolve()) == expected + + expected = str((tmp_path / "src2/my_package2/my_module2.py").resolve()) + assert str(Path(mod2.__file__).resolve()) == expected + + assert mod1.a == 13 + assert mod2.b == 37 + def test_dynamic_path_computation(self, tmp_path): # Follows the example in PEP 420 files = { @@ -598,19 +673,19 @@ def test_case_sensitivity(self, tmp_path): sys.modules.pop("foo", None) self.install_finder(template) - with pytest.raises(ImportError, match="\'FOO\'"): + with pytest.raises(ImportError, match="'FOO'"): import_module("FOO") - with pytest.raises(ImportError, match="\'foo\\.LOWERCASE\'"): + with pytest.raises(ImportError, match="'foo\\.LOWERCASE'"): import_module("foo.LOWERCASE") - with pytest.raises(ImportError, match="\'foo\\.bar\\.Lowercase\'"): + with pytest.raises(ImportError, match="'foo\\.bar\\.Lowercase'"): import_module("foo.bar.Lowercase") - with pytest.raises(ImportError, match="\'foo\\.BAR\'"): + with pytest.raises(ImportError, match="'foo\\.BAR'"): import_module("foo.BAR.lowercase") - with pytest.raises(ImportError, match="\'FOO\'"): + with pytest.raises(ImportError, match="'FOO'"): import_module("FOO.bar.lowercase") mod = import_module("foo.lowercase") @@ -651,13 +726,13 @@ def test_namespace_case_sensitivity(self, tmp_path): bar = import_module("ns.othername.foo.bar") assert bar.c == 42 - with pytest.raises(ImportError, match="\'NS\'"): + with pytest.raises(ImportError, match="'NS'"): import_module("NS.othername.foo") - with pytest.raises(ImportError, match="\'ns\\.othername\\.FOO\\'"): + with pytest.raises(ImportError, match="'ns\\.othername\\.FOO\\'"): import_module("ns.othername.FOO") - with pytest.raises(ImportError, match="\'ns\\.othername\\.foo\\.BAR\\'"): + with pytest.raises(ImportError, match="'ns\\.othername\\.foo\\.BAR\\'"): import_module("ns.othername.foo.BAR") def test_intermediate_packages(self, tmp_path): @@ -765,7 +840,8 @@ class TestOverallBehaviour: version = "3.14159" """ - FLAT_LAYOUT = { + # Any: Would need a TypedDict. Keep it simple for tests + FLAT_LAYOUT: dict[str, Any] = { "pyproject.toml": dedent(PYPROJECT), "MANIFEST.in": EXAMPLE["MANIFEST.in"], "otherfile.py": "", @@ -803,9 +879,9 @@ class TestOverallBehaviour: "otherfile.py": "", "mypkg": { "__init__.py": "", - "mod1.py": FLAT_LAYOUT["mypkg"]["mod1.py"], # type: ignore + "mod1.py": FLAT_LAYOUT["mypkg"]["mod1.py"], }, - "other": FLAT_LAYOUT["mypkg"]["subpackage"], # type: ignore + "other": FLAT_LAYOUT["mypkg"]["subpackage"], }, "namespace": { "pyproject.toml": dedent(PYPROJECT), @@ -813,13 +889,14 @@ class TestOverallBehaviour: "otherfile.py": "", "src": { "mypkg": { - "mod1.py": FLAT_LAYOUT["mypkg"]["mod1.py"], # type: ignore - "subpackage": FLAT_LAYOUT["mypkg"]["subpackage"], # type: ignore + "mod1.py": FLAT_LAYOUT["mypkg"]["mod1.py"], + "subpackage": FLAT_LAYOUT["mypkg"]["subpackage"], }, }, }, } + @pytest.mark.xfail(sys.platform == "darwin", reason="pypa/setuptools#4328") @pytest.mark.parametrize("layout", EXAMPLES.keys()) def test_editable_install(self, tmp_path, venv, layout, editable_opts): project, _ = install_project( @@ -834,7 +911,7 @@ def test_editable_install(self, tmp_path, venv, layout, editable_opts): print(ex) """ out = venv.run(["python", "-c", dedent(cmd_import_error)]) - assert b"No module named 'otherfile'" in out + assert "No module named 'otherfile'" in out # Ensure the modules are importable cmd_get_vars = """\ @@ -842,7 +919,7 @@ def test_editable_install(self, tmp_path, venv, layout, editable_opts): print(mypkg.mod1.var, mypkg.subpackage.mod2.var) """ out = venv.run(["python", "-c", dedent(cmd_get_vars)]) - assert b"42 13" in out + assert "42 13" in out # Ensure resources are reachable cmd_get_resource = """\ @@ -852,7 +929,7 @@ def test_editable_install(self, tmp_path, venv, layout, editable_opts): print(text.read_text(encoding="utf-8")) """ out = venv.run(["python", "-c", dedent(cmd_get_resource)]) - assert b"resource 39" in out + assert "resource 39" in out # Ensure files are editable mod1 = next(project.glob("**/mod1.py")) @@ -864,12 +941,12 @@ def test_editable_install(self, tmp_path, venv, layout, editable_opts): resource_file.write_text("resource 374", encoding="utf-8") out = venv.run(["python", "-c", dedent(cmd_get_vars)]) - assert b"42 13" not in out - assert b"17 781" in out + assert "42 13" not in out + assert "17 781" in out out = venv.run(["python", "-c", dedent(cmd_get_resource)]) - assert b"resource 39" not in out - assert b"resource 374" in out + assert "resource 39" not in out + assert "resource 374" in out class TestLinkTree: @@ -928,7 +1005,7 @@ def test_strict_install(self, tmp_path, venv): install_project("mypkg", venv, tmp_path, self.FILES, *opts) out = venv.run(["python", "-c", "import mypkg.mod1; print(mypkg.mod1.var)"]) - assert b"42" in out + assert "42" in out # Ensure packages excluded from distribution are not importable cmd_import_error = """\ @@ -938,7 +1015,7 @@ def test_strict_install(self, tmp_path, venv): print(ex) """ out = venv.run(["python", "-c", dedent(cmd_import_error)]) - assert b"cannot import name 'subpackage'" in out + assert "cannot import name 'subpackage'" in out # Ensure resource files excluded from distribution are not reachable cmd_get_resource = """\ @@ -951,8 +1028,8 @@ def test_strict_install(self, tmp_path, venv): print(ex) """ out = venv.run(["python", "-c", dedent(cmd_get_resource)]) - assert b"No such file or directory" in out - assert b"resource.not_in_manifest" in out + assert "No such file or directory" in out + assert "resource.not_in_manifest" in out @pytest.mark.filterwarnings("ignore:.*compat.*:setuptools.SetuptoolsDeprecationWarning") @@ -963,7 +1040,7 @@ def test_compat_install(tmp_path, venv): install_project("mypkg", venv, tmp_path, files, *opts) out = venv.run(["python", "-c", "import mypkg.mod1; print(mypkg.mod1.var)"]) - assert b"42" in out + assert "42" in out expected_path = comparable_path(str(tmp_path)) @@ -974,7 +1051,7 @@ def test_compat_install(tmp_path, venv): "import other; print(other)", "import mypkg; print(mypkg)", ): - out = comparable_path(str(venv.run(["python", "-c", cmd]), "utf-8")) + out = comparable_path(venv.run(["python", "-c", cmd])) assert expected_path in out # Compatible behaviour will not consider custom mappings @@ -984,51 +1061,26 @@ def test_compat_install(tmp_path, venv): except ImportError as ex: print(ex) """ - out = str(venv.run(["python", "-c", dedent(cmd)]), "utf-8") + out = venv.run(["python", "-c", dedent(cmd)]) assert "cannot import name 'subpackage'" in out -def test_pbr_integration(tmp_path, venv, editable_opts): +@pytest.mark.uses_network +def test_pbr_integration(pbr_package, venv, editable_opts): """Ensure editable installs work with pbr, issue #3500""" - files = { - "pyproject.toml": dedent( - """\ - [build-system] - requires = ["setuptools"] - build-backend = "setuptools.build_meta" - """ - ), - "setup.py": dedent( - """\ - __import__('setuptools').setup( - pbr=True, - setup_requires=["pbr"], - ) - """ - ), - "setup.cfg": dedent( - """\ - [metadata] - name = mypkg - - [files] - packages = - mypkg - """ - ), - "mypkg": { - "__init__.py": "", - "hello.py": "print('Hello world!')", - }, - "other": {"test.txt": "Another file in here."}, - } - venv.run(["python", "-m", "pip", "install", "pbr"]) - - with contexts.environment(PBR_VERSION="0.42"): - install_project("mypkg", venv, tmp_path, files, *editable_opts) - + cmd = [ + 'python', + '-m', + 'pip', + '-v', + 'install', + '--editable', + pbr_package, + *editable_opts, + ] + venv.run(cmd, stderr=subprocess.STDOUT) out = venv.run(["python", "-c", "import mypkg.hello"]) - assert b"Hello world!" in out + assert "Hello world!" in out class TestCustomBuildPy: @@ -1066,11 +1118,11 @@ def test_safeguarded_from_errors(self, tmp_path, venv): """Ensure that errors in custom build_py are reported as warnings""" # Warnings should show up _, out = install_project("mypkg", venv, tmp_path, self.FILES) - assert b"SetuptoolsDeprecationWarning" in out - assert b"ValueError: TEST_RAISE" in out + assert "SetuptoolsDeprecationWarning" in out + assert "ValueError: TEST_RAISE" in out # but installation should be successful out = venv.run(["python", "-c", "import mypkg.mod1; print(mypkg.mod1.var)"]) - assert b"42" in out + assert "42" in out class TestCustomBuildWheel: @@ -1147,9 +1199,9 @@ def test_debugging_tips(tmpdir_cwd, monkeypatch): simulated_failure = Mock(side_effect=SimulatedErr()) monkeypatch.setattr(cmd, "get_finalized_command", simulated_failure) - expected_msg = "following steps are recommended to help debugging" - with pytest.raises(SimulatedErr), pytest.warns(_DebuggingTips, match=expected_msg): + with pytest.raises(SimulatedErr) as ctx: cmd.run() + assert any('debugging-tips' in note for note in ctx.value.__notes__) @pytest.mark.filterwarnings("error") @@ -1171,14 +1223,17 @@ def install_project(name, venv, tmp_path, files, *opts): return project, out -def _addsitedir(new_dir: Path): +def _addsitedirs(new_dirs): """To use this function, it is necessary to insert new_dir in front of sys.path. The Python process will try to import a ``sitecustomize`` module on startup. If we manipulate sys.path/PYTHONPATH, we can force it to run our code, which invokes ``addsitedir`` and ensure ``.pth`` files are loaded. """ - file = f"import site; site.addsitedir({os.fspath(new_dir)!r})\n" - (new_dir / "sitecustomize.py").write_text(file, encoding="utf-8") + content = '\n'.join( + ("import site",) + + tuple(f"site.addsitedir({os.fspath(new_dir)!r})" for new_dir in new_dirs) + ) + (new_dirs[0] / "sitecustomize.py").write_text(content, encoding="utf-8") # ---- Assertion Helpers ---- @@ -1192,7 +1247,7 @@ def assert_path(pkg, expected): assert str(Path(path).resolve()) == expected -def assert_link_to(file: Path, other: Path): +def assert_link_to(file: Path, other: Path) -> None: if file.is_symlink(): assert str(file.resolve()) == str(other.resolve()) else: diff --git a/setuptools/tests/test_egg_info.py b/setuptools/tests/test_egg_info.py index 614fca7a23..3653be096f 100644 --- a/setuptools/tests/test_egg_info.py +++ b/setuptools/tests/test_egg_info.py @@ -1,11 +1,12 @@ -import sys +from __future__ import annotations + import ast -import os import glob +import os import re import stat +import sys import time -from typing import List, Tuple from pathlib import Path from unittest import mock @@ -13,16 +14,11 @@ from jaraco import path from setuptools import errors -from setuptools.command.egg_info import ( - egg_info, - manifest_maker, - write_entries, -) +from setuptools.command.egg_info import egg_info, manifest_maker, write_entries from setuptools.dist import Distribution -from . import environment +from . import contexts, environment from .textwrap import DALS -from . import contexts class Environment(str): @@ -37,19 +33,16 @@ def env(): subs = 'home', 'lib', 'scripts', 'data', 'egg-base' env.paths = dict((dirname, os.path.join(env_dir, dirname)) for dirname in subs) list(map(os.mkdir, env.paths.values())) - path.build( - { - env.paths['home']: { - '.pydistutils.cfg': DALS( - """ + path.build({ + env.paths['home']: { + '.pydistutils.cfg': DALS( + """ [egg_info] - egg-base = %(egg-base)s - """ - % env.paths - ) - } + egg-base = {egg-base} + """.format(**env.paths) + ) } - ) + }) yield env @@ -68,22 +61,21 @@ class TestEggInfo: ) def _create_project(self): - path.build( - { - 'setup.py': self.setup_script, - 'hello.py': DALS( - """ + path.build({ + 'setup.py': self.setup_script, + 'hello.py': DALS( + """ def run(): print('hello') """ - ), - } - ) + ), + }) @staticmethod - def _extract_mv_version(pkg_info_lines: List[str]) -> Tuple[int, int]: + def _extract_mv_version(pkg_info_lines: list[str]) -> tuple[int, int]: version_str = pkg_info_lines[0].split(' ')[1] - return tuple(map(int, version_str.split('.')[:2])) + major, minor = map(int, version_str.split('.')[:2]) + return major, minor def test_egg_info_save_version_info_setup_empty(self, tmpdir_cwd, env): """ @@ -97,7 +89,7 @@ def test_egg_info_save_version_info_setup_empty(self, tmpdir_cwd, env): ei.initialize_options() ei.save_version_info(setup_cfg) - with open(setup_cfg, 'r') as f: + with open(setup_cfg, 'r', encoding="utf-8") as f: content = f.read() assert '[egg_info]' in content @@ -128,23 +120,21 @@ def test_egg_info_save_version_info_setup_defaults(self, tmpdir_cwd, env): the file should remain unchanged. """ setup_cfg = os.path.join(env.paths['home'], 'setup.cfg') - path.build( - { - setup_cfg: DALS( - """ + path.build({ + setup_cfg: DALS( + """ [egg_info] tag_build = tag_date = 0 """ - ), - } - ) + ), + }) dist = Distribution() ei = egg_info(dist) ei.initialize_options() ei.save_version_info(setup_cfg) - with open(setup_cfg, 'r') as f: + with open(setup_cfg, 'r', encoding="utf-8") as f: content = f.read() assert '[egg_info]' in content @@ -207,12 +197,10 @@ def test_license_is_a_string(self, tmpdir_cwd, env): """ ) - path.build( - { - 'setup.py': setup_script, - 'setup.cfg': setup_config, - } - ) + path.build({ + 'setup.py': setup_script, + 'setup.cfg': setup_config, + }) # This command should fail with a ValueError, but because it's # currently configured to use a subprocess, the actual traceback @@ -220,13 +208,9 @@ def test_license_is_a_string(self, tmpdir_cwd, env): with pytest.raises(AssertionError) as exc: self._run_egg_info_command(tmpdir_cwd, env) - # Hopefully this is not too fragile: the only argument to the - # assertion error should be a traceback, ending with: - # ValueError: .... - # - # assert not 1 - tb = exc.value.args[0].split('\n') - assert tb[-3].lstrip().startswith('ValueError') + # The only argument to the assertion error should be a traceback + # containing a ValueError + assert 'ValueError' in exc.value.args[0] def test_rebuilt(self, tmpdir_cwd, env): """Ensure timestamps are updated when the command is re-run.""" @@ -245,50 +229,39 @@ def test_rebuilt(self, tmpdir_cwd, env): def test_manifest_template_is_read(self, tmpdir_cwd, env): self._create_project() - path.build( - { - 'MANIFEST.in': DALS( - """ + path.build({ + 'MANIFEST.in': DALS( + """ recursive-include docs *.rst """ - ), - 'docs': { - 'usage.rst': "Run 'hi'", - }, - } - ) + ), + 'docs': { + 'usage.rst': "Run 'hi'", + }, + }) self._run_egg_info_command(tmpdir_cwd, env) egg_info_dir = os.path.join('.', 'foo.egg-info') sources_txt = os.path.join(egg_info_dir, 'SOURCES.txt') - with open(sources_txt) as f: + with open(sources_txt, encoding="utf-8") as f: assert 'docs/usage.rst' in f.read().split('\n') def _setup_script_with_requires(self, requires, use_setup_cfg=False): - setup_script = ( - DALS( - ''' + setup_script = DALS( + """ from setuptools import setup setup(name='foo', zip_safe=False, %s) - ''' - ) - % ('' if use_setup_cfg else requires) - ) + """ + ) % ('' if use_setup_cfg else requires) setup_config = requires if use_setup_cfg else '' - path.build( - { - 'setup.py': setup_script, - 'setup.cfg': setup_config, - } - ) + path.build({ + 'setup.py': setup_script, + 'setup.cfg': setup_config, + }) - mismatch_marker = "python_version<'{this_ver}'".format( - this_ver=sys.version_info[0], - ) + mismatch_marker = f"python_version<'{sys.version_info[0]}'" # Alternate equivalent syntax. - mismatch_marker_alternate = 'python_version < "{this_ver}"'.format( - this_ver=sys.version_info[0], - ) + mismatch_marker_alternate = f'python_version < "{sys.version_info[0]}"' invalid_marker = "<=>++" class RequiresTestHelper: @@ -305,9 +278,9 @@ def parametrize(*test_list, **format_dict): else: install_cmd_kwargs = {} name = name_kwargs[0].strip() - setup_py_requires, setup_cfg_requires, expected_requires = ( + setup_py_requires, setup_cfg_requires, expected_requires = [ DALS(a).format(**format_dict) for a in test_params - ) + ] for id_, requires, use_cfg in ( (name, setup_py_requires, False), (name + '_in_setup_cfg', setup_cfg_requires, True), @@ -327,7 +300,12 @@ def parametrize(*test_list, **format_dict): ) ) return pytest.mark.parametrize( - 'requires,use_setup_cfg,' 'expected_requires,install_cmd_kwargs', + ( + "requires", + "use_setup_cfg", + "expected_requires", + "install_cmd_kwargs", + ), argvalues, ids=idlist, ) @@ -343,7 +321,7 @@ def parametrize(*test_list, **format_dict): # requires block (when used in setup.cfg) # # expected contents of requires.txt - ''' + """ install_requires_deterministic install_requires=["wheel>=0.5", "pytest"] @@ -355,8 +333,8 @@ def parametrize(*test_list, **format_dict): wheel>=0.5 pytest - ''', - ''' + """, + """ install_requires_ordered install_requires=["pytest>=3.0.2,!=10.9999"] @@ -366,8 +344,8 @@ def parametrize(*test_list, **format_dict): pytest>=3.0.2,!=10.9999 pytest!=10.9999,>=3.0.2 - ''', - ''' + """, + """ install_requires_with_marker install_requires=["barbazquux;{mismatch_marker}"], @@ -378,8 +356,8 @@ def parametrize(*test_list, **format_dict): [:{mismatch_marker_alternate}] barbazquux - ''', - ''' + """, + """ install_requires_with_extra {'cmd': ['egg_info']} @@ -390,8 +368,8 @@ def parametrize(*test_list, **format_dict): barbazquux [test] barbazquux[test] - ''', - ''' + """, + """ install_requires_with_extra_and_marker install_requires=["barbazquux [test]; {mismatch_marker}"], @@ -402,8 +380,8 @@ def parametrize(*test_list, **format_dict): [:{mismatch_marker_alternate}] barbazquux[test] - ''', - ''' + """, + """ setup_requires_with_markers setup_requires=["barbazquux;{mismatch_marker}"], @@ -412,19 +390,8 @@ def parametrize(*test_list, **format_dict): setup_requires = barbazquux; {mismatch_marker} - ''', - ''' - tests_require_with_markers - {'cmd': ['test'], 'output': "Ran 0 tests in"} - - tests_require=["barbazquux;{mismatch_marker}"], - - [options] - tests_require = - barbazquux; {mismatch_marker} - - ''', - ''' + """, + """ extras_require_with_extra {'cmd': ['egg_info']} @@ -435,8 +402,8 @@ def parametrize(*test_list, **format_dict): [extra] barbazquux[test] - ''', - ''' + """, + """ extras_require_with_extra_and_marker_in_req extras_require={{"extra": ["barbazquux [test]; {mismatch_marker}"]}}, @@ -449,9 +416,9 @@ def parametrize(*test_list, **format_dict): [extra:{mismatch_marker_alternate}] barbazquux[test] - ''', + """, # FIXME: ConfigParser does not allow : in key names! - ''' + """ extras_require_with_marker extras_require={{":{mismatch_marker}": ["barbazquux"]}}, @@ -462,8 +429,8 @@ def parametrize(*test_list, **format_dict): [:{mismatch_marker}] barbazquux - ''', - ''' + """, + """ extras_require_with_marker_in_req extras_require={{"extra": ["barbazquux; {mismatch_marker}"]}}, @@ -476,8 +443,8 @@ def parametrize(*test_list, **format_dict): [extra:{mismatch_marker_alternate}] barbazquux - ''', - ''' + """, + """ extras_require_with_empty_section extras_require={{"empty": []}}, @@ -486,7 +453,7 @@ def parametrize(*test_list, **format_dict): empty = [empty] - ''', + """, # Format arguments. invalid_marker=invalid_marker, mismatch_marker=mismatch_marker, @@ -506,7 +473,7 @@ def test_requires( egg_info_dir = os.path.join('.', 'foo.egg-info') requires_txt = os.path.join(egg_info_dir, 'requires.txt') if os.path.exists(requires_txt): - with open(requires_txt) as fp: + with open(requires_txt, encoding="utf-8") as fp: install_requires = fp.read() else: install_requires = '' @@ -545,21 +512,21 @@ def test_provides_extra(self, tmpdir_cwd, env): environ = os.environ.copy().update( HOME=env.paths['home'], ) - code, data = environment.run_setup_py( + environment.run_setup_py( cmd=['egg_info'], pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), data_stream=1, env=environ, ) egg_info_dir = os.path.join('.', 'foo.egg-info') - with open(os.path.join(egg_info_dir, 'PKG-INFO')) as pkginfo_file: - pkg_info_lines = pkginfo_file.read().split('\n') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') assert 'Provides-Extra: foobar' in pkg_info_lines - assert 'Metadata-Version: 2.1' in pkg_info_lines + assert 'Metadata-Version: 2.4' in pkg_info_lines def test_doesnt_provides_extra(self, tmpdir_cwd, env): self._setup_script_with_requires( - '''install_requires=["spam ; python_version<'3.6'"]''' + """install_requires=["spam ; python_version<'3.6'"]""" ) environ = os.environ.copy().update( HOME=env.paths['home'], @@ -571,12 +538,12 @@ def test_doesnt_provides_extra(self, tmpdir_cwd, env): env=environ, ) egg_info_dir = os.path.join('.', 'foo.egg-info') - with open(os.path.join(egg_info_dir, 'PKG-INFO')) as pkginfo_file: - pkg_info_text = pkginfo_file.read() + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_text = fp.read() assert 'Provides-Extra:' not in pkg_info_text @pytest.mark.parametrize( - "files, license_in_sources", + ('files', 'license_in_sources'), [ ( { @@ -650,8 +617,7 @@ def test_setup_cfg_license_file(self, tmpdir_cwd, env, files, license_in_sources ) egg_info_dir = os.path.join('.', 'foo.egg-info') - with open(os.path.join(egg_info_dir, 'SOURCES.txt')) as sources_file: - sources_text = sources_file.read() + sources_text = Path(egg_info_dir, "SOURCES.txt").read_text(encoding="utf-8") if license_in_sources: assert 'LICENSE' in sources_text @@ -661,7 +627,7 @@ def test_setup_cfg_license_file(self, tmpdir_cwd, env, files, license_in_sources assert 'INVALID_LICENSE' not in sources_text @pytest.mark.parametrize( - "files, incl_licenses, excl_licenses", + ('files', 'incl_licenses', 'excl_licenses'), [ ( { @@ -788,7 +754,7 @@ def test_setup_cfg_license_file(self, tmpdir_cwd, env, files, license_in_sources ), 'MANIFEST.in': "exclude LICENSE-XYZ", 'LICENSE-ABC': "ABC license", - 'LICENSE-XYZ': "XYZ license" + 'LICENSE-XYZ': "XYZ license", # manifest is overwritten by license_files }, ['LICENSE-ABC', 'LICENSE-XYZ'], @@ -849,6 +815,22 @@ def test_setup_cfg_license_file(self, tmpdir_cwd, env, files, license_in_sources [], id="files_only_added_once", ), + pytest.param( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = **/LICENSE + """ + ), + 'LICENSE': "ABC license", + 'LICENSE-OTHER': "Don't include", + 'vendor': {'LICENSE': "Vendor license"}, + }, + ['LICENSE', 'vendor/LICENSE'], + ['LICENSE-OTHER'], + id="recursive_glob", + ), ], ) def test_setup_cfg_license_files( @@ -863,8 +845,8 @@ def test_setup_cfg_license_files( ) egg_info_dir = os.path.join('.', 'foo.egg-info') - with open(os.path.join(egg_info_dir, 'SOURCES.txt')) as sources_file: - sources_lines = list(line.strip() for line in sources_file) + sources_text = Path(egg_info_dir, "SOURCES.txt").read_text(encoding="utf-8") + sources_lines = [line.strip() for line in sources_text.splitlines()] for lf in incl_licenses: assert sources_lines.count(lf) == 1 @@ -873,7 +855,7 @@ def test_setup_cfg_license_files( assert sources_lines.count(lf) == 0 @pytest.mark.parametrize( - "files, incl_licenses, excl_licenses", + ('files', 'incl_licenses', 'excl_licenses'), [ ( { @@ -901,7 +883,7 @@ def test_setup_cfg_license_files( """ ), 'LICENSE-ABC': "ABC license", - 'LICENSE-XYZ': "XYZ license" + 'LICENSE-XYZ': "XYZ license", # license_file is still singular }, [], @@ -939,7 +921,7 @@ def test_setup_cfg_license_files( ), 'LICENSE-ABC': "ABC license", 'LICENSE-PQR': "PQR license", - 'LICENSE-XYZ': "XYZ license" + 'LICENSE-XYZ': "XYZ license", # duplicate license }, ['LICENSE-ABC', 'LICENSE-PQR', 'LICENSE-XYZ'], @@ -957,7 +939,7 @@ def test_setup_cfg_license_files( ), 'LICENSE-ABC': "ABC license", 'LICENSE-PQR': "PQR license", - 'LICENSE-XYZ': "XYZ license" + 'LICENSE-XYZ': "XYZ license", # combined subset }, ['LICENSE-ABC', 'LICENSE-XYZ'], @@ -974,7 +956,7 @@ def test_setup_cfg_license_files( LICENSE-PQR """ ), - 'LICENSE-PQR': "Test license" + 'LICENSE-PQR': "Test license", # with invalid licenses }, ['LICENSE-PQR'], @@ -994,7 +976,7 @@ def test_setup_cfg_license_files( 'MANIFEST.in': "exclude LICENSE-ABC\nexclude LICENSE-PQR", 'LICENSE-ABC': "ABC license", 'LICENSE-PQR': "PQR license", - 'LICENSE-XYZ': "XYZ license" + 'LICENSE-XYZ': "XYZ license", # manifest is overwritten }, ['LICENSE-ABC', 'LICENSE-PQR', 'LICENSE-XYZ'], @@ -1047,8 +1029,8 @@ def test_setup_cfg_license_file_license_files( ) egg_info_dir = os.path.join('.', 'foo.egg-info') - with open(os.path.join(egg_info_dir, 'SOURCES.txt')) as sources_file: - sources_lines = list(line.strip() for line in sources_file) + sources_text = Path(egg_info_dir, "SOURCES.txt").read_text(encoding="utf-8") + sources_lines = [line.strip() for line in sources_text.splitlines()] for lf in incl_licenses: assert sources_lines.count(lf) == 1 @@ -1059,53 +1041,55 @@ def test_setup_cfg_license_file_license_files( def test_license_file_attr_pkg_info(self, tmpdir_cwd, env): """All matched license files should have a corresponding License-File.""" self._create_project() - path.build( - { - "setup.cfg": DALS( - """ + path.build({ + "setup.cfg": DALS( + """ [metadata] license_files = NOTICE* LICENSE* + **/LICENSE """ - ), - "LICENSE-ABC": "ABC license", - "LICENSE-XYZ": "XYZ license", - "NOTICE": "included", - "IGNORE": "not include", - } - ) + ), + "LICENSE-ABC": "ABC license", + "LICENSE-XYZ": "XYZ license", + "NOTICE": "included", + "IGNORE": "not include", + "vendor": {'LICENSE': "Vendor license"}, + }) environment.run_setup_py( cmd=['egg_info'], pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), ) egg_info_dir = os.path.join('.', 'foo.egg-info') - with open(os.path.join(egg_info_dir, 'PKG-INFO')) as pkginfo_file: - pkg_info_lines = pkginfo_file.read().split('\n') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') license_file_lines = [ line for line in pkg_info_lines if line.startswith('License-File:') ] # Only 'NOTICE', LICENSE-ABC', and 'LICENSE-XYZ' should have been matched # Also assert that order from license_files is keeped + assert len(license_file_lines) == 4 assert "License-File: NOTICE" == license_file_lines[0] assert "License-File: LICENSE-ABC" in license_file_lines[1:] assert "License-File: LICENSE-XYZ" in license_file_lines[1:] + assert "License-File: vendor/LICENSE" in license_file_lines[3] def test_metadata_version(self, tmpdir_cwd, env): """Make sure latest metadata version is used by default.""" self._setup_script_with_requires("") - code, data = environment.run_setup_py( + environment.run_setup_py( cmd=['egg_info'], pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), data_stream=1, ) egg_info_dir = os.path.join('.', 'foo.egg-info') - with open(os.path.join(egg_info_dir, 'PKG-INFO')) as pkginfo_file: - pkg_info_lines = pkginfo_file.read().split('\n') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') # Update metadata version if changed - assert self._extract_mv_version(pkg_info_lines) == (2, 1) + assert self._extract_mv_version(pkg_info_lines) == (2, 4) def test_long_description_content_type(self, tmpdir_cwd, env): # Test that specifying a `long_description_content_type` keyword arg to @@ -1121,18 +1105,18 @@ def test_long_description_content_type(self, tmpdir_cwd, env): environ = os.environ.copy().update( HOME=env.paths['home'], ) - code, data = environment.run_setup_py( + environment.run_setup_py( cmd=['egg_info'], pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), data_stream=1, env=environ, ) egg_info_dir = os.path.join('.', 'foo.egg-info') - with open(os.path.join(egg_info_dir, 'PKG-INFO')) as pkginfo_file: - pkg_info_lines = pkginfo_file.read().split('\n') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') expected_line = 'Description-Content-Type: text/markdown' assert expected_line in pkg_info_lines - assert 'Metadata-Version: 2.1' in pkg_info_lines + assert 'Metadata-Version: 2.4' in pkg_info_lines def test_long_description(self, tmpdir_cwd, env): # Test that specifying `long_description` and `long_description_content_type` @@ -1143,15 +1127,15 @@ def test_long_description(self, tmpdir_cwd, env): "long_description='This is a long description\\nover multiple lines'," "long_description_content_type='text/markdown'," ) - code, data = environment.run_setup_py( + environment.run_setup_py( cmd=['egg_info'], pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), data_stream=1, ) egg_info_dir = os.path.join('.', 'foo.egg-info') - with open(os.path.join(egg_info_dir, 'PKG-INFO')) as pkginfo_file: - pkg_info_lines = pkginfo_file.read().split('\n') - assert 'Metadata-Version: 2.1' in pkg_info_lines + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + assert 'Metadata-Version: 2.4' in pkg_info_lines assert '' == pkg_info_lines[-1] # last line should be empty long_desc_lines = pkg_info_lines[pkg_info_lines.index('') :] assert 'This is a long description' in long_desc_lines @@ -1174,15 +1158,15 @@ def test_project_urls(self, tmpdir_cwd, env): environ = os.environ.copy().update( HOME=env.paths['home'], ) - code, data = environment.run_setup_py( + environment.run_setup_py( cmd=['egg_info'], pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), data_stream=1, env=environ, ) egg_info_dir = os.path.join('.', 'foo.egg-info') - with open(os.path.join(egg_info_dir, 'PKG-INFO')) as pkginfo_file: - pkg_info_lines = pkginfo_file.read().split('\n') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') expected_line = 'Project-URL: Link One, https://example.com/one/' assert expected_line in pkg_info_lines expected_line = 'Project-URL: Link Two, https://example.com/two/' @@ -1192,14 +1176,14 @@ def test_project_urls(self, tmpdir_cwd, env): def test_license(self, tmpdir_cwd, env): """Test single line license.""" self._setup_script_with_requires("license='MIT',") - code, data = environment.run_setup_py( + environment.run_setup_py( cmd=['egg_info'], pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), data_stream=1, ) egg_info_dir = os.path.join('.', 'foo.egg-info') - with open(os.path.join(egg_info_dir, 'PKG-INFO')) as pkginfo_file: - pkg_info_lines = pkginfo_file.read().split('\n') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') assert 'License: MIT' in pkg_info_lines def test_license_escape(self, tmpdir_cwd, env): @@ -1207,14 +1191,14 @@ def test_license_escape(self, tmpdir_cwd, env): self._setup_script_with_requires( "license='This is a long license text \\nover multiple lines'," ) - code, data = environment.run_setup_py( + environment.run_setup_py( cmd=['egg_info'], pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), data_stream=1, ) egg_info_dir = os.path.join('.', 'foo.egg-info') - with open(os.path.join(egg_info_dir, 'PKG-INFO')) as pkginfo_file: - pkg_info_lines = pkginfo_file.read().split('\n') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') assert 'License: This is a long license text ' in pkg_info_lines assert ' over multiple lines' in pkg_info_lines @@ -1225,15 +1209,15 @@ def test_python_requires_egg_info(self, tmpdir_cwd, env): environ = os.environ.copy().update( HOME=env.paths['home'], ) - code, data = environment.run_setup_py( + environment.run_setup_py( cmd=['egg_info'], pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), data_stream=1, env=environ, ) egg_info_dir = os.path.join('.', 'foo.egg-info') - with open(os.path.join(egg_info_dir, 'PKG-INFO')) as pkginfo_file: - pkg_info_lines = pkginfo_file.read().split('\n') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') assert 'Requires-Python: >=2.7.12' in pkg_info_lines assert self._extract_mv_version(pkg_info_lines) >= (1, 2) @@ -1256,7 +1240,7 @@ def test_egg_info_includes_setup_py(self, tmpdir_cwd): assert 'setup.py' in egg_info_instance.filelist.files - with open(egg_info_instance.egg_info + "/SOURCES.txt") as f: + with open(egg_info_instance.egg_info + "/SOURCES.txt", encoding="utf-8") as f: sources = f.read().split('\n') assert 'setup.py' in sources @@ -1281,22 +1265,20 @@ def _run_egg_info_command(self, tmpdir_cwd, env, cmd=None, output=None): def test_egg_info_tag_only_once(self, tmpdir_cwd, env): self._create_project() - path.build( - { - 'setup.cfg': DALS( - """ + path.build({ + 'setup.cfg': DALS( + """ [egg_info] tag_build = dev tag_date = 0 tag_svn_revision = 0 """ - ), - } - ) + ), + }) self._run_egg_info_command(tmpdir_cwd, env) egg_info_dir = os.path.join('.', 'foo.egg-info') - with open(os.path.join(egg_info_dir, 'PKG-INFO')) as pkginfo_file: - pkg_info_lines = pkginfo_file.read().split('\n') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') assert 'Version: 0.0.0.dev0' in pkg_info_lines @@ -1305,10 +1287,11 @@ def test_invalid_entry_point(self, tmpdir_cwd, env): dist = Distribution({"name": "foo", "version": "0.0.1"}) dist.entry_points = {"foo": "foo = invalid-identifier:foo"} cmd = dist.get_command_obj("egg_info") - expected_msg = r"Problems to parse .*invalid-identifier.*" - with pytest.raises(errors.OptionError, match=expected_msg) as ex: + expected_msg = r"(Invalid object reference|Problems to parse)" + with pytest.raises((errors.OptionError, ValueError), match=expected_msg) as ex: write_entries(cmd, "entry_points", "entry_points.txt") assert "ensure entry-point follows the spec" in ex.value.args[0] + assert "invalid-identifier" in str(ex.value) def test_valid_entry_point(self, tmpdir_cwd, env): dist = Distribution({"name": "foo", "version": "0.0.1"}) diff --git a/setuptools/tests/test_extern.py b/setuptools/tests/test_extern.py index 0d6b164f53..d7eb3c62c1 100644 --- a/setuptools/tests/test_extern.py +++ b/setuptools/tests/test_extern.py @@ -1,19 +1,14 @@ import importlib import pickle +import packaging + from setuptools import Distribution -from setuptools.extern import ordered_set def test_reimport_extern(): - ordered_set2 = importlib.import_module(ordered_set.__name__) - assert ordered_set is ordered_set2 - - -def test_orderedset_pickle_roundtrip(): - o1 = ordered_set.OrderedSet([1, 2, 5]) - o2 = pickle.loads(pickle.dumps(o1)) - assert o1 == o2 + packaging2 = importlib.import_module(packaging.__name__) + assert packaging is packaging2 def test_distribution_picklable(): diff --git a/setuptools/tests/test_find_packages.py b/setuptools/tests/test_find_packages.py index 92da882d09..9fd9f8f663 100644 --- a/setuptools/tests/test_find_packages.py +++ b/setuptools/tests/test_find_packages.py @@ -1,39 +1,15 @@ """Tests for automatic package discovery""" + import os -import sys import shutil import tempfile -import platform import pytest -from setuptools import find_packages -from setuptools import find_namespace_packages +from setuptools import find_namespace_packages, find_packages from setuptools.discovery import FlatLayoutPackageFinder - -# modeled after CPython's test.support.can_symlink -def can_symlink(): - TESTFN = tempfile.mktemp() - symlink_path = TESTFN + "can_symlink" - try: - os.symlink(TESTFN, symlink_path) - can = True - except (OSError, NotImplementedError, AttributeError): - can = False - else: - os.remove(symlink_path) - globals().update(can_symlink=lambda: can) - return can - - -def has_symlink(): - bad_symlink = ( - # Windows symlink directory detection is broken on Python 3.2 - platform.system() == 'Windows' - and sys.version_info[:2] == (3, 2) - ) - return can_symlink() and not bad_symlink +from .compat.py39 import os_helper class TestFindPackages: @@ -82,8 +58,7 @@ def _mkdir(self, path, parent_dir=None): def _touch(self, path, dir_=None): if dir_: path = os.path.join(dir_, path) - fp = open(path, 'w') - fp.close() + open(path, 'wb').close() return path def test_regular_package(self): @@ -134,7 +109,7 @@ def test_dir_with_packages_in_subdir_is_excluded(self): packages = find_packages(self.dist_dir) assert 'build.pkg' not in packages - @pytest.mark.skipif(not has_symlink(), reason='Symlink support required') + @pytest.mark.skipif(not os_helper.can_symlink(), reason='Symlink support required') def test_symlinked_packages_are_included(self): """ A symbolically-linked directory should be treated like any other @@ -204,7 +179,8 @@ class TestFlatLayoutPackageFinder: [ "pkg/__init__.py", "examples/__init__.py", - "examples/file.py" "example/other_file.py", + "examples/file.py", + "example/other_file.py", # Sub-packages should always be fine "pkg/example/__init__.py", "pkg/examples/__init__.py", diff --git a/setuptools/tests/test_find_py_modules.py b/setuptools/tests/test_find_py_modules.py index dc7ff41edc..8034b54429 100644 --- a/setuptools/tests/test_find_py_modules.py +++ b/setuptools/tests/test_find_py_modules.py @@ -1,11 +1,13 @@ """Tests for automatic discovery of modules""" + import os import pytest from setuptools.discovery import FlatLayoutModuleFinder, ModuleFinder -from .test_find_packages import ensure_files, has_symlink +from .compat.py39 import os_helper +from .test_find_packages import ensure_files class TestModuleFinder: @@ -38,7 +40,7 @@ def test_finder(self, tmp_path, example): ensure_files(tmp_path, files) assert self.find(tmp_path, **kwargs) == set(expected_modules) - @pytest.mark.skipif(not has_symlink(), reason='Symlink support required') + @pytest.mark.skipif(not os_helper.can_symlink(), reason='Symlink support required') def test_symlinked_packages_are_included(self, tmp_path): src = "_myfiles/file.py" ensure_files(tmp_path, [src]) diff --git a/setuptools/tests/test_glob.py b/setuptools/tests/test_glob.py index 42b3c43a21..8d225a4461 100644 --- a/setuptools/tests/test_glob.py +++ b/setuptools/tests/test_glob.py @@ -5,12 +5,12 @@ @pytest.mark.parametrize( - 'tree, pattern, matches', + ('tree', 'pattern', 'matches'), ( ('', b'', []), ('', '', []), ( - ''' + """ appveyor.yml CHANGES.rst LICENSE @@ -19,12 +19,12 @@ README.rst setup.cfg setup.py - ''', + """, '*.rst', ('CHANGES.rst', 'README.rst'), ), ( - ''' + """ appveyor.yml CHANGES.rst LICENSE @@ -33,7 +33,7 @@ README.rst setup.cfg setup.py - ''', + """, b'*.rst', (b'CHANGES.rst', b'README.rst'), ), diff --git a/setuptools/tests/test_install_scripts.py b/setuptools/tests/test_install_scripts.py index 4338c792f1..e62a6b7f31 100644 --- a/setuptools/tests/test_install_scripts.py +++ b/setuptools/tests/test_install_scripts.py @@ -1,13 +1,12 @@ -"""install_scripts tests -""" +"""install_scripts tests""" -import io import sys import pytest from setuptools.command.install_scripts import install_scripts from setuptools.dist import Distribution + from . import contexts @@ -39,11 +38,11 @@ def test_sys_executable_escaping_unix(self, tmpdir, monkeypatch): Ensure that shebang is not quoted on Unix when getting the Python exe from sys.executable. """ - expected = '#!%s\n' % self.unix_exe + expected = f'#!{self.unix_exe}\n' monkeypatch.setattr('sys.executable', self.unix_exe) with tmpdir.as_cwd(): self._run_install_scripts(str(tmpdir)) - with io.open(str(tmpdir.join('foo')), 'r') as f: + with open(str(tmpdir.join('foo')), 'r', encoding="utf-8") as f: actual = f.readline() assert actual == expected @@ -53,11 +52,11 @@ def test_sys_executable_escaping_win32(self, tmpdir, monkeypatch): Ensure that shebang is quoted on Windows when getting the Python exe from sys.executable and it contains a space. """ - expected = '#!"%s"\n' % self.win32_exe + expected = f'#!"{self.win32_exe}"\n' monkeypatch.setattr('sys.executable', self.win32_exe) with tmpdir.as_cwd(): self._run_install_scripts(str(tmpdir)) - with io.open(str(tmpdir.join('foo-script.py')), 'r') as f: + with open(str(tmpdir.join('foo-script.py')), 'r', encoding="utf-8") as f: actual = f.readline() assert actual == expected @@ -68,10 +67,10 @@ def test_executable_with_spaces_escaping_unix(self, tmpdir): a value with spaces is specified using --executable. """ - expected = '#!%s\n' % self.unix_spaces_exe + expected = f'#!{self.unix_spaces_exe}\n' with tmpdir.as_cwd(): self._run_install_scripts(str(tmpdir), self.unix_spaces_exe) - with io.open(str(tmpdir.join('foo')), 'r') as f: + with open(str(tmpdir.join('foo')), 'r', encoding="utf-8") as f: actual = f.readline() assert actual == expected @@ -82,9 +81,9 @@ def test_executable_arg_escaping_win32(self, tmpdir): getting a path with spaces from --executable, that is itself properly quoted. """ - expected = '#!"%s"\n' % self.win32_exe + expected = f'#!"{self.win32_exe}"\n' with tmpdir.as_cwd(): self._run_install_scripts(str(tmpdir), '"' + self.win32_exe + '"') - with io.open(str(tmpdir.join('foo-script.py')), 'r') as f: + with open(str(tmpdir.join('foo-script.py')), 'r', encoding="utf-8") as f: actual = f.readline() assert actual == expected diff --git a/setuptools/tests/test_integration.py b/setuptools/tests/test_integration.py deleted file mode 100644 index e17ffc5d5c..0000000000 --- a/setuptools/tests/test_integration.py +++ /dev/null @@ -1,117 +0,0 @@ -"""Run some integration tests. - -Try to install a few packages. -""" - -import glob -import os -import sys -import urllib.request - -import pytest - -from setuptools.command.easy_install import easy_install -from setuptools.command import easy_install as easy_install_pkg -from setuptools.dist import Distribution - - -pytestmark = pytest.mark.skipif( - 'platform.python_implementation() == "PyPy" and ' 'platform.system() == "Windows"', - reason="pypa/setuptools#2496", -) - - -def setup_module(module): - packages = 'stevedore', 'virtualenvwrapper', 'pbr', 'novaclient' - for pkg in packages: - try: - __import__(pkg) - tmpl = "Integration tests cannot run when {pkg} is installed" - pytest.skip(tmpl.format(**locals())) - except ImportError: - pass - - try: - urllib.request.urlopen('https://pypi.python.org/pypi') - except Exception as exc: - pytest.skip(str(exc)) - - -@pytest.fixture -def install_context(request, tmpdir, monkeypatch): - """Fixture to set up temporary installation directory.""" - # Save old values so we can restore them. - new_cwd = tmpdir.mkdir('cwd') - user_base = tmpdir.mkdir('user_base') - user_site = tmpdir.mkdir('user_site') - install_dir = tmpdir.mkdir('install_dir') - - def fin(): - # undo the monkeypatch, particularly needed under - # windows because of kept handle on cwd - monkeypatch.undo() - new_cwd.remove() - user_base.remove() - user_site.remove() - install_dir.remove() - - request.addfinalizer(fin) - - # Change the environment and site settings to control where the - # files are installed and ensure we do not overwrite anything. - monkeypatch.chdir(new_cwd) - monkeypatch.setattr(easy_install_pkg, '__file__', user_site.strpath) - monkeypatch.setattr('site.USER_BASE', user_base.strpath) - monkeypatch.setattr('site.USER_SITE', user_site.strpath) - monkeypatch.setattr('sys.path', sys.path + [install_dir.strpath]) - monkeypatch.setenv(str('PYTHONPATH'), str(os.path.pathsep.join(sys.path))) - - # Set up the command for performing the installation. - dist = Distribution() - cmd = easy_install(dist) - cmd.install_dir = install_dir.strpath - return cmd - - -def _install_one(requirement, cmd, pkgname, modulename): - cmd.args = [requirement] - cmd.ensure_finalized() - cmd.run() - target = cmd.install_dir - dest_path = glob.glob(os.path.join(target, pkgname + '*.egg')) - assert dest_path - assert os.path.exists(os.path.join(dest_path[0], pkgname, modulename)) - - -def test_stevedore(install_context): - _install_one('stevedore', install_context, 'stevedore', 'extension.py') - - -@pytest.mark.xfail -def test_virtualenvwrapper(install_context): - _install_one( - 'virtualenvwrapper', install_context, 'virtualenvwrapper', 'hook_loader.py' - ) - - -def test_pbr(install_context): - _install_one('pbr', install_context, 'pbr', 'core.py') - - -@pytest.mark.xfail -def test_python_novaclient(install_context): - _install_one('python-novaclient', install_context, 'novaclient', 'base.py') - - -def test_pyuri(install_context): - """ - Install the pyuri package (version 0.3.1 at the time of writing). - - This is also a regression test for issue #1016. - """ - _install_one('pyuri', install_context, 'pyuri', 'uri.py') - - pyuri = install_context.installed_projects['pyuri'] - - # The package data should be installed. - assert os.path.exists(os.path.join(pyuri.location, 'pyuri', 'uri.regex')) diff --git a/setuptools/tests/test_logging.py b/setuptools/tests/test_logging.py index 39e67bab38..5d487bda2d 100644 --- a/setuptools/tests/test_logging.py +++ b/setuptools/tests/test_logging.py @@ -1,9 +1,12 @@ +import functools import inspect import logging -import os +import sys import pytest +IS_PYPY = '__pypy__' in sys.builtin_module_names + setup_py = """\ from setuptools import setup @@ -16,11 +19,12 @@ @pytest.mark.parametrize( - "flag, expected_level", [("--dry-run", "INFO"), ("--verbose", "DEBUG")] + ('flags', 'expected_level'), [([], "INFO"), (["--verbose"], "DEBUG")] ) -def test_verbosity_level(tmp_path, monkeypatch, flag, expected_level): +def test_verbosity_level(tmp_path, monkeypatch, flags, expected_level): """Make sure the correct verbosity level is set (issue #3038)""" import setuptools # noqa: F401 # import setuptools to monkeypatch distutils + import distutils # <- load distutils after all the patches take place logger = logging.Logger(__name__) @@ -29,25 +33,44 @@ def test_verbosity_level(tmp_path, monkeypatch, flag, expected_level): assert logging.getLevelName(unset_log_level) == "NOTSET" setup_script = tmp_path / "setup.py" - setup_script.write_text(setup_py) + setup_script.write_text(setup_py, encoding="utf-8") dist = distutils.core.run_setup(setup_script, stop_after="init") - dist.script_args = [flag, "sdist"] + dist.script_args = flags + ["sdist"] dist.parse_command_line() # <- where the log level is set log_level = logger.getEffectiveLevel() log_level_name = logging.getLevelName(log_level) assert log_level_name == expected_level +def flaky_on_pypy(func): + @functools.wraps(func) + def _func(): + try: + func() + except AssertionError: # pragma: no cover + if IS_PYPY: + msg = "Flaky monkeypatch on PyPy (#4124)" + pytest.xfail(f"{msg}. Original discussion in #3707, #3709.") + raise + + return _func + + +@flaky_on_pypy def test_patching_does_not_cause_problems(): # Ensure `dist.log` is only patched if necessary + import _distutils_hack + import setuptools.logging + from distutils import dist setuptools.logging.configure() - if os.getenv("SETUPTOOLS_USE_DISTUTILS", "local").lower() == "local": + if _distutils_hack.enabled(): # Modern logging infra, no problematic patching. + assert dist.__file__ is None or "setuptools" in dist.__file__ assert isinstance(dist.log, logging.Logger) else: assert inspect.ismodule(dist.log) diff --git a/setuptools/tests/test_manifest.py b/setuptools/tests/test_manifest.py index 33b85d0644..903a528db0 100644 --- a/setuptools/tests/test_manifest.py +++ b/setuptools/tests/test_manifest.py @@ -1,22 +1,24 @@ """sdist tests""" +from __future__ import annotations + import contextlib +import io +import itertools +import logging import os import shutil import sys import tempfile -import itertools -import io -import logging -from distutils import log -from distutils.errors import DistutilsTemplateError + +import pytest from setuptools.command.egg_info import FileList, egg_info, translate_pattern from setuptools.dist import Distribution from setuptools.tests.textwrap import DALS -import pytest - +from distutils import log +from distutils.errors import DistutilsTemplateError IS_PYPY = '__pypy__' in sys.builtin_module_names @@ -32,14 +34,11 @@ def make_local_path(s): 'packages': ['app'], } -SETUP_PY = ( - """\ +SETUP_PY = f"""\ from setuptools import setup -setup(**%r) +setup(**{SETUP_ATTRS!r}) """ - % SETUP_ATTRS -) @contextlib.contextmanager @@ -53,7 +52,7 @@ def quiet(): def touch(filename): - open(filename, 'w').close() + open(filename, 'wb').close() # The set of files always in the manifest, including all files in the @@ -75,7 +74,7 @@ def touch(filename): ) -translate_specs = [ +translate_specs: list[tuple[str, list[str], list[str]]] = [ ('foo', ['foo'], ['bar', 'foobar']), ('foo/bar', ['foo/bar'], ['foo/bar/baz', './foo/bar', 'foo']), # Glob matching @@ -171,9 +170,9 @@ def teardown_method(self, method): class TestManifestTest(TempDirTestCase): def setup_method(self, method): - super(TestManifestTest, self).setup_method(method) + super().setup_method(method) - f = open(os.path.join(self.temp_dir, 'setup.py'), 'w') + f = open(os.path.join(self.temp_dir, 'setup.py'), 'w', encoding="utf-8") f.write(SETUP_PY) f.close() """ @@ -211,7 +210,8 @@ def setup_method(self, method): def make_manifest(self, contents): """Write a MANIFEST.in.""" - with open(os.path.join(self.temp_dir, 'MANIFEST.in'), 'w') as f: + manifest = os.path.join(self.temp_dir, 'MANIFEST.in') + with open(manifest, 'w', encoding="utf-8") as f: f.write(DALS(contents)) def get_files(self): @@ -256,44 +256,38 @@ def test_include_multiple(self): """Include with multiple patterns.""" ml = make_local_path self.make_manifest("include app/*.txt app/static/*") - files = default_files | set( - [ - ml('app/a.txt'), - ml('app/b.txt'), - ml('app/static/app.js'), - ml('app/static/app.js.map'), - ml('app/static/app.css'), - ml('app/static/app.css.map'), - ] - ) + files = default_files | set([ + ml('app/a.txt'), + ml('app/b.txt'), + ml('app/static/app.js'), + ml('app/static/app.js.map'), + ml('app/static/app.css'), + ml('app/static/app.css.map'), + ]) assert files == self.get_files() def test_graft(self): """Include the whole app/static/ directory.""" ml = make_local_path self.make_manifest("graft app/static") - files = default_files | set( - [ - ml('app/static/app.js'), - ml('app/static/app.js.map'), - ml('app/static/app.css'), - ml('app/static/app.css.map'), - ] - ) + files = default_files | set([ + ml('app/static/app.js'), + ml('app/static/app.js.map'), + ml('app/static/app.css'), + ml('app/static/app.css.map'), + ]) assert files == self.get_files() def test_graft_glob_syntax(self): """Include the whole app/static/ directory.""" ml = make_local_path self.make_manifest("graft */static") - files = default_files | set( - [ - ml('app/static/app.js'), - ml('app/static/app.js.map'), - ml('app/static/app.css'), - ml('app/static/app.css.map'), - ] - ) + files = default_files | set([ + ml('app/static/app.js'), + ml('app/static/app.js.map'), + ml('app/static/app.css'), + ml('app/static/app.css.map'), + ]) assert files == self.get_files() def test_graft_global_exclude(self): @@ -316,15 +310,13 @@ def test_global_include(self): global-include *.rst *.js *.css """ ) - files = default_files | set( - [ - '.hidden.rst', - 'testing.rst', - ml('app/c.rst'), - ml('app/static/app.js'), - ml('app/static/app.css'), - ] - ) + files = default_files | set([ + '.hidden.rst', + 'testing.rst', + ml('app/c.rst'), + ml('app/static/app.js'), + ml('app/static/app.css'), + ]) assert files == self.get_files() def test_graft_prune(self): @@ -374,9 +366,9 @@ def assertWarnings(self, caplog): def make_files(self, files): for file in files: file = os.path.join(self.temp_dir, file) - dirname, basename = os.path.split(file) + dirname, _basename = os.path.split(file) os.makedirs(dirname, exist_ok=True) - open(file, 'w').close() + touch(file) def test_process_template_line(self): # testing all MANIFEST.in template patterns @@ -384,27 +376,25 @@ def test_process_template_line(self): ml = make_local_path # simulated file list - self.make_files( - [ - 'foo.tmp', - 'ok', - 'xo', - 'four.txt', - 'buildout.cfg', - # filelist does not filter out VCS directories, - # it's sdist that does - ml('.hg/last-message.txt'), - ml('global/one.txt'), - ml('global/two.txt'), - ml('global/files.x'), - ml('global/here.tmp'), - ml('f/o/f.oo'), - ml('dir/graft-one'), - ml('dir/dir2/graft2'), - ml('dir3/ok'), - ml('dir3/sub/ok.txt'), - ] - ) + self.make_files([ + 'foo.tmp', + 'ok', + 'xo', + 'four.txt', + 'buildout.cfg', + # filelist does not filter out VCS directories, + # it's sdist that does + ml('.hg/last-message.txt'), + ml('global/one.txt'), + ml('global/two.txt'), + ml('global/files.x'), + ml('global/here.tmp'), + ml('f/o/f.oo'), + ml('dir/graft-one'), + ml('dir/dir2/graft2'), + ml('dir3/ok'), + ml('dir3/sub/ok.txt'), + ]) MANIFEST_IN = DALS( """\ @@ -492,14 +482,8 @@ def test_process_template_line_invalid(self): 'prune', 'blarg', ): - try: + with pytest.raises(DistutilsTemplateError): file_list.process_template_line(action) - except DistutilsTemplateError: - pass - except Exception: - assert False, "Incorrect error thrown" - else: - assert False, "Should have thrown an error" def test_include(self, caplog): caplog.set_level(logging.DEBUG) diff --git a/setuptools/tests/test_msvc14.py b/setuptools/tests/test_msvc14.py deleted file mode 100644 index 619293cada..0000000000 --- a/setuptools/tests/test_msvc14.py +++ /dev/null @@ -1,83 +0,0 @@ -""" -Tests for msvc support module (msvc14 unit tests). -""" - -import os -from distutils.errors import DistutilsPlatformError -import pytest -import sys - - -@pytest.mark.skipif(sys.platform != "win32", reason="These tests are only for win32") -class TestMSVC14: - """Python 3.8 "distutils/tests/test_msvccompiler.py" backport""" - - def test_no_compiler(self): - import setuptools.msvc as _msvccompiler - - # makes sure query_vcvarsall raises - # a DistutilsPlatformError if the compiler - # is not found - - def _find_vcvarsall(plat_spec): - return None, None - - old_find_vcvarsall = _msvccompiler._msvc14_find_vcvarsall - _msvccompiler._msvc14_find_vcvarsall = _find_vcvarsall - try: - pytest.raises( - DistutilsPlatformError, - _msvccompiler._msvc14_get_vc_env, - 'wont find this version', - ) - finally: - _msvccompiler._msvc14_find_vcvarsall = old_find_vcvarsall - - def test_get_vc_env_unicode(self): - import setuptools.msvc as _msvccompiler - - test_var = 'ṰḖṤṪ┅ṼẨṜ' - test_value = '₃⁴₅' - - # Ensure we don't early exit from _get_vc_env - old_distutils_use_sdk = os.environ.pop('DISTUTILS_USE_SDK', None) - os.environ[test_var] = test_value - try: - env = _msvccompiler._msvc14_get_vc_env('x86') - assert test_var.lower() in env - assert test_value == env[test_var.lower()] - finally: - os.environ.pop(test_var) - if old_distutils_use_sdk: - os.environ['DISTUTILS_USE_SDK'] = old_distutils_use_sdk - - def test_get_vc2017(self): - import setuptools.msvc as _msvccompiler - - # This function cannot be mocked, so pass it if we find VS 2017 - # and mark it skipped if we do not. - version, path = _msvccompiler._msvc14_find_vc2017() - if os.environ.get('APPVEYOR_BUILD_WORKER_IMAGE', '') in ['Visual Studio 2017']: - assert version - if version: - assert version >= 15 - assert os.path.isdir(path) - else: - pytest.skip("VS 2017 is not installed") - - def test_get_vc2015(self): - import setuptools.msvc as _msvccompiler - - # This function cannot be mocked, so pass it if we find VS 2015 - # and mark it skipped if we do not. - version, path = _msvccompiler._msvc14_find_vc2015() - if os.environ.get('APPVEYOR_BUILD_WORKER_IMAGE', '') in [ - 'Visual Studio 2015', - 'Visual Studio 2017', - ]: - assert version - if version: - assert version >= 14 - assert os.path.isdir(path) - else: - pytest.skip("VS 2015 is not installed") diff --git a/setuptools/tests/test_namespaces.py b/setuptools/tests/test_namespaces.py index cc54cc9f73..ef4a6f65c4 100644 --- a/setuptools/tests/test_namespaces.py +++ b/setuptools/tests/test_namespaces.py @@ -1,17 +1,12 @@ -import sys import subprocess +import sys -import pytest +from setuptools._path import paths_on_pythonpath from . import namespaces -from setuptools.command import test class TestNamespaces: - @pytest.mark.skipif( - sys.version_info < (3, 5), - reason="Requires importlib.util.module_from_spec", - ) def test_mixed_site_and_non_site(self, tmpdir): """ Installing two packages sharing the same namespace, one installed @@ -51,35 +46,7 @@ def test_mixed_site_and_non_site(self, tmpdir): '-c', 'import myns.pkgA; import myns.pkgB', ] - with test.test.paths_on_pythonpath(map(str, targets)): - subprocess.check_call(try_import) - - def test_pkg_resources_import(self, tmpdir): - """ - Ensure that a namespace package doesn't break on import - of pkg_resources. - """ - pkg = namespaces.build_namespace_package(tmpdir, 'myns.pkgA') - target = tmpdir / 'packages' - target.mkdir() - install_cmd = [ - sys.executable, - '-m', - 'pip', - 'install', - '-t', - str(target), - str(pkg), - ] - with test.test.paths_on_pythonpath([str(target)]): - subprocess.check_call(install_cmd) - namespaces.make_site_dir(target) - try_import = [ - sys.executable, - '-c', - 'import pkg_resources', - ] - with test.test.paths_on_pythonpath([str(target)]): + with paths_on_pythonpath(map(str, targets)): subprocess.check_call(try_import) def test_namespace_package_installed_and_cwd(self, tmpdir): @@ -102,42 +69,11 @@ def test_namespace_package_installed_and_cwd(self, tmpdir): subprocess.check_call(install_cmd) namespaces.make_site_dir(target) - # ensure that package imports and pkg_resources imports + # ensure that package imports pkg_resources_imp = [ sys.executable, '-c', - 'import pkg_resources; import myns.pkgA', + 'import myns.pkgA', ] - with test.test.paths_on_pythonpath([str(target)]): + with paths_on_pythonpath([str(target)]): subprocess.check_call(pkg_resources_imp, cwd=str(pkg_A)) - - def test_packages_in_the_same_namespace_installed_and_cwd(self, tmpdir): - """ - Installing one namespace package and also have another in the same - namespace in the current working directory, both of them must be - importable. - """ - pkg_A = namespaces.build_namespace_package(tmpdir, 'myns.pkgA') - pkg_B = namespaces.build_namespace_package(tmpdir, 'myns.pkgB') - target = tmpdir / 'packages' - # use pip to install to the target directory - install_cmd = [ - sys.executable, - '-m', - 'pip.__main__', - 'install', - str(pkg_A), - '-t', - str(target), - ] - subprocess.check_call(install_cmd) - namespaces.make_site_dir(target) - - # ensure that all packages import and pkg_resources imports - pkg_resources_imp = [ - sys.executable, - '-c', - 'import pkg_resources; import myns.pkgA; import myns.pkgB', - ] - with test.test.paths_on_pythonpath([str(target)]): - subprocess.check_call(pkg_resources_imp, cwd=str(pkg_B)) diff --git a/setuptools/tests/test_packageindex.py b/setuptools/tests/test_packageindex.py deleted file mode 100644 index 02870639d3..0000000000 --- a/setuptools/tests/test_packageindex.py +++ /dev/null @@ -1,307 +0,0 @@ -import sys -import os -import distutils.errors -import platform -import urllib.request -import urllib.error -import http.client -from unittest import mock - -import pytest - -import setuptools.package_index -from .textwrap import DALS - - -class TestPackageIndex: - def test_regex(self): - hash_url = 'http://other_url?:action=show_md5&' - hash_url += 'digest=0123456789abcdef0123456789abcdef' - doc = """ - Name - (md5) - """.lstrip().format( - **locals() - ) - assert setuptools.package_index.PYPI_MD5.match(doc) - - def test_bad_url_bad_port(self): - index = setuptools.package_index.PackageIndex() - url = 'http://127.0.0.1:0/nonesuch/test_package_index' - try: - v = index.open_url(url) - except Exception as exc: - assert url in str(exc) - else: - assert isinstance(v, urllib.error.HTTPError) - - def test_bad_url_typo(self): - # issue 16 - # easy_install inquant.contentmirror.plone breaks because of a typo - # in its home URL - index = setuptools.package_index.PackageIndex(hosts=('www.example.com',)) - - url = ( - 'url:%20https://svn.plone.org/svn' - '/collective/inquant.contentmirror.plone/trunk' - ) - try: - v = index.open_url(url) - except Exception as exc: - assert url in str(exc) - else: - assert isinstance(v, urllib.error.HTTPError) - - def test_bad_url_bad_status_line(self): - index = setuptools.package_index.PackageIndex(hosts=('www.example.com',)) - - def _urlopen(*args): - raise http.client.BadStatusLine('line') - - index.opener = _urlopen - url = 'http://example.com' - try: - index.open_url(url) - except Exception as exc: - assert 'line' in str(exc) - else: - raise AssertionError('Should have raise here!') - - def test_bad_url_double_scheme(self): - """ - A bad URL with a double scheme should raise a DistutilsError. - """ - index = setuptools.package_index.PackageIndex(hosts=('www.example.com',)) - - # issue 20 - url = 'http://http://svn.pythonpaste.org/Paste/wphp/trunk' - try: - index.open_url(url) - except distutils.errors.DistutilsError as error: - msg = str(error) - assert ( - 'nonnumeric port' in msg - or 'getaddrinfo failed' in msg - or 'Name or service not known' in msg - ) - return - raise RuntimeError("Did not raise") - - def test_bad_url_screwy_href(self): - index = setuptools.package_index.PackageIndex(hosts=('www.example.com',)) - - # issue #160 - if sys.version_info[0] == 2 and sys.version_info[1] == 7: - # this should not fail - url = 'http://example.com' - page = '' - index.process_index(url, page) - - def test_url_ok(self): - index = setuptools.package_index.PackageIndex(hosts=('www.example.com',)) - url = 'file:///tmp/test_package_index' - assert index.url_ok(url, True) - - def test_parse_bdist_wininst(self): - parse = setuptools.package_index.parse_bdist_wininst - - actual = parse('reportlab-2.5.win32-py2.4.exe') - expected = 'reportlab-2.5', '2.4', 'win32' - assert actual == expected - - actual = parse('reportlab-2.5.win32.exe') - expected = 'reportlab-2.5', None, 'win32' - assert actual == expected - - actual = parse('reportlab-2.5.win-amd64-py2.7.exe') - expected = 'reportlab-2.5', '2.7', 'win-amd64' - assert actual == expected - - actual = parse('reportlab-2.5.win-amd64.exe') - expected = 'reportlab-2.5', None, 'win-amd64' - assert actual == expected - - def test__vcs_split_rev_from_url(self): - """ - Test the basic usage of _vcs_split_rev_from_url - """ - vsrfu = setuptools.package_index.PackageIndex._vcs_split_rev_from_url - url, rev = vsrfu('https://example.com/bar@2995') - assert url == 'https://example.com/bar' - assert rev == '2995' - - def test_local_index(self, tmpdir): - """ - local_open should be able to read an index from the file system. - """ - index_file = tmpdir / 'index.html' - with index_file.open('w') as f: - f.write('
content
') - url = 'file:' + urllib.request.pathname2url(str(tmpdir)) + '/' - res = setuptools.package_index.local_open(url) - assert 'content' in res.read() - - def test_egg_fragment(self): - """ - EGG fragments must comply to PEP 440 - """ - epoch = [ - '', - '1!', - ] - releases = [ - '0', - '0.0', - '0.0.0', - ] - pre = [ - 'a0', - 'b0', - 'rc0', - ] - post = ['.post0'] - dev = [ - '.dev0', - ] - local = [ - ('', ''), - ('+ubuntu.0', '+ubuntu.0'), - ('+ubuntu-0', '+ubuntu.0'), - ('+ubuntu_0', '+ubuntu.0'), - ] - versions = [ - [''.join([e, r, p, loc]) for loc in locs] - for e in epoch - for r in releases - for p in sum([pre, post, dev], ['']) - for locs in local - ] - for v, vc in versions: - dists = list( - setuptools.package_index.distros_for_url( - 'http://example.com/example-foo.zip#egg=example-foo-' + v - ) - ) - assert dists[0].version == '' - assert dists[1].version == vc - - def test_download_git_with_rev(self, tmpdir): - url = 'git+https://github.example/group/project@master#egg=foo' - index = setuptools.package_index.PackageIndex() - - with mock.patch("os.system") as os_system_mock: - result = index.download(url, str(tmpdir)) - - os_system_mock.assert_called() - - expected_dir = str(tmpdir / 'project@master') - expected = ( - 'git clone --quiet ' 'https://github.example/group/project {expected_dir}' - ).format(**locals()) - first_call_args = os_system_mock.call_args_list[0][0] - assert first_call_args == (expected,) - - tmpl = 'git -C {expected_dir} checkout --quiet master' - expected = tmpl.format(**locals()) - assert os_system_mock.call_args_list[1][0] == (expected,) - assert result == expected_dir - - def test_download_git_no_rev(self, tmpdir): - url = 'git+https://github.example/group/project#egg=foo' - index = setuptools.package_index.PackageIndex() - - with mock.patch("os.system") as os_system_mock: - result = index.download(url, str(tmpdir)) - - os_system_mock.assert_called() - - expected_dir = str(tmpdir / 'project') - expected = ( - 'git clone --quiet ' 'https://github.example/group/project {expected_dir}' - ).format(**locals()) - os_system_mock.assert_called_once_with(expected) - - def test_download_svn(self, tmpdir): - url = 'svn+https://svn.example/project#egg=foo' - index = setuptools.package_index.PackageIndex() - - msg = r".*SVN download is not supported.*" - with pytest.raises(distutils.errors.DistutilsError, match=msg): - index.download(url, str(tmpdir)) - - -class TestContentCheckers: - def test_md5(self): - checker = setuptools.package_index.HashChecker.from_url( - 'http://foo/bar#md5=f12895fdffbd45007040d2e44df98478' - ) - checker.feed('You should probably not be using MD5'.encode('ascii')) - assert checker.hash.hexdigest() == 'f12895fdffbd45007040d2e44df98478' - assert checker.is_valid() - - def test_other_fragment(self): - "Content checks should succeed silently if no hash is present" - checker = setuptools.package_index.HashChecker.from_url( - 'http://foo/bar#something%20completely%20different' - ) - checker.feed('anything'.encode('ascii')) - assert checker.is_valid() - - def test_blank_md5(self): - "Content checks should succeed if a hash is empty" - checker = setuptools.package_index.HashChecker.from_url('http://foo/bar#md5=') - checker.feed('anything'.encode('ascii')) - assert checker.is_valid() - - def test_get_hash_name_md5(self): - checker = setuptools.package_index.HashChecker.from_url( - 'http://foo/bar#md5=f12895fdffbd45007040d2e44df98478' - ) - assert checker.hash_name == 'md5' - - def test_report(self): - checker = setuptools.package_index.HashChecker.from_url( - 'http://foo/bar#md5=f12895fdffbd45007040d2e44df98478' - ) - rep = checker.report(lambda x: x, 'My message about %s') - assert rep == 'My message about md5' - - -@pytest.fixture -def temp_home(tmpdir, monkeypatch): - key = ( - 'USERPROFILE' - if platform.system() == 'Windows' and sys.version_info > (3, 8) - else 'HOME' - ) - - monkeypatch.setitem(os.environ, key, str(tmpdir)) - return tmpdir - - -class TestPyPIConfig: - def test_percent_in_password(self, temp_home): - pypirc = temp_home / '.pypirc' - pypirc.write( - DALS( - """ - [pypi] - repository=https://pypi.org - username=jaraco - password=pity% - """ - ) - ) - cfg = setuptools.package_index.PyPIConfig() - cred = cfg.creds_by_repository['https://pypi.org'] - assert cred.username == 'jaraco' - assert cred.password == 'pity%' - - -@pytest.mark.timeout(1) -def test_REL_DoS(): - """ - REL should not hang on a contrived attack string. - """ - setuptools.package_index.REL.search('< rel=' + ' ' * 2**12) diff --git a/setuptools/tests/test_register.py b/setuptools/tests/test_register.py deleted file mode 100644 index ed85e9bbd3..0000000000 --- a/setuptools/tests/test_register.py +++ /dev/null @@ -1,19 +0,0 @@ -from setuptools.command.register import register -from setuptools.dist import Distribution -from setuptools.errors import RemovedCommandError - -from unittest import mock - -import pytest - - -class TestRegister: - def test_register_exception(self): - """Ensure that the register command has been properly removed.""" - dist = Distribution() - dist.dist_files = [(mock.Mock(), mock.Mock(), mock.Mock())] - - cmd = register(dist) - - with pytest.raises(RemovedCommandError): - cmd.run() diff --git a/setuptools/tests/test_sandbox.py b/setuptools/tests/test_sandbox.py deleted file mode 100644 index 4cbae2b679..0000000000 --- a/setuptools/tests/test_sandbox.py +++ /dev/null @@ -1,133 +0,0 @@ -"""develop tests -""" -import os -import types - -import pytest - -import pkg_resources -import setuptools.sandbox - - -class TestSandbox: - def test_devnull(self, tmpdir): - with setuptools.sandbox.DirectorySandbox(str(tmpdir)): - self._file_writer(os.devnull) - - @staticmethod - def _file_writer(path): - def do_write(): - with open(path, 'w') as f: - f.write('xxx') - - return do_write - - def test_setup_py_with_BOM(self): - """ - It should be possible to execute a setup.py with a Byte Order Mark - """ - target = pkg_resources.resource_filename(__name__, 'script-with-bom.py') - namespace = types.ModuleType('namespace') - setuptools.sandbox._execfile(target, vars(namespace)) - assert namespace.result == 'passed' - - def test_setup_py_with_CRLF(self, tmpdir): - setup_py = tmpdir / 'setup.py' - with setup_py.open('wb') as stream: - stream.write(b'"degenerate script"\r\n') - setuptools.sandbox._execfile(str(setup_py), globals()) - - -class TestExceptionSaver: - def test_exception_trapped(self): - with setuptools.sandbox.ExceptionSaver(): - raise ValueError("details") - - def test_exception_resumed(self): - with setuptools.sandbox.ExceptionSaver() as saved_exc: - raise ValueError("details") - - with pytest.raises(ValueError) as caught: - saved_exc.resume() - - assert isinstance(caught.value, ValueError) - assert str(caught.value) == 'details' - - def test_exception_reconstructed(self): - orig_exc = ValueError("details") - - with setuptools.sandbox.ExceptionSaver() as saved_exc: - raise orig_exc - - with pytest.raises(ValueError) as caught: - saved_exc.resume() - - assert isinstance(caught.value, ValueError) - assert caught.value is not orig_exc - - def test_no_exception_passes_quietly(self): - with setuptools.sandbox.ExceptionSaver() as saved_exc: - pass - - saved_exc.resume() - - def test_unpickleable_exception(self): - class CantPickleThis(Exception): - "This Exception is unpickleable because it's not in globals" - - def __repr__(self): - return 'CantPickleThis%r' % (self.args,) - - with setuptools.sandbox.ExceptionSaver() as saved_exc: - raise CantPickleThis('detail') - - with pytest.raises(setuptools.sandbox.UnpickleableException) as caught: - saved_exc.resume() - - assert str(caught.value) == "CantPickleThis('detail',)" - - def test_unpickleable_exception_when_hiding_setuptools(self): - """ - As revealed in #440, an infinite recursion can occur if an unpickleable - exception while setuptools is hidden. Ensure this doesn't happen. - """ - - class ExceptionUnderTest(Exception): - """ - An unpickleable exception (not in globals). - """ - - with pytest.raises(setuptools.sandbox.UnpickleableException) as caught: - with setuptools.sandbox.save_modules(): - setuptools.sandbox.hide_setuptools() - raise ExceptionUnderTest() - - (msg,) = caught.value.args - assert msg == 'ExceptionUnderTest()' - - def test_sandbox_violation_raised_hiding_setuptools(self, tmpdir): - """ - When in a sandbox with setuptools hidden, a SandboxViolation - should reflect a proper exception and not be wrapped in - an UnpickleableException. - """ - - def write_file(): - "Trigger a SandboxViolation by writing outside the sandbox" - with open('/etc/foo', 'w'): - pass - - with pytest.raises(setuptools.sandbox.SandboxViolation) as caught: - with setuptools.sandbox.save_modules(): - setuptools.sandbox.hide_setuptools() - with setuptools.sandbox.DirectorySandbox(str(tmpdir)): - write_file() - - cmd, args, kwargs = caught.value.args - assert cmd == 'open' - assert args == ('/etc/foo', 'w') - assert kwargs == {} - - msg = str(caught.value) - assert 'open' in msg - assert "('/etc/foo', 'w')" in msg diff --git a/setuptools/tests/test_scripts.py b/setuptools/tests/test_scripts.py new file mode 100644 index 0000000000..8641f7b639 --- /dev/null +++ b/setuptools/tests/test_scripts.py @@ -0,0 +1,12 @@ +from setuptools import _scripts + + +class TestWindowsScriptWriter: + def test_header(self): + hdr = _scripts.WindowsScriptWriter.get_header('') + assert hdr.startswith('#!') + assert hdr.endswith('\n') + hdr = hdr.lstrip('#!') + hdr = hdr.rstrip('\n') + # header should not start with an escaped quote + assert not hdr.startswith('\\"') diff --git a/setuptools/tests/test_sdist.py b/setuptools/tests/test_sdist.py index 2cd7482792..5b435fe111 100644 --- a/setuptools/tests/test_sdist.py +++ b/setuptools/tests/test_sdist.py @@ -1,33 +1,33 @@ """sdist tests""" +import contextlib +import io +import logging import os +import pathlib import sys +import tarfile import tempfile import unicodedata -import contextlib -import io -import tarfile -import logging -import distutils from inspect import cleandoc from pathlib import Path from unittest import mock +import jaraco.path import pytest -from distutils.core import run_setup -from setuptools import Command +from setuptools import Command, SetuptoolsDeprecationWarning from setuptools._importlib import metadata -from setuptools import SetuptoolsDeprecationWarning -from setuptools.command.sdist import sdist from setuptools.command.egg_info import manifest_maker +from setuptools.command.sdist import sdist from setuptools.dist import Distribution from setuptools.extension import Extension from setuptools.tests import fail_on_ascii -from .text import Filenames -import jaraco.path +from .text import Filenames +import distutils +from distutils.core import run_setup SETUP_ATTRS = { 'name': 'sdist_test', @@ -37,14 +37,11 @@ 'data_files': [("data", [os.path.join("d", "e.dat")])], } -SETUP_PY = ( - """\ +SETUP_PY = f"""\ from setuptools import setup -setup(**%r) +setup(**{SETUP_ATTRS!r}) """ - % SETUP_ATTRS -) EXTENSION = Extension( name="sdist_test.f", @@ -86,7 +83,7 @@ def decompose(path): def read_all_bytes(filename): - with io.open(filename, 'rb') as fp: + with open(filename, 'rb') as fp: return fp.read() @@ -116,18 +113,17 @@ def latin1_fail(): def touch(path): - if isinstance(path, str): - path = Path(path) - path.write_text('', encoding='utf-8') + open(path, 'wb').close() return path def symlink_or_skip_test(src, dst): try: os.symlink(src, dst) - return dst except (OSError, NotImplementedError): pytest.skip("symlink not supported in OS") + return None + return dst class TestSdistTest: @@ -259,20 +255,16 @@ def test_symlinked_extension_sources(self): assert path not in manifest _INVALID_PATHS = { - "must be relative": lambda: ( - os.path.abspath(os.path.join("sdist_test", "f.h")) - ), - "can't have `..` segments": lambda: ( - os.path.join("sdist_test", "..", "sdist_test", "f.h") + "must be relative": lambda: os.path.abspath(os.path.join("sdist_test", "f.h")), + "can't have `..` segments": lambda: os.path.join( + "sdist_test", "..", "sdist_test", "f.h" ), - "doesn't exist": lambda: ( - os.path.join("sdist_test", "this_file_does_not_exist.h") + "doesn't exist": lambda: os.path.join( + "sdist_test", "this_file_does_not_exist.h" ), - "must be inside the project root": lambda: ( - symlink_or_skip_test( - touch(os.path.join("..", "outside_of_project_root.h")), - "symlink.h", - ) + "must be inside the project root": lambda: symlink_or_skip_test( + touch(os.path.join("..", "outside_of_project_root.h")), + "symlink.h", ), } @@ -386,7 +378,7 @@ def test_setup_py_missing(self): assert 'setup.py' not in manifest def test_setup_py_excluded(self): - with open("MANIFEST.in", "w") as manifest_file: + with open("MANIFEST.in", "w", encoding="utf-8") as manifest_file: manifest_file.write("exclude setup.py") dist = Distribution(SETUP_ATTRS) @@ -428,6 +420,46 @@ def test_defaults_case_sensitivity(self, source_dir): assert 'setup.py' not in manifest, manifest assert 'setup.cfg' not in manifest, manifest + def test_exclude_dev_only_cache_folders(self, source_dir): + included = { + # Emulate problem in https://github.com/pypa/setuptools/issues/4601 + "MANIFEST.in": ( + "global-include LICEN[CS]E* COPYING* NOTICE* AUTHORS*\n" + "global-include *.txt\n" + ), + # For the sake of being conservative and limiting unforeseen side-effects + # we just exclude dev-only cache folders at the root of the repository: + "test/.venv/lib/python3.9/site-packages/bar-2.dist-info/AUTHORS.rst": "", + "src/.nox/py/lib/python3.12/site-packages/bar-2.dist-info/COPYING.txt": "", + "doc/.tox/default/lib/python3.11/site-packages/foo-4.dist-info/LICENSE": "", + # Let's test against false positives with similarly named files: + ".venv-requirements.txt": "", + ".tox-coveragerc.txt": "", + ".noxy/coveragerc.txt": "", + } + + excluded = { + # .tox/.nox/.venv are well-know folders present at the root of Python repos + # and therefore should be excluded + ".tox/release/lib/python3.11/site-packages/foo-4.dist-info/LICENSE": "", + ".nox/py/lib/python3.12/site-packages/bar-2.dist-info/COPYING.txt": "", + ".venv/lib/python3.9/site-packages/bar-2.dist-info/AUTHORS.rst": "", + } + + for file, content in {**excluded, **included}.items(): + Path(source_dir, file).parent.mkdir(parents=True, exist_ok=True) + Path(source_dir, file).write_text(content, encoding="utf-8") + + cmd = self.setup_with_extension() + self.assert_package_data_in_manifest(cmd) + manifest = {f.replace(os.sep, '/') for f in cmd.filelist.files} + for path in excluded: + assert os.path.exists(path) + assert path not in manifest, (path, manifest) + for path in included: + assert os.path.exists(path) + assert path in manifest, (path, manifest) + @fail_on_ascii def test_manifest_is_written_with_utf8_encoding(self): # Test for #303. @@ -441,7 +473,7 @@ def test_manifest_is_written_with_utf8_encoding(self): filename = os.path.join('sdist_test', 'smörbröd.py') # Must create the file or it will get stripped. - open(filename, 'w').close() + touch(filename) # Add UTF-8 filename and write manifest with quiet(): @@ -469,7 +501,7 @@ def test_write_manifest_allows_utf8_filenames(self): filename = os.path.join(b'sdist_test', Filenames.utf_8) # Must touch the file or risk removal - open(filename, "w").close() + touch(filename) # Add filename and write manifest with quiet(): @@ -546,7 +578,7 @@ def test_manifest_is_read_with_utf8_encoding(self): manifest.close() # The file must exist to be included in the filelist - open(filename, 'w').close() + touch(filename) # Re-read manifest cmd.filelist.files = [] @@ -577,7 +609,7 @@ def test_read_manifest_skips_non_utf8_filenames(self): manifest.close() # The file must exist to be included in the filelist - open(filename, 'w').close() + touch(filename) # Re-read manifest cmd.filelist.files = [] @@ -598,7 +630,7 @@ def test_sdist_with_utf8_encoded_filename(self): cmd.ensure_finalized() filename = os.path.join(b'sdist_test', Filenames.utf_8) - open(filename, 'w').close() + touch(filename) with quiet(): cmd.run() @@ -639,7 +671,7 @@ def test_sdist_with_latin1_encoded_filename(self): # Latin-1 filename filename = os.path.join(b'sdist_test', Filenames.latin_1) - open(filename, 'w').close() + touch(filename) assert os.path.isfile(filename) with quiet(): @@ -658,7 +690,7 @@ def test_sdist_with_latin1_encoded_filename(self): else: # The Latin-1 filename should have been skipped filename = filename.decode('latin-1') - filename not in cmd.filelist.files + assert filename not in cmd.filelist.files _EXAMPLE_DIRECTIVES = { "setup.cfg - long_description and version": """ @@ -672,12 +704,21 @@ def test_sdist_with_latin1_encoded_filename(self): [project] name = "testing" readme = "USAGE.rst" - license = {file = "DOWHATYOUWANT"} + license-files = ["DOWHATYOUWANT"] dynamic = ["version"] [tool.setuptools.dynamic] version = {file = ["src/VERSION.txt"]} """, "pyproject.toml - directive with str instead of list": """ + [project] + name = "testing" + readme = "USAGE.rst" + license-files = ["DOWHATYOUWANT"] + dynamic = ["version"] + [tool.setuptools.dynamic] + version = {file = "src/VERSION.txt"} + """, + "pyproject.toml - deprecated license table with file entry": """ [project] name = "testing" readme = "USAGE.rst" @@ -689,6 +730,9 @@ def test_sdist_with_latin1_encoded_filename(self): } @pytest.mark.parametrize("config", _EXAMPLE_DIRECTIVES.keys()) + @pytest.mark.filterwarnings( + "ignore:.project.license. as a TOML table is deprecated" + ) def test_add_files_referenced_by_config_directives(self, source_dir, config): config_file, _, _ = config.partition(" - ") config_text = self._EXAMPLE_DIRECTIVES[config] @@ -736,7 +780,7 @@ def test_pyproject_toml_excluded(self, source_dir): Check that pyproject.toml can excluded even if present """ touch(source_dir / 'pyproject.toml') - with open('MANIFEST.in', 'w') as mts: + with open('MANIFEST.in', 'w', encoding="utf-8") as mts: print('exclude pyproject.toml', file=mts) dist = Distribution(SETUP_ATTRS) dist.script_name = 'setup.py' @@ -765,14 +809,11 @@ def test_build_subcommand_source_files(self, source_dir): build.sub_commands = [*build.sub_commands, ("build_custom", None)] class build_custom(Command): - def initialize_options(self): - ... + def initialize_options(self): ... - def finalize_options(self): - ... + def finalize_options(self): ... - def run(self): - ... + def run(self): ... def get_source_files(self): return ['.myfile~'] @@ -787,6 +828,21 @@ def get_source_files(self): manifest = cmd.filelist.files assert '.myfile~' in manifest + @pytest.mark.skipif("os.environ.get('SETUPTOOLS_USE_DISTUTILS') == 'stdlib'") + def test_build_base_pathlib(self, source_dir): + """ + Ensure if build_base is a pathlib.Path, the build still succeeds. + """ + dist = Distribution({ + **SETUP_ATTRS, + "script_name": "setup.py", + "options": {"build": {"build_base": pathlib.Path('build')}}, + }) + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + def test_default_revctrl(): """ @@ -913,3 +969,12 @@ def run_sdist(monkeypatch, project): archive = next((project / "dist").glob("*.tar.gz")) with tarfile.open(str(archive)) as tar: return set(tar.getnames()) + + +def test_sanity_check_setuptools_own_sdist(setuptools_sdist): + with tarfile.open(setuptools_sdist) as tar: + files = tar.getnames() + + # setuptools sdist should not include the .tox folder + tox_files = [name for name in files if ".tox" in name] + assert len(tox_files) == 0, f"not empty {tox_files}" diff --git a/setuptools/tests/test_setopt.py b/setuptools/tests/test_setopt.py index 3600863214..ccf25618a5 100644 --- a/setuptools/tests/test_setopt.py +++ b/setuptools/tests/test_setopt.py @@ -1,4 +1,3 @@ -import io import configparser from setuptools.command import setopt @@ -8,13 +7,13 @@ class TestEdit: @staticmethod def parse_config(filename): parser = configparser.ConfigParser() - with io.open(filename, encoding='utf-8') as reader: + with open(filename, encoding='utf-8') as reader: parser.read_file(reader) return parser @staticmethod def write_text(file, content): - with io.open(file, 'wb') as strm: + with open(file, 'wb') as strm: strm.write(content.encode('utf-8')) def test_utf8_encoding_retained(self, tmpdir): diff --git a/setuptools/tests/test_setuptools.py b/setuptools/tests/test_setuptools.py index 1ca5523d20..c57908b026 100644 --- a/setuptools/tests/test_setuptools.py +++ b/setuptools/tests/test_setuptools.py @@ -1,27 +1,27 @@ """Tests for the 'setuptools' package""" -import sys import os -import distutils.core -import distutils.cmd -from distutils.errors import DistutilsOptionError -from distutils.errors import DistutilsSetupError -from distutils.core import Extension +import re +import sys from zipfile import ZipFile import pytest +from packaging.version import Version import setuptools -import setuptools.dist import setuptools.depends as dep +import setuptools.dist from setuptools.depends import Require -from setuptools.extern.packaging.version import Version +import distutils.cmd +import distutils.core +from distutils.core import Extension +from distutils.errors import DistutilsSetupError @pytest.fixture(autouse=True) def isolated_dir(tmpdir_cwd): - yield + return def makeSetup(**args): @@ -53,7 +53,7 @@ def testExtractConst(self): def f1(): global x, y, z x = "test" - y = z + y = z # pyright: ignore[reportUnboundVariable] # Explicitly testing for this runtime issue fc = f1.__code__ @@ -61,46 +61,50 @@ def f1(): assert dep.extract_constant(fc, 'q', -1) is None # constant assigned - dep.extract_constant(fc, 'x', -1) == "test" + assert dep.extract_constant(fc, 'x', -1) == "test" # expression assigned - dep.extract_constant(fc, 'y', -1) == -1 + assert dep.extract_constant(fc, 'y', -1) == -1 # recognized name, not assigned - dep.extract_constant(fc, 'z', -1) is None + assert dep.extract_constant(fc, 'z', -1) is None def testFindModule(self): with pytest.raises(ImportError): dep.find_module('no-such.-thing') with pytest.raises(ImportError): dep.find_module('setuptools.non-existent') - f, p, i = dep.find_module('setuptools.tests') + f, _p, _i = dep.find_module('setuptools.tests') f.close() - @needs_bytecode - def testModuleExtract(self): - from json import __version__ + @pytest.fixture + def sample_module(self, monkeypatch, tmp_path): + monkeypatch.syspath_prepend(str(tmp_path)) + module = "mod_with_version" + version = "2.0.9" + file = tmp_path / f"{module}.py" + file.write_text(f"__version__ = {version!r}", encoding="utf-8") + return (module, version) - assert dep.get_module_constant('json', '__version__') == __version__ + @needs_bytecode + def testModuleExtract(self, sample_module): + (module, version) = sample_module + assert dep.get_module_constant(module, '__version__') == version assert dep.get_module_constant('sys', 'version') == sys.version - assert ( - dep.get_module_constant('setuptools.tests.test_setuptools', '__doc__') - == __doc__ - ) + assert dep.get_module_constant(__name__, '__doc__') == __doc__ @needs_bytecode - def testRequire(self): - req = Require('Json', '1.0.3', 'json') + def testRequire(self, sample_module): + (module, version) = sample_module + req = Require('GivenName', '1.0.3', module) - assert req.name == 'Json' - assert req.module == 'json' + assert req.name == 'GivenName' + assert req.module == module assert req.requested_version == Version('1.0.3') assert req.attribute == '__version__' - assert req.full_name() == 'Json-1.0.3' - - from json import __version__ + assert req.full_name() == 'GivenName-1.0.3' - assert str(req.get_version()) == __version__ + assert str(req.get_version()) == version assert req.version_ok('1.0.9') assert not req.version_ok('0.9.1') assert not req.version_ok('unknown') @@ -221,43 +225,6 @@ def testInvalidIncludeExclude(self): self.dist.exclude(package_dir=['q']) -class TestCommandTests: - def testTestIsCommand(self): - test_cmd = makeSetup().get_command_obj('test') - assert isinstance(test_cmd, distutils.cmd.Command) - - def testLongOptSuiteWNoDefault(self): - ts1 = makeSetup(script_args=['test', '--test-suite=foo.tests.suite']) - ts1 = ts1.get_command_obj('test') - ts1.ensure_finalized() - assert ts1.test_suite == 'foo.tests.suite' - - def testDefaultSuite(self): - ts2 = makeSetup(test_suite='bar.tests.suite').get_command_obj('test') - ts2.ensure_finalized() - assert ts2.test_suite == 'bar.tests.suite' - - def testDefaultWModuleOnCmdLine(self): - ts3 = makeSetup( - test_suite='bar.tests', script_args=['test', '-m', 'foo.tests'] - ).get_command_obj('test') - ts3.ensure_finalized() - assert ts3.test_module == 'foo.tests' - assert ts3.test_suite == 'foo.tests.test_suite' - - def testConflictingOptions(self): - ts4 = makeSetup( - script_args=['test', '-m', 'bar.tests', '-s', 'foo.tests.suite'] - ).get_command_obj('test') - with pytest.raises(DistutilsOptionError): - ts4.ensure_finalized() - - def testNoSuite(self): - ts5 = makeSetup().get_command_obj('test') - ts5.ensure_finalized() - assert ts5.test_suite is None - - @pytest.fixture def example_source(tmpdir): tmpdir.mkdir('foo') @@ -294,13 +261,15 @@ def can_symlink(tmpdir): os.remove(link_fn) -def test_findall_missing_symlink(tmpdir, can_symlink): +@pytest.mark.usefixtures("can_symlink") +def test_findall_missing_symlink(tmpdir): with tmpdir.as_cwd(): os.symlink('foo', 'bar') found = list(setuptools.findall()) assert found == [] +@pytest.mark.xfail(reason="unable to exclude tests; #4475 #3260") def test_its_own_wheel_does_not_contain_tests(setuptools_wheel): with ZipFile(setuptools_wheel) as zipfile: contents = [f.replace(os.sep, '/') for f in zipfile.namelist()] @@ -309,6 +278,17 @@ def test_its_own_wheel_does_not_contain_tests(setuptools_wheel): assert '/tests/' not in member -def test_convert_path_deprecated(): - with pytest.warns(setuptools.SetuptoolsDeprecationWarning): - setuptools.convert_path('setuptools/tests') +def test_wheel_includes_cli_scripts(setuptools_wheel): + with ZipFile(setuptools_wheel) as zipfile: + contents = [f.replace(os.sep, '/') for f in zipfile.namelist()] + + assert any('cli-64.exe' in member for member in contents) + + +def test_wheel_includes_vendored_metadata(setuptools_wheel): + with ZipFile(setuptools_wheel) as zipfile: + contents = [f.replace(os.sep, '/') for f in zipfile.namelist()] + + assert any( + re.search(r'_vendor/.*\.dist-info/METADATA', member) for member in contents + ) diff --git a/setuptools/tests/test_shutil_wrapper.py b/setuptools/tests/test_shutil_wrapper.py new file mode 100644 index 0000000000..74ff7e9a89 --- /dev/null +++ b/setuptools/tests/test_shutil_wrapper.py @@ -0,0 +1,23 @@ +import stat +import sys +from unittest.mock import Mock + +from setuptools import _shutil + + +def test_rmtree_readonly(monkeypatch, tmp_path): + """Verify onerr works as expected""" + + tmp_dir = tmp_path / "with_readonly" + tmp_dir.mkdir() + some_file = tmp_dir.joinpath("file.txt") + some_file.touch() + some_file.chmod(stat.S_IREAD) + + expected_count = 1 if sys.platform.startswith("win") else 0 + chmod_fn = Mock(wraps=_shutil.attempt_chmod_verbose) + monkeypatch.setattr(_shutil, "attempt_chmod_verbose", chmod_fn) + + _shutil.rmtree(tmp_dir) + assert chmod_fn.call_count == expected_count + assert not tmp_dir.is_dir() diff --git a/setuptools/tests/test_test.py b/setuptools/tests/test_test.py deleted file mode 100644 index 989996f3ba..0000000000 --- a/setuptools/tests/test_test.py +++ /dev/null @@ -1,39 +0,0 @@ -import pytest -from jaraco import path - -from setuptools.command.test import test -from setuptools.dist import Distribution - -from .textwrap import DALS - - -@pytest.mark.usefixtures('tmpdir_cwd') -def test_tests_are_run_once(capfd): - params = dict( - packages=['dummy'], - ) - files = { - 'setup.py': 'from setuptools import setup; setup(' - + ','.join(f'{name}={params[name]!r}' for name in params) - + ')', - 'dummy': { - '__init__.py': '', - 'test_dummy.py': DALS( - """ - import unittest - class TestTest(unittest.TestCase): - def test_test(self): - print('Foo') - """ - ), - }, - } - path.build(files) - dist = Distribution(params) - dist.script_name = 'setup.py' - cmd = test(dist) - cmd.ensure_finalized() - cmd.run() - out, err = capfd.readouterr() - assert out.endswith('Foo\n') - assert len(out.split('Foo')) == 2 diff --git a/setuptools/tests/test_upload.py b/setuptools/tests/test_upload.py deleted file mode 100644 index 4ed59bc24d..0000000000 --- a/setuptools/tests/test_upload.py +++ /dev/null @@ -1,19 +0,0 @@ -from setuptools.command.upload import upload -from setuptools.dist import Distribution -from setuptools.errors import RemovedCommandError - -from unittest import mock - -import pytest - - -class TestUpload: - def test_upload_exception(self): - """Ensure that the register command has been properly removed.""" - dist = Distribution() - dist.dist_files = [(mock.Mock(), mock.Mock(), mock.Mock())] - - cmd = upload(dist) - - with pytest.raises(RemovedCommandError): - cmd.run() diff --git a/setuptools/tests/test_virtualenv.py b/setuptools/tests/test_virtualenv.py index d02993fd6b..b02949baf9 100644 --- a/setuptools/tests/test_virtualenv.py +++ b/setuptools/tests/test_virtualenv.py @@ -1,17 +1,11 @@ import os -import sys import subprocess -from urllib.request import urlopen +import sys from urllib.error import URLError - -import pathlib +from urllib.request import urlopen import pytest -from . import contexts -from .textwrap import DALS -from .test_easy_install import make_nspkg_sdist - @pytest.fixture(autouse=True) def pytest_virtualenv_works(venv): @@ -111,86 +105,9 @@ def test_pip_upgrade_from_source( venv.run(["pip", "install", "--no-cache-dir", "--upgrade", str(setuptools_sdist)]) -def _check_test_command_install_requirements(venv, tmpdir): - """ - Check the test command will install all required dependencies. - """ - - def sdist(distname, version): - dist_path = tmpdir.join('%s-%s.tar.gz' % (distname, version)) - make_nspkg_sdist(str(dist_path), distname, version) - return dist_path - - dependency_links = [ - pathlib.Path(str(dist_path)).as_uri() - for dist_path in ( - sdist('foobar', '2.4'), - sdist('bits', '4.2'), - sdist('bobs', '6.0'), - sdist('pieces', '0.6'), - ) - ] - with tmpdir.join('setup.py').open('w') as fp: - fp.write( - DALS( - ''' - from setuptools import setup - - setup( - dependency_links={dependency_links!r}, - install_requires=[ - 'barbazquux1; sys_platform in ""', - 'foobar==2.4', - ], - setup_requires='bits==4.2', - tests_require=""" - bobs==6.0 - """, - extras_require={{ - 'test': ['barbazquux2'], - ':"" in sys_platform': 'pieces==0.6', - ':python_version > "1"': """ - pieces - foobar - """, - }} - ) - '''.format( - dependency_links=dependency_links - ) - ) - ) - with tmpdir.join('test.py').open('w') as fp: - fp.write( - DALS( - ''' - import foobar - import bits - import bobs - import pieces - - open('success', 'w').close() - ''' - ) - ) - - cmd = ["python", 'setup.py', 'test', '-s', 'test'] - venv.run(cmd, cwd=str(tmpdir)) - assert tmpdir.join('success').check() - - -def test_test_command_install_requirements(venv, tmpdir, tmpdir_cwd): - # Ensure pip is installed. - venv.run(["python", "-c", "import pip"]) - # disable index URL so bits and bobs aren't requested from PyPI - with contexts.environment(PYTHONPATH=None, PIP_NO_INDEX="1"): - _check_test_command_install_requirements(venv, tmpdir) - - def test_no_missing_dependencies(bare_venv, request): """ Quick and dirty test to ensure all external dependencies are vendored. """ setuptools_dir = request.config.rootdir - for command in ('upload',): # sorted(distutils.command.__all__): - bare_venv.run(['python', 'setup.py', command, '-h'], cwd=setuptools_dir) + bare_venv.run(['python', 'setup.py', '--help'], cwd=setuptools_dir) diff --git a/setuptools/tests/test_warnings.py b/setuptools/tests/test_warnings.py index b5da66b9d6..41193d4f71 100644 --- a/setuptools/tests/test_warnings.py +++ b/setuptools/tests/test_warnings.py @@ -4,7 +4,6 @@ from setuptools.warnings import SetuptoolsDeprecationWarning, SetuptoolsWarning - _EXAMPLES = { "default": dict( args=("Hello {x}", "\n\t{target} {v:.1f}"), @@ -18,7 +17,7 @@ ******************************************************************************** !! - """, # noqa, + """, ), "futue_due_date": dict( args=("Summary", "Lorem ipsum"), @@ -35,7 +34,7 @@ ******************************************************************************** !! - """, # noqa + """, ), "past_due_date_with_docs": dict( args=("Summary", "Lorem ipsum"), @@ -54,7 +53,7 @@ ******************************************************************************** !! - """, # noqa + """, ), } @@ -99,7 +98,7 @@ class _MyDeprecation(SetuptoolsDeprecationWarning): ******************************************************************************** !! - """ # noqa + """ assert str(exc_info.value) == cleandoc(expected) diff --git a/setuptools/tests/test_wheel.py b/setuptools/tests/test_wheel.py index 114b2e91f7..c3b215a474 100644 --- a/setuptools/tests/test_wheel.py +++ b/setuptools/tests/test_wheel.py @@ -1,30 +1,31 @@ -"""wheel tests -""" +"""wheel tests""" + +from __future__ import annotations -from distutils.sysconfig import get_config_var -from distutils.util import get_platform import contextlib -import pathlib -import stat import glob import inspect import os -import shutil +import pathlib +import stat import subprocess import sys +import sysconfig import zipfile +from typing import Any import pytest from jaraco import path +from packaging.tags import parse_tag -from pkg_resources import Distribution, PathMetadata, PY_MAJOR -from setuptools.extern.packaging.utils import canonicalize_name -from setuptools.extern.packaging.tags import parse_tag +from setuptools._importlib import metadata from setuptools.wheel import Wheel from .contexts import tempdir from .textwrap import DALS +from distutils.sysconfig import get_config_var +from distutils.util import get_platform WHEEL_INFO_TESTS = ( ('invalid.whl', ValueError), @@ -92,12 +93,12 @@ def build_wheel(extra_file_defs=None, **kwargs): file_defs = { 'setup.py': ( DALS( - ''' + """ # -*- coding: utf-8 -*- from setuptools import setup import setuptools setup(**%r) - ''' + """ ) % kwargs ).encode('utf-8'), @@ -113,11 +114,11 @@ def build_wheel(extra_file_defs=None, **kwargs): def tree_set(root): - contents = set() - for dirpath, dirnames, filenames in os.walk(root): - for filename in filenames: - contents.add(os.path.join(os.path.relpath(dirpath, root), filename)) - return contents + return { + os.path.join(os.path.relpath(dirpath, root), filename) + for dirpath, dirnames, filenames in os.walk(root) + for filename in filenames + } def flatten_tree(tree): @@ -138,7 +139,7 @@ def flatten_tree(tree): def format_install_tree(tree): return { x.format( - py_version=PY_MAJOR, + py_version=sysconfig.get_python_version(), platform=get_platform(), shlib_ext=get_config_var('EXT_SUFFIX') or get_config_var('SO'), ) @@ -157,41 +158,40 @@ def _check_wheel_install( exp = tree_set(install_dir) assert install_tree.issubset(exp), install_tree - exp - metadata = PathMetadata(egg_path, os.path.join(egg_path, 'EGG-INFO')) - dist = Distribution.from_filename(egg_path, metadata=metadata) - assert dist.project_name == project_name - assert dist.version == version - if requires_txt is None: - assert not dist.has_metadata('requires.txt') - else: - # Order must match to ensure reproducibility. - assert requires_txt == dist.get_metadata('requires.txt').lstrip() + (dist,) = metadata.Distribution.discover(path=[egg_path]) + + # pyright is nitpicky; fine to assume dist.metadata.__getitem__ will fail or return None + # (https://github.com/pypa/setuptools/pull/5006#issuecomment-2894774288) + assert dist.metadata['Name'] == project_name # pyright: ignore # noqa: PGH003 + assert dist.metadata['Version'] == version # pyright: ignore # noqa: PGH003 + assert dist.read_text('requires.txt') == requires_txt class Record: - def __init__(self, id, **kwargs): + def __init__(self, id, **kwargs) -> None: self._id = id self._fields = kwargs - def __repr__(self): - return '%s(**%r)' % (self._id, self._fields) + def __repr__(self) -> str: + return f'{self._id}(**{self._fields!r})' -WHEEL_INSTALL_TESTS = ( +# Using Any to avoid possible type union issues later in test +# making a TypedDict is not worth in a test and anonymous/inline TypedDict are experimental +# https://github.com/python/mypy/issues/9884 +WHEEL_INSTALL_TESTS: tuple[dict[str, Any], ...] = ( dict( id='basic', file_defs={'foo': {'__init__.py': ''}}, setup_kwargs=dict( packages=['foo'], ), - install_tree=flatten_tree( - { - 'foo-1.0-py{py_version}.egg': { - 'EGG-INFO': ['PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt'], - 'foo': ['__init__.py'], - } + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': ['PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt'], + 'foo': ['__init__.py'], } - ), + }), ), dict( id='utf-8', @@ -203,28 +203,26 @@ def __repr__(self): id='data', file_defs={ 'data.txt': DALS( - ''' + """ Some data... - ''' + """ ), }, setup_kwargs=dict( data_files=[('data_dir', ['data.txt'])], ), - install_tree=flatten_tree( - { - 'foo-1.0-py{py_version}.egg': { - 'EGG-INFO': ['PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt'], - 'data_dir': ['data.txt'], - } + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': ['PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt'], + 'data_dir': ['data.txt'], } - ), + }), ), dict( id='extension', file_defs={ 'extension.c': DALS( - ''' + """ #include "Python.h" #if PY_MAJOR_VERSION >= 3 @@ -264,7 +262,7 @@ def __repr__(self): return module; #endif } - ''' + """ ), }, setup_kwargs=dict( @@ -274,171 +272,162 @@ def __repr__(self): ) ], ), - install_tree=flatten_tree( - { - 'foo-1.0-py{py_version}-{platform}.egg': [ - 'extension{shlib_ext}', - { - 'EGG-INFO': [ - 'PKG-INFO', - 'RECORD', - 'WHEEL', - 'top_level.txt', - ] - }, - ] - } - ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}-{platform}.egg': [ + 'extension{shlib_ext}', + { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + ] + }, + ] + }), ), dict( id='header', file_defs={ 'header.h': DALS( - ''' - ''' + """ + """ ), }, setup_kwargs=dict( headers=['header.h'], ), - install_tree=flatten_tree( - { - 'foo-1.0-py{py_version}.egg': [ - 'header.h', - { - 'EGG-INFO': [ - 'PKG-INFO', - 'RECORD', - 'WHEEL', - 'top_level.txt', - ] - }, - ] - } - ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': [ + 'header.h', + { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + ] + }, + ] + }), ), dict( id='script', file_defs={ 'script.py': DALS( - ''' + """ #/usr/bin/python print('hello world!') - ''' + """ ), 'script.sh': DALS( - ''' + """ #/bin/sh echo 'hello world!' - ''' + """ ), }, setup_kwargs=dict( scripts=['script.py', 'script.sh'], ), - install_tree=flatten_tree( - { - 'foo-1.0-py{py_version}.egg': { - 'EGG-INFO': [ - 'PKG-INFO', - 'RECORD', - 'WHEEL', - 'top_level.txt', - {'scripts': ['script.py', 'script.sh']}, - ] - } + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + {'scripts': ['script.py', 'script.sh']}, + ] } - ), + }), ), dict( id='requires1', install_requires='foobar==2.0', - install_tree=flatten_tree( - { - 'foo-1.0-py{py_version}.egg': { - 'EGG-INFO': [ - 'PKG-INFO', - 'RECORD', - 'WHEEL', - 'requires.txt', - 'top_level.txt', - ] - } + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'requires.txt', + 'top_level.txt', + ] } - ), + }), requires_txt=DALS( - ''' + """ foobar==2.0 - ''' + """ ), ), dict( id='requires2', - install_requires=''' + install_requires=f""" bar - foo<=2.0; %r in sys_platform - ''' - % sys.platform, + foo<=2.0; {sys.platform!r} in sys_platform + """, requires_txt=DALS( - ''' + """ bar foo<=2.0 - ''' + """ ), ), dict( id='requires3', - install_requires=''' - bar; %r != sys_platform - ''' - % sys.platform, + install_requires=f""" + bar; {sys.platform!r} != sys_platform + """, ), dict( id='requires4', - install_requires=''' + install_requires=""" foo - ''', + """, extras_require={ 'extra': 'foobar>3', }, requires_txt=DALS( - ''' + """ foo [extra] foobar>3 - ''' + """ ), ), dict( id='requires5', extras_require={ - 'extra': 'foobar; %r != sys_platform' % sys.platform, + 'extra': f'foobar; {sys.platform!r} != sys_platform', }, - requires_txt=DALS( - ''' + requires_txt='\n' + + DALS( + """ [extra] - ''' + """ ), ), dict( id='requires_ensure_order', - install_requires=''' + install_requires=""" foo bar baz qux - ''', + """, extras_require={ - 'extra': ''' + 'extra': """ foobar>3 barbaz>4 bazqux>5 quxzap>6 - ''', + """, }, requires_txt=DALS( - ''' + """ foo bar baz @@ -449,7 +438,7 @@ def __repr__(self): barbaz>4 bazqux>5 quxzap>6 - ''' + """ ), ), dict( @@ -463,28 +452,26 @@ def __repr__(self): namespace_packages=['foo'], packages=['foo.bar'], ), - install_tree=flatten_tree( - { - 'foo-1.0-py{py_version}.egg': [ - 'foo-1.0-py{py_version}-nspkg.pth', - { - 'EGG-INFO': [ - 'PKG-INFO', - 'RECORD', - 'WHEEL', - 'namespace_packages.txt', - 'top_level.txt', - ] - }, - { - 'foo': [ - '__init__.py', - {'bar': ['__init__.py']}, - ] - }, - ] - } - ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': [ + 'foo-1.0-py{py_version}-nspkg.pth', + { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'namespace_packages.txt', + 'top_level.txt', + ] + }, + { + 'foo': [ + '__init__.py', + {'bar': ['__init__.py']}, + ] + }, + ] + }), ), dict( id='empty_namespace_package', @@ -499,27 +486,25 @@ def __repr__(self): namespace_packages=['foobar'], packages=['foobar'], ), - install_tree=flatten_tree( - { - 'foo-1.0-py{py_version}.egg': [ - 'foo-1.0-py{py_version}-nspkg.pth', - { - 'EGG-INFO': [ - 'PKG-INFO', - 'RECORD', - 'WHEEL', - 'namespace_packages.txt', - 'top_level.txt', - ] - }, - { - 'foobar': [ - '__init__.py', - ] - }, - ] - } - ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': [ + 'foo-1.0-py{py_version}-nspkg.pth', + { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'namespace_packages.txt', + 'top_level.txt', + ] + }, + { + 'foobar': [ + '__init__.py', + ] + }, + ] + }), ), dict( id='data_in_package', @@ -528,9 +513,9 @@ def __repr__(self): '__init__.py': '', 'data_dir': { 'data.txt': DALS( - ''' + """ Some data... - ''' + """ ), }, } @@ -539,26 +524,24 @@ def __repr__(self): packages=['foo'], data_files=[('foo/data_dir', ['foo/data_dir/data.txt'])], ), - install_tree=flatten_tree( - { - 'foo-1.0-py{py_version}.egg': { - 'EGG-INFO': [ - 'PKG-INFO', - 'RECORD', - 'WHEEL', - 'top_level.txt', - ], - 'foo': [ - '__init__.py', - { - 'data_dir': [ - 'data.txt', - ] - }, - ], - } + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + ], + 'foo': [ + '__init__.py', + { + 'data_dir': [ + 'data.txt', + ] + }, + ], } - ), + }), ), ) @@ -566,7 +549,7 @@ def __repr__(self): @pytest.mark.parametrize( 'params', WHEEL_INSTALL_TESTS, - ids=list(params['id'] for params in WHEEL_INSTALL_TESTS), + ids=[params['id'] for params in WHEEL_INSTALL_TESTS], ) def test_wheel_install(params): project_name = params.get('name', 'foo') @@ -577,42 +560,26 @@ def test_wheel_install(params): install_tree = params.get('install_tree') file_defs = params.get('file_defs', {}) setup_kwargs = params.get('setup_kwargs', {}) - with build_wheel( - name=project_name, - version=version, - install_requires=install_requires, - extras_require=extras_require, - extra_file_defs=file_defs, - **setup_kwargs - ) as filename, tempdir() as install_dir: + with ( + build_wheel( + name=project_name, + version=version, + install_requires=install_requires, + extras_require=extras_require, + extra_file_defs=file_defs, + **setup_kwargs, + ) as filename, + tempdir() as install_dir, + ): _check_wheel_install( filename, install_dir, install_tree, project_name, version, requires_txt ) -def test_wheel_install_pep_503(): - project_name = 'Foo_Bar' # PEP 503 canonicalized name is "foo-bar" - version = '1.0' - with build_wheel( - name=project_name, - version=version, - ) as filename, tempdir() as install_dir: - new_filename = filename.replace(project_name, canonicalize_name(project_name)) - shutil.move(filename, new_filename) - _check_wheel_install( - new_filename, - install_dir, - None, - canonicalize_name(project_name), - version, - None, - ) - - def test_wheel_no_dist_dir(): project_name = 'nodistinfo' version = '1.0' - wheel_name = '{0}-{1}-py2.py3-none-any.whl'.format(project_name, version) + wheel_name = f'{project_name}-{version}-py2.py3-none-any.whl' with tempdir() as source_dir: wheel_path = os.path.join(source_dir, wheel_name) # create an empty zip file @@ -641,12 +608,12 @@ def build_wheel(extra_file_defs=None, **kwargs): file_defs = { 'setup.py': ( DALS( - ''' + """ # -*- coding: utf-8 -*- from setuptools import setup import setuptools setup(**%r) - ''' + """ ) % kwargs ).encode('utf-8'), @@ -666,34 +633,32 @@ def build_wheel(extra_file_defs=None, **kwargs): id='script', file_defs={ 'script.py': DALS( - ''' + """ #/usr/bin/python print('hello world!') - ''' + """ ), 'script.sh': DALS( - ''' + """ #/bin/sh echo 'hello world!' - ''' + """ ), }, setup_kwargs=dict( scripts=['script.py', 'script.sh'], ), - install_tree=flatten_tree( - { - 'foo-1.0-py{py_version}.egg': { - 'EGG-INFO': [ - 'PKG-INFO', - 'RECORD', - 'WHEEL', - 'top_level.txt', - {'scripts': ['script.py', 'script.sh']}, - ] - } + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + {'scripts': ['script.py', 'script.sh']}, + ] } - ), + }), ) project_name = params.get('name', 'foo') @@ -702,14 +667,17 @@ def build_wheel(extra_file_defs=None, **kwargs): file_defs = params.get('file_defs', {}) setup_kwargs = params.get('setup_kwargs', {}) - with build_wheel( - name=project_name, - version=version, - install_requires=[], - extras_require={}, - extra_file_defs=file_defs, - **setup_kwargs - ) as filename, tempdir() as install_dir: + with ( + build_wheel( + name=project_name, + version=version, + install_requires=[], + extras_require={}, + extra_file_defs=file_defs, + **setup_kwargs, + ) as filename, + tempdir() as install_dir, + ): _check_wheel_install( filename, install_dir, install_tree, project_name, version, None ) diff --git a/setuptools/tests/test_windows_wrappers.py b/setuptools/tests/test_windows_wrappers.py index 4089634213..4f990eb1c3 100644 --- a/setuptools/tests/test_windows_wrappers.py +++ b/setuptools/tests/test_windows_wrappers.py @@ -11,16 +11,16 @@ the script they are to wrap and with the same name as the script they are to wrap. """ + import pathlib -import sys import platform -import textwrap import subprocess +import sys +import textwrap import pytest -from setuptools.command.easy_install import nt_quote_arg -import pkg_resources +from setuptools._importlib import resources pytestmark = pytest.mark.skipif(sys.platform != 'win32', reason="Windows only") @@ -28,7 +28,7 @@ class WrapperTester: @classmethod def prep_script(cls, template): - python_exe = nt_quote_arg(sys.executable) + python_exe = subprocess.list2cmdline([sys.executable]) return template % locals() @classmethod @@ -48,7 +48,7 @@ def create_script(cls, tmpdir): # also copy cli.exe to the sample directory with (tmpdir / cls.wrapper_name).open('wb') as f: - w = pkg_resources.resource_string('setuptools', cls.wrapper_source) + w = resources.files('setuptools').joinpath(cls.wrapper_source).read_bytes() f.write(w) @@ -56,9 +56,9 @@ def win_launcher_exe(prefix): """A simple routine to select launcher script based on platform.""" assert prefix in ('cli', 'gui') if platform.machine() == "ARM64": - return "{}-arm64.exe".format(prefix) + return f"{prefix}-arm64.exe" else: - return "{}-32.exe".format(prefix) + return f"{prefix}-32.exe" class TestCLI(WrapperTester): @@ -109,9 +109,13 @@ def test_basic(self, tmpdir): 'arg5 a\\\\b', ] proc = subprocess.Popen( - cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, text=True + cmd, + stdout=subprocess.PIPE, + stdin=subprocess.PIPE, + text=True, + encoding="utf-8", ) - stdout, stderr = proc.communicate('hello\nworld\n') + stdout, _stderr = proc.communicate('hello\nworld\n') actual = stdout.replace('\r\n', '\n') expected = textwrap.dedent( r""" @@ -142,9 +146,13 @@ def test_symlink(self, tmpdir): 'arg5 a\\\\b', ] proc = subprocess.Popen( - cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, text=True + cmd, + stdout=subprocess.PIPE, + stdin=subprocess.PIPE, + text=True, + encoding="utf-8", ) - stdout, stderr = proc.communicate('hello\nworld\n') + stdout, _stderr = proc.communicate('hello\nworld\n') actual = stdout.replace('\r\n', '\n') expected = textwrap.dedent( r""" @@ -190,8 +198,9 @@ def test_with_options(self, tmpdir): stdin=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, + encoding="utf-8", ) - stdout, stderr = proc.communicate() + stdout, _stderr = proc.communicate() actual = stdout.replace('\r\n', '\n') expected = textwrap.dedent( r""" @@ -239,6 +248,7 @@ def test_basic(self, tmpdir): stdin=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, + encoding="utf-8", ) stdout, stderr = proc.communicate() assert not stdout diff --git a/setuptools/unicode_utils.py b/setuptools/unicode_utils.py index e84e65e3e1..f502f5b089 100644 --- a/setuptools/unicode_utils.py +++ b/setuptools/unicode_utils.py @@ -1,5 +1,9 @@ -import unicodedata import sys +import unicodedata +from configparser import RawConfigParser + +from .compat import py39 +from .warnings import SetuptoolsDeprecationWarning # HFS Plus uses decomposed UTF-8 @@ -18,7 +22,7 @@ def decompose(path): def filesys_decode(path): """ Ensure that the given path is decoded, - NONE when no expected encoding works + ``None`` when no expected encoding works """ if isinstance(path, str): @@ -33,6 +37,8 @@ def filesys_decode(path): except UnicodeDecodeError: continue + return None + def try_encode(string, enc): "turn unicode encoding into a functional routine" @@ -40,3 +46,57 @@ def try_encode(string, enc): return string.encode(enc) except UnicodeEncodeError: return None + + +def _read_utf8_with_fallback(file: str, fallback_encoding=py39.LOCALE_ENCODING) -> str: + """ + First try to read the file with UTF-8, if there is an error fallback to a + different encoding ("locale" by default). Returns the content of the file. + Also useful when reading files that might have been produced by an older version of + setuptools. + """ + try: + with open(file, "r", encoding="utf-8") as f: + return f.read() + except UnicodeDecodeError: # pragma: no cover + _Utf8EncodingNeeded.emit(file=file, fallback_encoding=fallback_encoding) + with open(file, "r", encoding=fallback_encoding) as f: + return f.read() + + +def _cfg_read_utf8_with_fallback( + cfg: RawConfigParser, file: str, fallback_encoding=py39.LOCALE_ENCODING +) -> None: + """Same idea as :func:`_read_utf8_with_fallback`, but for the + :meth:`RawConfigParser.read` method. + + This method may call ``cfg.clear()``. + """ + try: + cfg.read(file, encoding="utf-8") + except UnicodeDecodeError: # pragma: no cover + _Utf8EncodingNeeded.emit(file=file, fallback_encoding=fallback_encoding) + cfg.clear() + cfg.read(file, encoding=fallback_encoding) + + +class _Utf8EncodingNeeded(SetuptoolsDeprecationWarning): + _SUMMARY = """ + `encoding="utf-8"` fails with {file!r}, trying `encoding={fallback_encoding!r}`. + """ + + _DETAILS = """ + Fallback behavior for UTF-8 is considered **deprecated** and future versions of + `setuptools` may not implement it. + + Please encode {file!r} with "utf-8" to ensure future builds will succeed. + + If this file was produced by `setuptools` itself, cleaning up the cached files + and re-building/re-installing the package with a newer version of `setuptools` + (e.g. by updating `build-system.requires` in its `pyproject.toml`) + might solve the problem. + """ + # TODO: Add a deadline? + # Will we be able to remove this? + # The question comes to mind mainly because of sdists that have been produced + # by old versions of setuptools and published to PyPI... diff --git a/setuptools/warnings.py b/setuptools/warnings.py index b3e252ca57..97f6971cf7 100644 --- a/setuptools/warnings.py +++ b/setuptools/warnings.py @@ -5,14 +5,19 @@ setuptools. """ +from __future__ import annotations + import os import warnings from datetime import date from inspect import cleandoc from textwrap import indent -from typing import Optional, Tuple +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing import TypeAlias -_DueDate = Tuple[int, int, int] # time tuple +_DueDate: TypeAlias = tuple[int, int, int] # time tuple _INDENT = 8 * " " _TEMPLATE = f"""{80 * '*'}\n{{details}}\n{80 * '*'}""" @@ -23,14 +28,14 @@ class SetuptoolsWarning(UserWarning): @classmethod def emit( cls, - summary: Optional[str] = None, - details: Optional[str] = None, - due_date: Optional[_DueDate] = None, - see_docs: Optional[str] = None, - see_url: Optional[str] = None, + summary: str | None = None, + details: str | None = None, + due_date: _DueDate | None = None, + see_docs: str | None = None, + see_url: str | None = None, stacklevel: int = 2, **kwargs, - ): + ) -> None: """Private: reserved for ``setuptools`` internal use only""" # Default values: summary_ = summary or getattr(cls, "_SUMMARY", None) or "" @@ -51,10 +56,10 @@ def _format( cls, summary: str, details: str, - due_date: Optional[date] = None, - see_url: Optional[str] = None, - format_args: Optional[dict] = None, - ): + due_date: date | None = None, + see_url: str | None = None, + format_args: dict | None = None, + ) -> str: """Private: reserved for ``setuptools`` internal use only""" today = date.today() summary = cleandoc(summary).format_map(format_args or {}) diff --git a/setuptools/wheel.py b/setuptools/wheel.py index c6eabddc1f..9366303154 100644 --- a/setuptools/wheel.py +++ b/setuptools/wheel.py @@ -1,23 +1,29 @@ """Wheels support.""" +import contextlib import email -import itertools import functools +import itertools import os import posixpath import re import zipfile -import contextlib +from collections.abc import Iterator -from distutils.util import get_platform +from packaging.requirements import Requirement +from packaging.tags import sys_tags +from packaging.utils import canonicalize_name +from packaging.version import Version as parse_version import setuptools -from setuptools.extern.packaging.version import Version as parse_version -from setuptools.extern.packaging.tags import sys_tags -from setuptools.extern.packaging.utils import canonicalize_name -from setuptools.command.egg_info import write_requirements, _egg_basename from setuptools.archive_util import _unpack_zipfile_obj +from setuptools.command.egg_info import _egg_basename, write_requirements +from ._discovery import extras_from_deps +from ._importlib import metadata +from .unicode_utils import _read_utf8_with_fallback + +from distutils.util import get_platform WHEEL_NAME = re.compile( r"""^(?P.+?)-(?P\d.*?) @@ -29,7 +35,7 @@ NAMESPACE_PACKAGE_INIT = "__import__('pkg_resources').declare_namespace(__name__)\n" -@functools.lru_cache(maxsize=None) +@functools.cache def _get_supported_tags(): # We calculate the supported tags only once, otherwise calling # this method on thousands of wheels takes seconds instead of @@ -37,8 +43,8 @@ def _get_supported_tags(): return {(t.interpreter, t.abi, t.platform) for t in sys_tags()} -def unpack(src_dir, dst_dir): - '''Move everything under `src_dir` to `dst_dir`, and delete the former.''' +def unpack(src_dir, dst_dir) -> None: + """Move everything under `src_dir` to `dst_dir`, and delete the former.""" for dirpath, dirnames, filenames in os.walk(src_dir): subdir = os.path.relpath(dirpath, src_dir) for f in filenames: @@ -60,7 +66,7 @@ def unpack(src_dir, dst_dir): @contextlib.contextmanager -def disable_info_traces(): +def disable_info_traces() -> Iterator[None]: """ Temporarily disable info traces. """ @@ -74,16 +80,16 @@ def disable_info_traces(): class Wheel: - def __init__(self, filename): + def __init__(self, filename) -> None: match = WHEEL_NAME(os.path.basename(filename)) if match is None: - raise ValueError('invalid wheel name: %r' % filename) + raise ValueError(f'invalid wheel name: {filename!r}') self.filename = filename for k, v in match.groupdict().items(): setattr(self, k, v) def tags(self): - '''List tags (py_version, abi, platform) supported by this wheel.''' + """List tags (py_version, abi, platform) supported by this wheel.""" return itertools.product( self.py_version.split('.'), self.abi.split('.'), @@ -91,7 +97,7 @@ def tags(self): ) def is_compatible(self): - '''Is the wheel compatible with the current platform?''' + """Is the wheel compatible with the current platform?""" return next((True for t in self.tags() if t in _get_supported_tags()), False) def egg_name(self): @@ -114,15 +120,15 @@ def get_dist_info(self, zf): return dirname raise ValueError("unsupported wheel format. .dist-info not found") - def install_as_egg(self, destination_eggdir): - '''Install wheel as an egg directory.''' + def install_as_egg(self, destination_eggdir) -> None: + """Install wheel as an egg directory.""" with zipfile.ZipFile(self.filename) as zf: self._install_as_egg(destination_eggdir, zf) def _install_as_egg(self, destination_eggdir, zf): - dist_basename = '%s-%s' % (self.project_name, self.version) + dist_basename = f'{self.project_name}-{self.version}' dist_info = self.get_dist_info(zf) - dist_data = '%s.data' % dist_basename + dist_data = f'{dist_basename}.data' egg_info = os.path.join(destination_eggdir, 'EGG-INFO') self._convert_metadata(zf, destination_eggdir, dist_info, egg_info) @@ -131,8 +137,6 @@ def _install_as_egg(self, destination_eggdir, zf): @staticmethod def _convert_metadata(zf, destination_eggdir, dist_info, egg_info): - import pkg_resources - def get_metadata(name): with zf.open(posixpath.join(dist_info, name)) as fp: value = fp.read().decode('utf-8') @@ -143,33 +147,13 @@ def get_metadata(name): wheel_version = parse_version(wheel_metadata.get('Wheel-Version')) wheel_v1 = parse_version('1.0') <= wheel_version < parse_version('2.0dev0') if not wheel_v1: - raise ValueError('unsupported wheel format version: %s' % wheel_version) + raise ValueError(f'unsupported wheel format version: {wheel_version}') # Extract to target directory. _unpack_zipfile_obj(zf, destination_eggdir) - # Convert metadata. dist_info = os.path.join(destination_eggdir, dist_info) - dist = pkg_resources.Distribution.from_location( - destination_eggdir, - dist_info, - metadata=pkg_resources.PathMetadata(destination_eggdir, dist_info), + install_requires, extras_require = Wheel._convert_requires( + destination_eggdir, dist_info ) - - # Note: Evaluate and strip markers now, - # as it's difficult to convert back from the syntax: - # foobar; "linux" in sys_platform and extra == 'test' - def raw_req(req): - req.marker = None - return str(req) - - install_requires = list(map(raw_req, dist.requires())) - extras_require = { - extra: [ - req - for req in map(raw_req, dist.requires((extra,))) - if req not in install_requires - ] - for extra in dist.extras - } os.rename(dist_info, egg_info) os.rename( os.path.join(egg_info, 'METADATA'), @@ -188,6 +172,50 @@ def raw_req(req): os.path.join(egg_info, 'requires.txt'), ) + @staticmethod + def _convert_requires(destination_eggdir, dist_info): + md = metadata.Distribution.at(dist_info).metadata + deps = md.get_all('Requires-Dist') or [] + reqs = list(map(Requirement, deps)) + + extras = extras_from_deps(deps) + + # Note: Evaluate and strip markers now, + # as it's difficult to convert back from the syntax: + # foobar; "linux" in sys_platform and extra == 'test' + def raw_req(req): + req = Requirement(str(req)) + req.marker = None + return str(req) + + def eval(req, **env): + return not req.marker or req.marker.evaluate(env) + + def for_extra(req): + try: + markers = req.marker._markers + except AttributeError: + markers = () + return set( + marker[2].value + for marker in markers + if isinstance(marker, tuple) and marker[0].value == 'extra' + ) + + install_requires = list( + map(raw_req, filter(eval, itertools.filterfalse(for_extra, reqs))) + ) + extras_require = { + extra: list( + map( + raw_req, + (req for req in reqs if for_extra(req) and eval(req, extra=extra)), + ) + ) + for extra in extras + } + return install_requires, extras_require + @staticmethod def _move_data_entries(destination_eggdir, dist_data): """Move data entries to their correct location.""" @@ -222,13 +250,13 @@ def _move_data_entries(destination_eggdir, dist_data): def _fix_namespace_packages(egg_info, destination_eggdir): namespace_packages = os.path.join(egg_info, 'namespace_packages.txt') if os.path.exists(namespace_packages): - with open(namespace_packages) as fp: - namespace_packages = fp.read().split() + namespace_packages = _read_utf8_with_fallback(namespace_packages).split() + for mod in namespace_packages: mod_dir = os.path.join(destination_eggdir, *mod.split('.')) mod_init = os.path.join(mod_dir, '__init__.py') if not os.path.exists(mod_dir): os.mkdir(mod_dir) if not os.path.exists(mod_init): - with open(mod_init, 'w') as fp: + with open(mod_init, 'w', encoding="utf-8") as fp: fp.write(NAMESPACE_PACKAGE_INIT) diff --git a/setuptools/windows_support.py b/setuptools/windows_support.py index fdadeb597c..7a2b53a291 100644 --- a/setuptools/windows_support.py +++ b/setuptools/windows_support.py @@ -8,17 +8,17 @@ def windows_only(func): @windows_only -def hide_file(path): +def hide_file(path: str) -> None: """ Set the hidden attribute on a file or directory. - From http://stackoverflow.com/questions/19622133/ + From https://stackoverflow.com/questions/19622133/ `path` must be text. """ import ctypes + import ctypes.wintypes - __import__('ctypes.wintypes') SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD SetFileAttributes.restype = ctypes.wintypes.BOOL diff --git a/tools/build_launchers.py b/tools/build_launchers.py index 26d3913e00..48609367a0 100644 --- a/tools/build_launchers.py +++ b/tools/build_launchers.py @@ -17,15 +17,14 @@ - C++ ATL for latest v143 build tools (ARM64) """ -import os import functools import itertools +import os import pathlib import shutil import subprocess import tempfile - BUILD_TARGETS = ["cli", "gui"] GUI = {"cli": 0, "gui": 1} BUILD_PLATFORMS = ["Win32", "x64", "arm64"] @@ -55,13 +54,13 @@ """ -def resolve_platform(platform: str): +def resolve_platform(platform: str) -> str: if platform in ["Win32", "x64"]: return platform[-2:] return platform -def get_executable_name(name, platform: str): +def get_executable_name(name, platform: str) -> str: return f"{name}-{resolve_platform(platform)}" @@ -86,7 +85,7 @@ def build_cmake_project_with_msbuild(build_arena, msbuild_parameters): subprocess.check_call(cmd, cwd=build_arena) -@functools.lru_cache() +@functools.lru_cache def get_cmake(): """Find CMake using registry.""" import winreg @@ -96,7 +95,7 @@ def get_cmake(): return root / 'bin\\CMake.exe' -@functools.lru_cache() +@functools.lru_cache def get_msbuild(): """Use VSWhere to find MSBuild.""" vswhere = pathlib.Path( @@ -118,8 +117,8 @@ def get_msbuild(): ] try: return subprocess.check_output(cmd, encoding='utf-8', text=True).strip() - except subprocess.CalledProcessError: - raise SystemExit("Unable to find MSBuild; check Visual Studio install") + except subprocess.CalledProcessError as e: + raise SystemExit("Unable to find MSBuild; check Visual Studio install") from e def do_build(arena, platform, target): diff --git a/tools/finalize.py b/tools/finalize.py index f79f5b3b45..27471c7e25 100644 --- a/tools/finalize.py +++ b/tools/finalize.py @@ -5,14 +5,13 @@ __requires__ = ['bump2version', 'towncrier', 'jaraco.develop>=7.21'] -import subprocess import pathlib import re +import subprocess import sys from jaraco.develop import towncrier - bump_version_command = [ sys.executable, '-m', @@ -23,7 +22,7 @@ def get_version(): cmd = bump_version_command + ['--dry-run', '--verbose'] - out = subprocess.check_output(cmd, text=True) + out = subprocess.check_output(cmd, text=True, encoding='utf-8') return re.search('^new_version=(.*)', out, re.MULTILINE).group(1) @@ -38,7 +37,7 @@ def _repair_changelog(): """ changelog_fn = pathlib.Path('NEWS.rst') changelog = changelog_fn.read_text(encoding='utf-8') - fixed = re.sub(r'^(v[0-9.]+)v[0-9.]+$', r'\1', changelog, flags=re.M) + fixed = re.sub(r'^(v[0-9.]+)v[0-9.]+$', r'\1', changelog, flags=re.MULTILINE) changelog_fn.write_text(fixed, encoding='utf-8') subprocess.check_output(['git', 'add', changelog_fn]) diff --git a/tools/generate_validation_code.py b/tools/generate_validation_code.py index 53bc8ad650..157693de65 100644 --- a/tools/generate_validation_code.py +++ b/tools/generate_validation_code.py @@ -1,30 +1,39 @@ +from __future__ import annotations + +import itertools import subprocess import sys - +from collections.abc import Iterable from pathlib import Path -def generate_pyproject_validation(dest: Path): +def generate_pyproject_validation(dest: Path, schemas: Iterable[Path]) -> bool: """ Generates validation code for ``pyproject.toml`` based on JSON schemas and the ``validate-pyproject`` library. """ + schema_args = (("-t", f"{f.name.partition('.')[0]}={f}") for f in schemas) cmd = [ sys.executable, "-m", - "validate_pyproject.vendoring", + "validate_pyproject.pre_compile", f"--output-dir={dest}", "--enable-plugins", "setuptools", "distutils", "--very-verbose", + *itertools.chain.from_iterable(schema_args), ] subprocess.check_call(cmd) print(f"Validation code generated at: {dest}") + return True -def main(): - generate_pyproject_validation(Path("setuptools/config/_validate_pyproject")) +def main() -> bool: + return generate_pyproject_validation( + Path("setuptools/config/_validate_pyproject"), + schemas=Path("setuptools/config").glob("*.schema.json"), + ) __name__ == '__main__' and main() diff --git a/tools/ppc64le-patch.py b/tools/ppc64le-patch.py deleted file mode 100644 index 2a8ff8e0a0..0000000000 --- a/tools/ppc64le-patch.py +++ /dev/null @@ -1,28 +0,0 @@ -""" -Except on bionic, Travis Linux base image for PPC64LE -platform lacks the proper -permissions to the directory ~/.cache/pip/wheels that allow -the user running travis build to install pip packages. -TODO: is someone tracking this issue? Maybe just move to bionic? -""" - -import subprocess -import collections -import os - - -def patch(): - env = collections.defaultdict(str, os.environ) - if env['TRAVIS_CPU_ARCH'] != 'ppc64le': - return - cmd = [ - 'sudo', - 'chown', - '-Rfv', - '{USER}:{GROUP}'.format_map(env), - os.path.expanduser('~/.cache/pip/wheels'), - ] - subprocess.Popen(cmd) - - -__name__ == '__main__' and patch() diff --git a/tools/vendored.py b/tools/vendored.py index 9b7cf729ba..4cbc3b2c6b 100644 --- a/tools/vendored.py +++ b/tools/vendored.py @@ -1,149 +1,77 @@ +import functools import re -import sys import subprocess +import jaraco.packaging.metadata from path import Path def remove_all(paths): for path in paths: - path.rmtree() if path.isdir() else path.remove() + path.rmtree() if path.is_dir() else path.remove() def update_vendored(): - update_pkg_resources() update_setuptools() -def rewrite_packaging(pkg_files, new_root): - """ - Rewrite imports in packaging to redirect to vendored copies. - """ - for file in pkg_files.glob('*.py'): - text = file.text() - text = re.sub(r' (pyparsing)', rf' {new_root}.\1', text) - text = text.replace( - 'from six.moves.urllib import parse', - 'from urllib import parse', - ) - file.write_text(text) - - -def rewrite_jaraco_text(pkg_files, new_root): +def clean(vendor): """ - Rewrite imports in jaraco.text to redirect to vendored copies. + Remove all files out of the vendor directory except the meta + data (as pip uninstall doesn't support -t). """ - for file in pkg_files.glob('*.py'): - text = file.read_text() - text = re.sub(r' (jaraco\.)', rf' {new_root}.\1', text) - text = re.sub(r' (importlib_resources)', rf' {new_root}.\1', text) - # suppress loading of lorem_ipsum; ref #3072 - text = re.sub(r'^lorem_ipsum.*\n$', '', text, flags=re.M) - file.write_text(text) + ignored = ['ruff.toml'] + remove_all(path for path in vendor.glob('*') if path.basename() not in ignored) -def rewrite_jaraco(pkg_files, new_root): - """ - Rewrite imports in jaraco.functools to redirect to vendored copies. - """ - for file in pkg_files.glob('*.py'): - text = file.read_text() - text = re.sub(r' (more_itertools)', rf' {new_root}.\1', text) - file.write_text(text) - # required for zip-packaged setuptools #3084 - pkg_files.joinpath('__init__.py').write_text('') +@functools.lru_cache +def metadata(): + return jaraco.packaging.metadata.load('.') -def rewrite_importlib_resources(pkg_files, new_root): +def upgrade_core(dep): """ - Rewrite imports in importlib_resources to redirect to vendored copies. + Remove 'extra == "core"' from any dependency. """ - for file in pkg_files.glob('*.py'): - text = file.read_text().replace('importlib_resources.abc', '.abc') - text = text.replace('zipp', '..zipp') - file.write_text(text) + return re.sub('''(;| and) extra == ['"]core['"]''', '', dep) -def rewrite_importlib_metadata(pkg_files, new_root): +def load_deps(): """ - Rewrite imports in importlib_metadata to redirect to vendored copies. + Read the dependencies from `.[core]`. """ - for file in pkg_files.glob('*.py'): - text = file.read_text().replace('typing_extensions', '..typing_extensions') - text = text.replace('import zipp', 'from .. import zipp') - file.write_text(text) + return list(map(upgrade_core, metadata().get_all('Requires-Dist'))) -def rewrite_more_itertools(pkg_files: Path): - """ - Defer import of concurrent.futures. Workaround for #3090. - """ - more_file = pkg_files.joinpath('more.py') - text = more_file.read_text() - text = re.sub(r'^.*concurrent.futures.*?\n', '', text, flags=re.MULTILINE) - text = re.sub( - 'ThreadPoolExecutor', - '__import__("concurrent.futures").futures.ThreadPoolExecutor', - text, - ) - more_file.write_text(text) - - -def rewrite_platformdirs(pkg_files: Path): - """ - Replace some absolute imports with relative ones. - """ - init = pkg_files.joinpath('__init__.py') - text = init.read_text() - text = text.replace('from platformdirs.', 'from .') - text = text.replace('from typing_extensions', 'from ..typing_extensions') - init.write_text(text) +def min_python(): + return metadata()['Requires-Python'].removeprefix('>=').strip() -def clean(vendor): +def install_deps(deps, vendor): """ - Remove all files out of the vendor directory except the meta - data (as pip uninstall doesn't support -t). + Install the deps to vendor. """ - remove_all(path for path in vendor.glob('*') if path.basename() != 'vendored.txt') - - -def install(vendor): - clean(vendor) install_args = [ - sys.executable, - '-m', + 'uv', 'pip', 'install', - '-r', - str(vendor / 'vendored.txt'), - '-t', + '--target', str(vendor), - ] + '--python-version', + min_python(), + '--only-binary', + ':all:', + ] + list(deps) subprocess.check_call(install_args) - (vendor / '__init__.py').write_text('') - - -def update_pkg_resources(): - vendor = Path('pkg_resources/_vendor') - install(vendor) - rewrite_packaging(vendor / 'packaging', 'pkg_resources.extern') - rewrite_jaraco_text(vendor / 'jaraco/text', 'pkg_resources.extern') - rewrite_jaraco(vendor / 'jaraco', 'pkg_resources.extern') - rewrite_importlib_resources(vendor / 'importlib_resources', 'pkg_resources.extern') - rewrite_more_itertools(vendor / "more_itertools") - rewrite_platformdirs(vendor / "platformdirs") def update_setuptools(): vendor = Path('setuptools/_vendor') - install(vendor) - rewrite_packaging(vendor / 'packaging', 'setuptools.extern') - rewrite_jaraco_text(vendor / 'jaraco/text', 'setuptools.extern') - rewrite_jaraco(vendor / 'jaraco', 'setuptools.extern') - rewrite_importlib_resources(vendor / 'importlib_resources', 'setuptools.extern') - rewrite_importlib_metadata(vendor / 'importlib_metadata', 'setuptools.extern') - rewrite_more_itertools(vendor / "more_itertools") + deps = load_deps() + clean(vendor) + install_deps(deps, vendor) + # uv only installs non-portable shebangs (#5159) + (vendor / 'bin').rmtree() __name__ == '__main__' and update_vendored() diff --git a/towncrier.toml b/towncrier.toml index 9505e57db6..577e87a793 100644 --- a/towncrier.toml +++ b/towncrier.toml @@ -1,4 +1,3 @@ [tool.towncrier] title_format = "{version}" -# workaround for sphinx-contrib/sphinxcontrib-towncrier#83 -directory = "newsfragments" +directory = "newsfragments" # jaraco/skeleton#184 diff --git a/tox.ini b/tox.ini index 783827d26e..bcee70d589 100644 --- a/tox.ini +++ b/tox.ini @@ -1,32 +1,35 @@ [testenv] +description = perform primary checks (tests, style, types, coverage) deps = # Ideally all the dependencies should be set as "extras" - build[virtualenv] @ git+https://github.com/pypa/build@59c1f87 - # ^-- pypa/build#630, use dev version while we wait for the new release - packaging @ git+https://github.com/pypa/packaging@7e68d82 - # ^-- use dev version while we wait for the new release setenv = PYTHONWARNDEFAULTENCODING = 1 - SETUPTOOLS_ENFORCE_DEPRECATION = 1 + SETUPTOOLS_ENFORCE_DEPRECATION = {env:SETUPTOOLS_ENFORCE_DEPRECATION:0} # TODO: return to 1 (temporarily disabled) commands = pytest {posargs} usedevelop = True extras = - testing -passenv = + test + check + cover + enabler + type + core +pass_env = SETUPTOOLS_USE_DISTUTILS + SETUPTOOLS_ENFORCE_DEPRECATION PRE_BUILT_SETUPTOOLS_WHEEL PRE_BUILT_SETUPTOOLS_SDIST TIMEOUT_BACKEND_TEST # timeout (in seconds) for test_build_meta - windir # required for test_pkg_resources + SSH_AUTH_SOCK # for exercise.py if repo was checked out with ssh # honor git config in pytest-perf HOME [testenv:integration] deps = {[testenv]deps} -extras = testing-integration -passenv = - {[testenv]passenv} +extras = {[testenv]extras} +pass_env = + {[testenv]pass_env} DOWNLOAD_PATH setenv = PROJECT_ROOT = {toxinidir} @@ -34,25 +37,34 @@ commands = pytest --integration {posargs:-vv --durations=10} setuptools/tests/integration # use verbose mode by default to facilitate debugging from CI logs +[testenv:diffcov] +description = run tests and check that diff from main is covered +deps = + {[testenv]deps} + diff-cover +commands = + pytest {posargs} --cov-report xml + diff-cover coverage.xml --compare-branch=origin/main --format html:diffcov.html + diff-cover coverage.xml --compare-branch=origin/main --fail-under=100 + [testenv:docs] +description = build the documentation extras = - docs - testing + doc + test changedir = docs -deps = - importlib_resources < 6 # twisted/towncrier#528 (waiting for release) commands = python -m sphinx -W --keep-going . {toxinidir}/build/html python -m sphinxlint [testenv:finalize] +description = assemble changelog and tag a release skip_install = True deps = towncrier bump2version jaraco.develop >= 7.23 - importlib_resources < 6 # twisted/towncrier#528 (waiting for release) -passenv = * +pass_env = * commands = python tools/finalize.py @@ -60,31 +72,35 @@ commands = skip_install = True deps = path + jaraco.packaging + # workaround for pypa/pyproject-hooks#192 + pyproject-hooks!=1.1 + uv commands = - python -m tools.vendored + vendor: python -m tools.vendored [testenv:generate-validation-code] skip_install = True deps = - validate-pyproject[all]==0.12.2 + validate-pyproject[all]==0.25 commands = python -m tools.generate_validation_code [testenv:release] +description = publish the package to PyPI and GitHub skip_install = True deps = build + pyproject-hooks!=1.1 # workaround for pypa/setuptools#4333 twine>=3 jaraco.develop>=7.1 -passenv = +pass_env = TWINE_PASSWORD GITHUB_TOKEN setenv = TWINE_USERNAME = {env:TWINE_USERNAME:__token__} commands = python -c "import shutil; shutil.rmtree('dist', ignore_errors=True)" - # unset tag_build and tag_date pypa/setuptools#2500 - python setup.py egg_info -Db "" saveopts python -m build python -m twine upload dist/* python -m jaraco.develop.create-github-release